首页 > 代码库 > 微信保存access_token

微信保存access_token

function get_accessToken(){
$appid = ‘......‘;
$secret = ‘......‘;

$tokenFile = "./access_token.txt"; // 缓存文件名

$data = http://www.mamicode.com/json_decode(file_get_contents($tokenFile)); //转换为json格式

if ($data->expire_time < time() or ! $data->expire_time) {

//token过期的情况

$res = file_get_contents(‘https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=‘ . $appid . ‘&secret=‘ . $secret);

$res = json_decode($res, true); // 对 JSON 格式的字符串进行编码

$access_token = $res[‘access_token‘];

if ($access_token) {

$data->expire_time = time() + 7200; //保存2小时

$data->access_token = $access_token;

$fp = fopen($tokenFile, "w"); //只写文件

fwrite($fp, json_encode($data)); //写入json格式文件

fclose($fp); //关闭连接

}

} else {

$access_token = $data->access_token;

}

return $access_token;

}

微信保存access_token