調用微信接口token的問題

前言

微信的影響力衆所周知,越來越多的人也都離不開它,工作,生活,社交的好幫手。相信大家對微信公衆號,小程序也都不陌生,那麼在開發公衆號,小程序的時候需要調用到微信的接口,固然就會遇到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...{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...{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;
}

相關資料
微信errcode":48001,"errmsg":"api unauthorized

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章