Django微信公众号开发:获取access_token
一、access_token说明
access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。开发者需要进行妥善保存。access_token的存储至少要保留512个字符空间。access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。
公众号和小程序均可以使用AppID和AppSecret调用本接口来获取access_token。AppID和AppSecret可在“微信公众平台-开发-基本配置”页中获得。调用接口时,请登录“微信公众平台-开发-基本配置”提前将服务器IP地址添加到IP白名单中,点击查看设置方法,否则将无法调用成功。
二、接口调用请求地址
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 | 请求成功 |
40001 | AppSecret错误或者AppSecret不属于这个公众号,请开发者确认AppSecret的正确性 |
40002 | 请确保grant_type字段值为client_credential |
40164 | 调用接口的IP地址不在白名单中,请在接口IP白名单中进行设置。 |
89503 | 此IP调用需要管理员确认,请联系管理员 |
89501 | 此IP正在等待管理员确认,请联系管理员 |
89506 | 24小时内该IP被管理员拒绝调用两次,24小时内不可再使用该IP调用 |
89507 | 1小时内该IP被管理员拒绝调用一次,1小时内不可再使用该IP调用 |
四、Django获取access_token
import json
import requests
from django.http.response import JsonResponse
def get_access_token():
AppID = "你的AppID",
AppSecret = "你的AppSecret"
url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={AppId}&secret={AppSecret}'.format(
AppId='AppId', AppSecret='AppSecret')
token_str = requests.get(url).content.decode()
token_json = json.loads(token_str)
access_token = token_json.get('access_token')
return JsonResponse({"code": 1, "token": access_token})
安装Redis,使用redis缓存解决access_token有效期2小时的问题
import json
import requests
import redis
from django.http.response import JsonResponse
AppID = "你的AppID",
AppSecret = "你的AppSecret"
r = redis.Redis(host='localhost', port=6379, db=1, decode_responses=True) # 创建redis对象
def get_access_token():
access_token = r.get("access_token") # 从redis中获取ACCESS_TOKEN
if not access_token:
url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={AppId}&secret={AppSecret}'.format(
AppId='AppId', AppSecret='AppSecret')
token_str = requests.get(url).content.decode()
token_json = json.loads(token_str)
access_token = token_json.get('access_token')
r.setex('access_token', 7200, access_token)#过期时间7200秒
return JsonResponse({"code": 1, "token": access_token})
THE END