您好,欢迎访问一九零五行业门户网

PHP怎么获取微信access_token

php获取微信“access_token”的方法:首先保存好公众号的appid和secret;然后设置白名单;接着将一个token缓存起来;最后通过“getaccesstoken”获取微信“access_token”即可。
php怎么获取微信access_token?
接口调用请求说明
https请求方式: get
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appid&secret=appsecret
参数说明
参数是否必须说明grant_type是获取access_token填写client_credentialappid是第三方用户唯一凭证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小时,这样才不会超过接口的调用次数。
<?php public 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的代码,相对来说难度比较低。
更多相关技术知识,请访问!
其它类似信息

推荐信息