调用微信接口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微信

相关文章
相关标签/搜索