Python 对接企业微信 API:发送应用消息与部门管理示例
使用 Python 的 requests 库,先通过企业微信 API 获取 access_token ,再调用消息发送接口或部门管理接口即可完成对接。

应用凭证与 Token 获取机制
企业微信所有 API 调用都需要 access_token,它由 corp_id 和 corp_secret 换取。Token 有效期为 7200 秒,建议缓存复用,避免频繁请求触发频率限制。

Token 获取接口返回 JSON 包含 errcode、errmsg 和 access_token。若 errcode 不为 0,需检查 corp_id 和 corp_secret 是否正确,或应用是否已授权。实际开发中应封装一个 get_token 函数,并在 token 过期前自动刷新。
发送应用消息与部门列表查询实现
将完整程序保存为 wechat_work.py,运行 python wechat_work.py 即可看到发送消息和获取部门列表的结果。程序默认使用测试用的 CorpID 和 Secret,实际使用时请替换为真实值。

import requests
def get_access_token(corp_id, corp_secret):
url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corp_id}&corpsecret={corp_secret}"
response = requests.get(url)
data = response.json()
if data.get('errcode') != 0:
raise Exception(f"Failed to get token: {data.get('errmsg')}")
return data['access_token']
def send_app_message(token, msg_type, content, agentid, touser="@all", toparty=None, totag=None):
url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}"
data = {
"touser": touser,
"msgtype": msg_type,
"agentid": agentid,
msg_type: content
}
if toparty:
data["toparty"] = toparty
if totag:
data["totag"] = totag
response = requests.post(url, json=data)
result = response.json()
print(f"Send message result: {result}")
return result
def get_department_list(token, dept_id=1):
url = f"https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={token}&id={dept_id}"
response = requests.get(url)
data = response.json()
if data.get('errcode') != 0:
print(f"Failed to get department list: {data.get('errmsg')}")
return []
return data.get('department', [])
if __name__ == "__main__":
# 请替换为真实的 CorpID 和 Secret
CORP_ID = "your_corp_id"
CORP_SECRET = "your_corp_secret"
AGENT_ID = 1000001 # 请替换为真实的应用 AgentId
try:
token = get_access_token(CORP_ID, CORP_SECRET)
# 发送文本消息给所有成员
text_content = {"content": "Hello from Python!"}
send_app_message(token, "text", text_content, AGENT_ID, touser="@all")
# 获取部门列表
depts = get_department_list(token, 1)
print(f"Departments: {depts}")
except Exception as e:
print(f"Error: {e}")
程序输出应显示消息发送成功(errcode=0)及部门列表数据。若发送失败,检查 touser 是否为有效用户或部门,以及 agentid 是否正确。部门 ID 传入 1 通常返回根部门及其子部门。
程序演示了如何构造消息体并发送,以及如何查询指定部门的子部门列表。注意消息发送需要指定 agentid,且接收人可以是 userid、departmentid 或 touser(多个用户用 | 分隔)。
touser 参数在部门 ID 场景下的行为差异
当接收人参数设置为部门 ID 时,API 会向该部门下所有成员发送消息,但前提是这些成员必须关注了该企业微信应用。若未关注,则不会收到消息。
在实际使用中,常遇到“消息发送成功但无人收到”的情况。这通常是因为目标部门成员未安装或未关注企业微信应用。排查时应先确认成员状态,而非仅检查 API 返回值。部门 ID 必须是数字类型,且在 JSON 中作为字符串传递时需确保格式正确。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













