php微信token存储,PHP取微信access_token并全局存储与更新

来源:http://www.zcphp.com/html/weixinkaifa-show-20.html

官方的说明:

access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token。

开发时需要进行妥善保存。

access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。

众所周知,在微信开发中access_token是经常用的。但是access_token的请求次数是有限制的,所以不能每次都重新请求,只有将它缓存到本地了。

function accessToken() {

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

$data = json_decode(file_get_contents($tokenFile));

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

$appid = "你的appid";

$appsecret = "你的appsecret";

$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";

$res = getJson($url);

$access_token = $res[‘access_token‘];

if($access_token) {

$data[‘expire_time‘] = time() + 7000;

$data[‘access_token‘] = $access_token;

$fp = fopen($tokenFile, "w");

fwrite($fp, json_encode($data));

fclose($fp);

}

} else {

$access_token = $data->access_token;

}

return $access_token;

}

//取得微信返回的JSON数据

function getJson($url){

$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);

return json_decode($output, true);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值