Python 调用微信 API 基础:使用 requests 获取 Access Token 并发送消息
使用 requests 库发起 HTTP 请求,通过微信提供的接口地址获取 Access Token ,再利用该 Token 调用消息发送接口即可实现自动化消息推送。

Access Token 的获取与缓存机制
微信 API 要求所有操作必须携带有效的 Access Token,该凭证有效期为 7200 秒,且全局唯一。开发者需维护一个本地缓存,避免频繁请求导致触发频率限制。

get_token_url 需要传入 AppID 和 AppSecret。返回的 JSON 数据中包含 access_token 字段。在实际工程中,通常会将获取到的 Token 存入 Redis 或本地文件,并记录过期时间。当 Token 即将过期时,再发起刷新请求。直接硬编码 Token 会导致服务在两天后失效,因此动态获取是必须的步骤。
完整消息发送流程实现
以下代码演示了从获取 Token 到发送文本消息的完整闭环。请将此脚本保存为 WeChatBot.py,替换其中的 AppID 和 AppSecret 后即可运行。

import requests
import json
import time
def get_access_token(app_id, app_secret):
url = "https://api.weixin.qq.com/cgi-bin/token"
params = {
"grant_type": "client_credential",
"appid": app_id,
"secret": app_secret
}
response = requests.get(url, params=params)
data = response.json()
if "access_token" in data:
return data["access_token"], data.get("expires_in", 7200)
else:
raise Exception(f"Failed to get token: {data}")
def send_text_message(access_token, content, touser="@all"):
url = f"https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={access_token}"
payload = {
"touser": touser,
"msgtype": "text",
"text": {
"content": content
}
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, data=json.dumps(payload), headers=headers)
return response.json()
if __name__ == "__main__":
APP_ID = "your_app_id"
APP_SECRET = "your_app_secret"
try:
token, expires_in = get_access_token(APP_ID, APP_SECRET)
print(f"Token obtained. Expires in {expires_in}s")
result = send_text_message(token, "Hello from Python!")
print(f"Send result: {result}")
except Exception as e:
print(f"Error: {e}")
运行脚本后,若配置正确,将输出 Token 获取成功信息及消息发送结果。预期结果为 {"errcode":0,"errmsg":"ok"}。若出现 40001 错误,请检查 AppID/Secret 是否正确,或尝试清除缓存后重试。
程序先尝试读取本地缓存的 Token,若不存在或已过期,则向微信服务器请求新 Token。随后构造 POST 请求体,指定接收方类型为 all(全员)或具体用户 OpenID。发送成功后,控制台会打印响应状态码及消息 ID。若遇到 40001 错误,说明 Token 无效,需检查网络或重新获取。
Token 失效时的自动重试策略
当发送消息返回 40001 (invalid credential) 错误时,表明当前使用的 Access Token 已失效或被其他进程覆盖。此时应立即触发 Token 刷新逻辑,并重试上一次的消息发送请求。
在上面的程序中,我们可以在发送消息前增加一个校验步骤。如果 response.json() 中的 errcode 不为 0,且错误码为 40001,则清空本地缓存并重新调用 get_access_token 函数。这种“失败-刷新-重试”的模式能显著提高接口的稳定性,避免因并发调用导致的 Token 冲突问题。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













