第三节 利用curl获取access_token和微信服务器地址

一.获取access_token

自动更新access_token

//获取access_token(支持自动更新凭证)
public function get_access_token()
{
  $res = file_get_contents('access_token.json');//打开文件获取文件内容
  $result = json_decode($res, true);    //把文件内容json格式转换成数组
  $this->expires_time = $result["expires_time"];
  $this->access_token = $result["access_token"];
  if(time() > ($this->expires_time + 7200)){
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";   
    $result = $this->https_request($url);//调用curl模拟请求方法
    $this->access_token = $result["access_token"];
    $this->expires_time = time();
    file_put_contents('access_token.json', '{"access_token": "'.$this->access_token.'", "expires_time": '.$this->expires_time.'}');
        }//把新的access_token值写入文件中
  return $this->access_token;//返回access_token值
}

//https请求(支持GET和POST)
protected function https_request($url,$data = null)
{
  $ch = curl_init();
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  if(!empty($data))
  {
    curl_setopt($ch,CURLOPT_POST,1);//模拟POST
    curl_setopt($ch,CURLOPT_POSTFIELDS,$data);//POST内容
  }
  $outopt = curl_exec($ch);
  curl_close($ch);
  $outopt = json_decode($outopt,true);
return $outopt;
}

二.获取微信服务器地址

function getWxServerIp(){
    $accessToken = '055hsH2RgwIRtLYMcm3LPXs82VwHb23a5q1mgF7jaFGEl3pmwlEsn_JJcljAAr91KvgpzANG6bGukKlm_9SzW9SKdni4415t_CU9LbHUCj2VXwW60LtcvjuM2XbnmLupQDYcAIAYLG';
    $url='https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token='.$accessToken;
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    $res = curl_exec($ch);
    curl_close($ch);
    if(curl_errno($ch)){
        var_dump(curl_error($ch));
    }
    $arr = json_decode($res,true);
    echo '<pre>';
    var_dump($arr);
    echo '</pre>';
}
getWxServerIp();

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值