/** * 请求微信平台服务器,并解析返回的json字符串为数组,失败抛异常 * @param $url * @param $data * @return array * @throws \PFinal\Wechat\WechatException */ protected static function request($url, $data = null, $jsonEncode = true) { $executeUrl = str_replace('ACCESS_TOKEN', self::getApi()->getAccessToken(), $url); if ($jsonEncode) { $data = Json::encode($data); } try { return Json::parseOrFail(Curl::execute($executeUrl, is_null($data) ? 'get' : 'post', $data)); } catch (WechatException $ex) { //更新AccessToken再次请求 if ($ex->getCode() == 40001) { $executeUrl = str_replace('ACCESS_TOKEN', self::getApi()->getAccessToken(false), $url); return Json::parseOrFail(Curl::execute($executeUrl, is_null($data) ? 'get' : 'post', $data)); } throw $ex; } }
/** * 获取公众号的全局唯一票据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; }