【微信公众号】一、获取 access_token
一、获取 access_token
- 开发环境:Python
说明:
- 微信公众号的 token,可以通过appid和appsecret登录后获取;
- token的有效期为两个小时;
- 如果本地开发,需要将本机的外网IP设为白名单,如果有服务器直接配置即可。
原理:
- 定义一个配置文件,用来保存
用户名
,密码
,token
和token获取时间
; - 读取配置文件,如果
token获取时间
存在,则根据时间差是否超过两个小时,直接获取或者重新获取。
配置文件 conf.toml
如下:
[basic]
app_id = "xxx"
app_secret = "xxx"
access_token = "xxx"
token_time = 1700225491.118164
[web]
user_agents = [ "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)", "Mozilla/5.0 (Windows NT 5.1; U; en; rv:1.8.1) Gecko/20061208 Firefox/2.0.0 Opera 9.50", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.4.3.4000 Chrome/30.0.1599.101 Safari/537.36", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; SE 2.X MetaSr 1.0)", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36 Edg/91.0.864.59",]
相关逻辑的python
代码如下
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : deepboat
# @Desc : 连接网络 获取 access_token
# @Date : 2023/11/17 17:41
import json
import random
import requests
import time
import toml
class Basic:
def __init__(self, conf_file):
self.confFile = conf_file
self.confInfo = self.read_toml()
self.appID = self.confInfo["basic"]["app_id"]
self.appSecret = self.confInfo["basic"]["app_secret"]
self.accessToken = self.confInfo["basic"]["access_token"]
self.tokenTime = self.confInfo["basic"]["token_time"]
self.userAgent = self.get_user_agent()
def read_toml(self):
conf_file = toml.load(self.confFile)
return conf_file
def write_toml(self):
self.confInfo["basic"]["app_id"] = self.appID
self.confInfo["basic"]["app_secret"] = self.appSecret
self.confInfo["basic"]["access_token"] = self.accessToken
self.confInfo["basic"]["token_time"] = self.tokenTime
with open(self.confFile, "w", encoding="utf-8") as f:
toml.dump(self.confInfo, f)
# // 获取token
def get_wechat_token(self):
# 判断token是否过期
if self.which_token_over():
try:
params = {
"grant_type": "client_credential",
"appid": self.appID,
"secret": self.appSecret
}
headers = {'User-Agent': self.userAgent}
post_url = "https://api.weixin.qq.com/cgi-bin/token"
response_post = requests.post(url=post_url, params=params, headers=headers)
print(response_post)
print(response_post.text)
res = json.loads(response_post.text)
access_token = res["access_token"]
self.accessToken = access_token
self.tokenTime = time.time()
self.write_toml()
return self.accessToken
except Exception as e:
print(e)
return False
else:
return self.accessToken
# 判断token是否过期
def which_token_over(self):
# 获取当前时间戳 -- 时间戳是自1970年1月1日午夜以来的秒数
now_time = time.time()
# 用当前时间戳减去getTokenTime,大于两个小时就判定失效
hour2 = 2 * 60 * 60
if now_time - self.tokenTime > hour2:
return True
return False
def get_user_agent(self):
user_agent = random.choice(self.confInfo["web"]["user_agents"])
return user_agent
# if __name__ == '__main__':
# my_basic = Basic("../../docs/conf.toml")
# my_basic.get_wechat_token()