一.获取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();