我们知道,在公众号的开发中,有很多接口需要access_token才能访问,但是如果每次需要用到access_token的时候,都通过appid和appsecret去获得access_token,又有些资源浪费,毕竟,每个access_token的有效期都是7200秒,所以就只好通过将access_token通过保存文件的方式缓存下来,每次需要用到access_token的时候直接读取文件,如果token没有过期,那么就不去向微信服务器请求新的access_token,这样就很方便了,毕竟,关注用户多的时候,2000次的请求次数根本不够用。
目标:将获得的access_token保存到.properties文件中,每次请求access_token的时候,优先读取properties文件,判断token是否过期,如果已过期,重新想微信服务器发送请求获得access_token,否则,直接返回文件中保存的access_token。
首先,是Properties.php文件类的代码,Properties类提供读取属性、修改属性的方法,类似传统的properties文件,每个属性设置一行,用“=”号隔开,如下:
<?php
/*
* 科学改变世界
* CopyRight 2018- All Rights Reserved
* Properties文件相关操作:
* -打开文件
* -读取属性设置
* -修改属性设置
* -保存文件
*/
class Properties{
private $_path;
private $_properties;
//打开文件
public function openFile($_file){
$this->_path = fopen($_file, "r+") or exit("Unable to open file!");
stream_set_timeout($this->_path, 0);
$this->_properties = array();
if( flock($this->_path, LOCK_EX) ){//加写锁
while(!feof($this->_path))
{
$keywords = fgets($this->_path);
$line = preg_replace('/\n|\r\n/','',$keywords);
if($line != ''){
$key_value = explode('=', $line);
$this->_properties[] = $key_value;
}
}
ftruncate($this->_path,0); // 将文件截断到给定的长度
rewind($this->_path); // 倒回文件指针的位置
flock($this->_path, LOCK_UN); //解锁
}
}
//读取文件属性
public function getProperty($_key){
$exist = FALSE;
foreach ($this->_properties as $val) {
if($val[0] == $_key){
$exist = TRUE;
return $val[1];
}
}
if(!$exist){
return 'NO EXISTS.';
}
}
//设置文件属性
public function setProperty($_key, $_value){
$exist = FALSE;
for($_i=0; $_i<count($this->_properties); $_i++){
$_item = $this->_properties[$_i];
if($_item[0] == $_key){
$exist = TRUE;
$_item[1] = $_value;
$this->_properties[$_i] = $_item;
}
}
if(!$exist){
$this->_properties[] = array($_key, $_value);
return TRUE;
}
}
//保存文件
public function saveFile(){
$contents = '';
foreach ($this->_properties as $val) {
$_line = implode('=', $val);
$contents = $contents.$_line."\r\n";
}
fwrite($this->_path, $contents);
fclose($this->_path);
}
}
?>
在服务器同一目录下,我们再创建一个token.php文件,这个文件用于接收get请求并返回token,代码如下:
<?php
/*
* 科学改变世界
* CopyRight 2018- All Rights Reserved
* token相关操作:
* -url请求获得token并保存
* -token有效期内直接读取文件获得token
*/
// 引入属性类
include 'Properties.php';
class Token
{
// 定义AppId和AppSecret
// 请自行修改为自己公众号的appId和appSecret
private $AppId = 'AppId';
private $AppSecret = 'AppSecret ';
//获取access_token
private function getAccessToken()
{
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->AppId . "&secret=" . $this->AppSecret;
//通过自定义函数getCurl得到https的内容
$data = getCurl($url);
//转为数组
$resultArr = json_decode($data, true);
//获取access_token
return $resultArr["access_token"];
}
// 获得token
public function getToken()
{
$tokenFile = __DIR__.'/conf/token.conf';
$prop = new Properties();
$prop->openFile($tokenFile);
$token_way = $prop->getProperty('way');
$token_create = $prop->getProperty('create');
// 如果token失效,就重新申请token
if((intval($token_create)+7200) < time()) {
$token = $this -> getAccessToken();
$prop->setProperty('token', $token);
$prop->setProperty('create', time());
}else {
$token = $prop->getProperty('token');
}
$prop->saveFile();
return $token;
}
}
function getCurl($url) {//get https的内容
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//不输出内容
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$response = [
'code' => 200,
'token' => (new Token())->getToken()
];
echo json_encode($response, TRUE);
?>
同样的,在当前目录下新建文件夹conf,并在里面新建token.conf文件,每次需要用到access_token的时候直接访问token.php文件就可以了。