mp_chajian/get_token.py

40 lines
1.0 KiB
Python
Raw Normal View History

2025-10-15 16:46:31 +08:00
import requests
import json
def get_wechat_token(appid, appsecret):
"""
通过微信公众号的APPID和AppSecret获取access_token
参数:
appid (str): 公众号的APPID
appsecret (str): 公众号的AppSecret
返回:
str: 成功时返回access_token
None: 失败时返回None
"""
if not appid or not appsecret:
return None
# 微信获取token的接口
url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={appsecret}"
try:
# 发送GET请求
response = requests.get(url, timeout=10)
# 解析JSON响应
result = json.loads(response.text)
# 检查是否返回了错误信息
if "errcode" in result and result["errcode"] != 0:
return None
# 返回获取到的token
return result.get("access_token")
except requests.exceptions.RequestException:
return None
except json.JSONDecodeError:
return None