Django微信公众号开发:获取access_token
1.access_token说明
access_token是公众号全球唯一的UI调用凭证。 公众号调用各个接口时需要使用access_token。开发商必须妥善保管。必须预留至少512个字符的空间用于存储access_token。 access_token有效期目前为2小时,需要定期更新。重复获取会导致最后一个access_token失效。
公众号和widget都可以使用AppID和AppSecret调用该接口获取access_token。 AppID和AppSecret可以在“微信公众平台-开发-基础配置”页面获取。调用接口时,请登录“微信公众平台-开发-基础配置”提前将服务器IP地址添加到IP白名单中,并点击查看设置方法,否则调用失败。
2。接口调用请求地址
https 请求方式:GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
参数说明⸓⸓❀是否需要? ️ 3。返回接口调用说明 正常情况下,微信会返回以下 JSON 数据包到 公众号 参数说明 如果出现错误,微信会返回错误码等信息。 JSON数据包示例如下(本例为AppID无效错误): 返回码说明 4。 Django获取access_token 安装Redis并使用redis缓存解决access_token有效期2小时的问题{"access_token":"ACCESS_TOKEN","expires_in":7200}
参数 说明 ❀已访问 expires_in 优惠券有效期时间、单位: 秒 {"errcode":40013,"errmsg":"invalid appid"}
返回码 说明 -1系统稍后繁忙 0 请求成功 40001 AppSecret-错误或AppSecret未找到属于此公众号,请开发者确认AppSecret的正确性 40002 确保grant_type字段值为client_credential IP地址接口未列入白名单。在接口IP白名单中设置。 89503 该IP呼叫需要管理员验证,请联系管理员 89501 该IP正在等待管理员验证,请联系管理员 89506 该IP在24小时内被管理员两次拒绝,24小时内无法呼叫小时 使用该IP拨打 89507 该IP将在1小时内被管理员拒绝一次。您无法使用此 IP 呼叫 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})
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})
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。