微信开发-access_token 过期解决方法
2015-11-14 15:55
609 查看
微信提供了丰富发的开发接口(如包括自定义菜单接口、客服接口、获取用户信息接口),调用这些接口时需要传入 access_token,它是访问接口的凭证. 但access_token 时效只有7200s , 目前,获取access_token接口的调用频率限制为2000次/天.
如果每次使用接口前先获取一遍access_token,这显然不合理.
解决思路很简单:创建一个xml格式的文件,保存access_token,如果超时则更新.
创建xml文件
构建获取access_token 类
需要获取acctoken 时调用格式如下
$acc = new access_token();
$access_token = $acc
如果每次使用接口前先获取一遍access_token,这显然不合理.
解决思路很简单:创建一个xml格式的文件,保存access_token,如果超时则更新.
创建xml文件
<?xml version="1.0" encoding="UTF-8"?> <access_token_save> <appid>填写appid</appid> <appsecret>填写 appsecret</span></appsecret> <access_token>填写accesstoken</access_token> <time>填写更新时间戳</time> </access_token_save>
构建获取access_token 类
class access_token { private $xml = array();//存储xml文件信息 private $url ='xml文件路径';
/*构造函数*/ function __construct() { $this->read_xml(); $this->judge_access_token_act(); } /*读取xml文件*/ private function read_xml() { $xml = simplexml_load_file($this->url); foreach ($xml as $k => $v) { $this->xml[$k] = trim((string)$v); } } /*更新xml文件*/ private function write_xml() { $xml = simplexml_load_file($this->url); $xml->time = time(); $xml->access_token = $this->xml['access_token']; $file = fopen($this->url,"w"); fwrite($file,$xml->asXML()); fclose($file); } /*获取access_token*/ private function set_access_token() { $appid = $this->xml['appid']; $appsecret = $this->xml['appsecret']; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret"; $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, $url); curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec( $ch); curl_close( $ch); $jsoninfo = json_decode( $output, true); $this->xml['access_token'] = $jsoninfo["access_token"]; } /*判断access_token是否超时*/ private function judge_access_token_act(){ $time = time() - (int)$this->xml['time']; if($time >= 1800){ $this->set_access_token(); $this->write_xml(); }else{ $this->access_token = $this->xml['access_token']; } } /*获取access_token*/ function __toString() { return $this->xml['access_token']; } }
需要获取acctoken 时调用格式如下
$acc = new access_token();
$access_token = $acc
相关文章推荐
- 微信公众平台解决用户无状态问题
- js判断是否在微信浏览器中打开
- (支付宝微信支付案例报错)
- Android案例(4)——微信6.0主界面
- CC254X IBEACON开发
- PHP常用的小程序代码段
- 微信分享回调
- 拉上微信做转转,58赶集要重构二手业务,终于认真了?
- 微信token验证代码
- 微信公众号开发API接口大全
- 为什么企业微信公众号都流行做二次开发?
- PHP常用的小程序代码段
- Java五子棋控制台小程序
- 微信在未来智能家居中竟然可以这样用?
- 曾推动微信运动成为潮流的乐心,想要用小米模式跟传统医疗说不
- 动手动脑之小程序:TryAndCatch
- 高仿微信短视频拍摄功能的demo下载
- 025.ArrayList中的方法.续
- 微信支付中xml和map互转
- 微信公众平台开发 - OAuth2.0网页授权