前言
微信的影響力眾所周知,越來越多的人也都離不開它,工作,生活,社交的好幫手。相信大家對微信公眾號,小程序也都不陌生,那么在開發公眾號,小程序的時候需要調用到微信的接口,固然就會遇到token的問題,有哪些問題,以及怎么解決的呢,我們繼續往下看。
問題一:微信接口返回"errcode":48001,"errmsg":"api unauthorized”
原因有下面幾個:
1、服務號可能沒認證,接口功能未授權
2、 appID和appsecret用的還是你申請的訂閱號里面(個人只能申請公眾號類型為訂閱號)
3、用 scope=snsapi_base,獲取用戶的基本信息
4、用 scope= snsapi_userinfo ,獲取用戶的基本信息access_token失效了
解決辦法:
1、確認公眾號已獲得該接口的權限,可在公眾平台官網-開發中心頁中查看接口權限
2、把項目里面的appID和appsecret改成測試公眾號的
3、 scope=snsapi_base不能用於獲取用戶基本信息
4、 access_token 失效后,可以使用 refresh_token 調用接口https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={0}&grant_type=refresh_token&refresh_token={1}
重新獲取 access_token(有效期7200秒)
問題二:微信接口返回 "errcode": 40001,"errmsg": "invalid credential, access_token is invalid or not latest
原因:
1、token失效或者不是最新的
解決辦法:
(1)把獲取到的token存入到緩存中,設置過期時間大約為3分鍾,每次獲取token時優先從緩存里獲取
(2)做刷新token的功能。調用接口https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token={0}
可查token,接口返回errcode= 40001時,把緩存里的token清除,然后再重新獲取。
附上代碼
1、獲取token的方法
public function getaccess_token()
{
load()->model('account’);
$account_api = WeAccount::create();
$token = $account_api->getAccessToken();
$result = $this->clearAccessToken($token,$account_api);
if(!empty($result['token'])){
$token = $result['token'];
}
if(is_error($token)){
$this->echoMsg(0,'access_token獲取失敗。');
}
return $token;
}
2、刷新token的方法
public function clearAccessToken($access_token,$account_api)
{
global $_W;
if(is_error($access_token)){
return $access_token;
}
$url = 'https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=' . $access_token; $response = ihttp_request($url);
$result = @json_decode($response['content'], true);
if(empty($result)) {
return $response;
}
if (!empty($result) && $result[‘errcode’] = ‘40001’) { cache_delete(cache_system_key('accesstoken_key', array('key' => $_W['account']['key'])));
return array('token'=>$account_api->getAccessToken());
}
return true;
}