我的博客

python 获取微信公众号 access token

目录
  1. 接口详情
  2. 代码

接口详情

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数据包给公众号:

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

代码

1
2
3
4
5
6
7
8
9
10
exp_time = 0
access_token = ''
def get_access_token():
global exp_time, access_token
if time.time() > exp_time:
r = requests.get('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET')
d = json.loads(r.text)
access_token = d['access_token']
exp_time = time.time() + d['expires_in'] - 10 # 减一点防止快到时间的时候已经失效了
return access_token

在 django 里直接把这个代码写到任意一个 views 里就可以了。

其他地方需要 access_token 就直接调这个函数,保证不会短时间内重复申请。

之前我会存到数据库里,但实际上没必要。

评论无需登录,可以匿名,欢迎评论!