在微信开发的过程中,调用接口的时候都需使用公众号的全局唯一接口调用凭据access_token,在使用之前我们需要获取它。目前Access_token的有效期通过返回的expire_in来传达,目前是7200秒之内的值。中控服务器需要根据这个有效时间提前去刷新新access_token。在刷新过程中,中控服务器可对外继续输出的老access_token,此时公众平台后台会保证在5分钟内,新老access_token都可用,这保证了第三方业务的平滑过渡。
接口调用请求说明
https请求方式: GET
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

参数说明

参数是否必须说明
grant_type获取access_token填写client_credential
appid第三方用户唯一凭证
secret第三方用户唯一凭证密钥,即appsecret

返回说明

正常情况下,微信会返回下述JSON数据包给公众号:

{"access_token":"ACCESS_TOKEN","expires_in":7200}

参数说明

参数说明
access_token获取到的凭证
expires_in凭证有效时间,单位:秒

错误时微信会返回错误码等信息,JSON数据包示例如下(该示例为AppID无效错误):
{"errcode":40013,"errmsg":"invalid appid"}

返回码说明

返回码说明
-1系统繁忙,此时请开发者稍候再试
0请求成功
40001AppSecret错误或者AppSecret不属于这个公众号,请开发者确认AppSecret的正确性
40002请确保grant_type字段值为client_credential
40164调用接口的IP地址不在白名单中,请在接口IP白名单中进行设置。(小程序及小游戏调用不要求IP地址在白名单内。)

以上的信息均来源于微信公众平台的开发者文档。但不保证是最新的,使用者可以自己上官网查看。
由于access_token的存活时间有时间上的限制,而且目前每天只能调用2000次,所有我们必须对access_token进行有效的利用,我们可以把它保存在session中,并设置有效的时间,如果有效,我们直接返回,无需重新获取。
示例代码:(thinkphp3.2.3)

/** * 返回access_token * @return [type] [description] */ public function getWxAccessToken(){ //将access_token存在session/cookie中 if($_SESSION['access_token']&&$_SESSION['expire_time']>time()){ //如果access_token在session并未过期 return $_SESSION['access_token']; }else{ //如果access_token不存在或者已经过期,重新获取access_token $appid = 'wxde8d3eacc9f91cae'; $appsecret = '3ae10c48de0ec193a7cc695f098c2817'; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret; $res = $this->http_curl($url,'get','json'); $access_token = $res['access_token']; //将创新获取的access_token存到session $_SESSION['access_token'] = $access_token; $_SESSION['expire_time'] = time()+7000; return $access_token; } } /** * @param url * @param 获取方式 * @param 获取到的格式 * @param string * @return [type] */ function http_curl($url,$type='get',$res='json',$arr=''){ //1.初始化curl $ch = curl_init(); //2.设置curl的参数 curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); if($type == 'post'){ curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $arr); } //3.采集 $output = curl_exec($ch); //4.关闭 if($res == 'json'){ if(curl_errno($ch)){ return curl_error($ch); }else{ return json_decode($output,true); } } curl_close($output); }
Last modification:June 24, 2018
If you think my article is useful to you, please feel free to appreciate