微信提供了丰富发的开发接口(如包括自定义菜单接口、客服接口、获取用户信息接口),调用这些接口时需要传入 access_token,它是访问接口的凭证. 但access_token 时效只有7200s , 目前,获取access_token接口的调用频率限制为2000次/天. 如果每次使用接口前先获取一遍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'];
}
}
$acc = new access_token();
$access_token = $acc