获取access_token

access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。因此需要开发者进行妥善保存。access_token的存储至少要保留512个字符空间。access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。

请求URL:

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

请求方式:

  • GET

请求参数:

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

返回示例:

正确时返回:

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

错误时返回:

{"errcode":40013,"errmsg":"invalid appid"}

返回码说明:

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

使用PHP代码实现

//加载初始化配置 需要配置$appid和$secret
include '../config/init.php';
//构建接口URL
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
//请求接口(推荐使用curl)
$json_token = file_get_contents($url);
//json转数组
$arr = json_decode($json_token,true);
echo '<pre>';
print_r($arr);

如果出现类似{"errcode":40164,"errmsg":"invalid ip *.*.*.*, not in whitelist hint: [***]"}的提示说明公众平台的后台没有设置白名单,需要进入后台设置允许的ip即可。

思考题

每次使用access_token时直接调用接口获取是否可以?

本文档由黎明互联官方发布