调用微信接口token的问题

<h2>前言</h2> <p>微信的影响力众所周知,愈来愈多的人也都离不开它,工做,生活,社交的好帮手。相信你们对微信公众号,小程序也都不陌生,那么在开发公众号,小程序的时候须要调用到微信的接口,当然就会遇到token的问题,有哪些问题,以及怎么解决的呢,咱们继续往下看。</p> <h2>问题一:微信接口返回"errcode":48001,"errmsg":"api unauthorized”</h2> <p>缘由有下面几个:<br>一、服务号可能没认证,接口功能未受权<br>二、 appID和appsecret用的仍是你申请的订阅号里面(我的只能申请公众号类型为订阅号)<br>三、用 scope=snsapi_base,获取用户的基本信息<br>四、用 scope= snsapi_userinfo ,获取用户的基本信息access_token失效了</p> <p>解决办法:<br>一、确认公众号已得到该接口的权限,可在公众平台官网-开发中心页中查看接口权限<br>二、把项目里面的appID和appsecret改为测试公众号的<br>三、 scope=snsapi_base不能用于获取用户基本信息<br>四、 access_token 失效后,可使用 refresh_token 调用接口<code>https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={0}&amp;grant_type=refresh_token&amp;refresh_token={1} </code>从新获取 access_token(有效期7200秒)</p> <h2>问题二:微信接口返回 "errcode": 40001,"errmsg": "invalid credential, access_token is invalid or not latest</h2> <p>缘由:<br>一、token失效或者不是最新的</p> <p>解决办法:<br>(1)把获取到的token存入到缓存中,设置过时时间大约为3分钟,每次获取token时优先从缓存里获取<br>(2)作刷新token的功能。调用接口<code>https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token={0}</code>可查token,接口返回errcode= 40001时,把缓存里的token清除,而后再从新获取。</p> <h2>附上代码</h2>html

一、获取token的方法
     public function getaccess_token()
     {        
         load()-&gt;model('account’);    
        $account_api = WeAccount::create();     
        $token = $account_api-&gt;getAccessToken();    
        $result = $this-&gt;clearAccessToken($token,$account_api);    
       if(!empty($result['token'])){        
             $token = $result['token'];     
       }    
       if(is_error($token)){        
            $this-&gt;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) &amp;&amp; $result[‘errcode’] = ‘40001’) {                            cache_delete(cache_system_key('accesstoken_key', array('key' =&gt; $_W['account']['key'])));         
        return array('token'=&gt;$account_api-&gt;getAccessToken());    
    }        
    return true;
}

<h2>相关资料</h2> <p><a href="http://www.cnblogs.com/liaolongjun/p/6080240.html" rel="nofollow noreferrer">微信errcode":48001,"errmsg":"api unauthorized</a></p>json

来源:https://segmentfault.com/a/1190000016652884小程序

相关文章
相关标签/搜索