PHP 获取微信access_token

接口调用请求说明

https请求方式: GEThttps://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

参数说明

参数 是否必须 说明
grant_type 获取access_token填写client_credential
appid 第三方用户唯一凭证
secret 第三方用户唯一凭证密钥,即appsecret

返回说明

正常情况下,微信会返回下述JSON数据包给公众号:

{"access_token":"ACCESS_TOKEN","expires_in":7200}

参数说明

参数 说明
access_token 获取到的凭证
expires_in 凭证有效时间,单位:秒

以上是微信的公众号获取access_token文档,本章简单说下php获取token的方法和要注意的地方

1.准备的参数需要公众号的appid和secret这2个信息,同时要注意的是secret更改后你保存的也需要更改,所以不建议更改,保存好即可。

2.需要设置白名单,可以根据服务器的ip地址获取,如果实在不知道的,也没关系,因为你可以根据微信接口的报错来知道自己的ip然后设置进去。

3.access_token每天调用的次数有效,没记错的话是2K次一天,但是一个token的有效期的2小时,所以我们必须将一个token缓存起来2小时,这样才不会超过接口的调用次数。

<?phppublic function getAccessToken($appid,$secret){$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";$res = $this->curl_get($url);$res = json_decode($res,1);if($res['errcode']!=0) throw new Exception($res['errmsg']);return $res['access_token'];}public function curl_get($url) {$headers = array('User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36');$oCurl = curl_init();if(stripos($url,"https://")!==FALSE){curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1}curl_setopt($oCurl, CURLOPT_TIMEOUT, 20);curl_setopt($oCurl, CURLOPT_URL, $url);curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );$sContent = curl_exec($oCurl);$aStatus = curl_getinfo($oCurl);curl_close($oCurl);if(intval($aStatus["http_code"])==200){return $sContent;}else{return false;}}

 以上就是php获取token的代码,相对来说难度比较低。

上一篇:PHP curl模拟用户登陆获取数据


下一篇:PHP curl多线程