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

相关资料

微信errcode":48001,"errmsg":"api unauthorized

来源:https://segmentfault.com/a/1190000016652884

原文地址:https://www.cnblogs.com/qixidi/p/10173756.html