/**
* 获取公众号的全局唯一票据accessToken,公众号主动调用各接口时都需使用accessToken
* accessToken默认有效时间为7200秒,每天调用次数有限制,认证服务号每天最多100000次
*
* @param bool $useCache 是否使用缓存
* @return string|null
*/
public function getAccessToken($useCache = true)
{
//缓存key
$cacheKey = md5(__FILE__ . __METHOD__ . $this->appId);
//检查是否启用缓存
if ($useCache) {
if (empty($this->accessToken)) {
$this->accessToken = Cache::get($cacheKey);
}
if (!empty($this->accessToken)) {
return $this->accessToken;
}
} else {
$this->accessToken = null;
Cache::delete($cacheKey);
}
//获取accessToken
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s';
$response = Curl::get(sprintf($url, $this->appId, $this->appSecret));
//返回格式 {"access_token":"ACCESS_TOKEN","expires_in":7200}
//{"access_token":"43BKbLBjBnwH600H5TMSlx6AKT9TCZ3BRXjxvT0erRpzHTIaUuaJBDUoUykTqA","expires_in":7200}
//每日调用超过次数,将提示
//{"errcode":45009,"errmsg":"reach max api daily quota limit hint: [PuguNA0618vr22]"}
$arr = Json::parseOrFail($response);
$this->accessToken = $arr['access_token'];
//默认时间是7200秒(120分钟)
$expires = $arr['expires_in'] - 1200;
if ($expires > 0) {
Cache::set($cacheKey, $this->accessToken, $expires);
}
return $this->accessToken;
}