$access_token_data = json_decode(cache('access_token'),true);
但是执行时报错如下:
[think\exception\ErrorException]
Undefined index: access_token
说没有找到对象。
我们想是不是cache的引用方式错了,将代码做了修改:
$access_token_data = json_decode(Cache::get('access_token'),true);
但执行时又报错了:
[think\exception\ErrorException]
Class 'Cache' not found
我们想知道如何在appliction/common.php中正确的使用Cache对象,实现全局存储和访问token的功能,就像早期的F方法一样。
我们的完整代码如下:
// 应用公共文件
function getAccessToken(){
//我们将access_token全局缓存在文件中,每次获取的时候,先判断是否过期,如果过期重新获取再全局缓存
//我们缓存的在文件中的数据,包括access_token和该access_token的过期时间戳.
//获取缓存的access_token
$access_token_data = json_decode(cache('access_token'),true);
//判断缓存的access_token是否存在和过期,如果不存在和过期则重新获取.
if($access_token_data !== null && $access_token_data['access_token'] && $access_token_data['expires_in'] > time()){
return $access_token_data['access_token'];
}else{
//重新获取access_token,并全局缓存
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='
.config('appID').'&secret='.config('appSecret'));
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
//获取access_token
$data = json_decode(curl_exec($curl),true);
if($data != null && $data['access_token']){
//设置access_token的过期时间,有效期是7200s
$data['expires_in'] = $data['expires_in'] + time()+1800;
//将access_token全局缓存,快速缓存到文件中.
cache('access_token',json_encode($data) );
//返回access_token
return $data['access_token'];
}else{
exit('微信获取access_token失败');
}
}
}
common.php.zip
( 1.39 KB 下载:1 次 )
最佳答案
