調用微信接口token的問題

前言

微信的影響力衆所周知,愈來愈多的人也都離不開它,工做,生活,社交的好幫手。相信你們對微信公衆號,小程序也都不陌生,那麼在開發公衆號,小程序的時候須要調用到微信的接口,當然就會遇到token的問題,有哪些問題,以及怎麼解決的呢,咱們繼續往下看。html

問題一:微信接口返回"errcode":48001,"errmsg":"api unauthorized」

緣由有下面幾個:
一、服務號可能沒認證,接口功能未受權
二、 appID和appsecret用的仍是你申請的訂閱號裏面(我的只能申請公衆號類型爲訂閱號)
三、用 scope=snsapi_base,獲取用戶的基本信息
四、用 scope= snsapi_userinfo ,獲取用戶的基本信息access_token失效了json

解決辦法:
一、確認公衆號已得到該接口的權限,可在公衆平臺官網-開發中心頁中查看接口權限
二、把項目裏面的appID和appsecret改爲測試公衆號的
三、 scope=snsapi_base不能用於獲取用戶基本信息
四、 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

緣由:
一、token失效或者不是最新的api

解決辦法:
(1)把獲取到的token存入到緩存中,設置過時時間大約爲3分鐘,每次獲取token時優先從緩存裏獲取
(2)作刷新token的功能。調用接口https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token={0}可查token,接口返回errcode= 40001時,把緩存裏的token清除,而後再從新獲取。緩存

附上代碼

一、獲取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;
    }
二、刷新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微信

相關文章
相關標籤/搜索