Implementing Enterprise WeChat Notifications with Python
This guide explains how to create an Enterprise WeChat application, obtain the required corp ID and secret, and use a Python script to send notification messages via the WeChat API, complete with code examples and expected results.
Common notification methods include email, phone calls, SMS, and WeChat; among them, Enterprise WeChat is suitable for alert-type messages. This article demonstrates how to send messages to enterprise members using the Enterprise WeChat API.
1. Create an Application
Log in to the web version of Enterprise WeChat (https://work.weixin.qq.com), go to Application Management → Application → Create Application , upload a logo, set the application name (e.g., "Bond New Issue"), and define the visible range to create an alert application.
2. Obtain Secret
The notification process uses two API endpoints:
Get Token : https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={secret}
Send Message : https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}
The corpid uniquely identifies your enterprise, and the secret is the application‑level key that authorizes the program to send messages on its behalf. Both can be retrieved from the Enterprise WeChat admin console.
3. Code Implementation
<code>import json
import time
import requests
"""This file implements sending messages to enterprise members via an Enterprise WeChat application."""
CORP_ID = "xxxx"
SECRET = "xxxx"
class WeChatPub:
s = requests.session()
def __init__(self):
self.token = self.get_token()
def get_token(self):
url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={CORP_ID}&corpsecret={SECRET}"
rep = self.s.get(url)
if rep.status_code != 200:
print("request failed.")
return
return json.loads(rep.content)["access_token"]
def send_msg(self, content):
url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + self.token
header = {"Content-Type": "application/json"}
form_data = {
"touser": "FengXianMei", # recipient
"toparty": "1", # department
"totag": " TagID1 | TagID2 ", # address book tag IDs
"msgtype": "textcard",
"agentid": 1000002, # application ID
"textcard": {
"title": "Bond New Issue Alert",
"description": content,
"url": "URL",
"btntxt": "More"
},
"safe": 0
}
rep = self.s.post(url, data=json.dumps(form_data).encode('utf-8'), headers=header)
if rep.status_code != 200:
print("request failed.")
return
return json.loads(rep.content)
if __name__ == "__main__":
wechat = WeChatPub()
timenow = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
wechat.send_msg(f"<div class=\"gray\">{timenow}</div> <div class=\"normal\">Attention!</div><div class=\"highlight\">New bond today, keep issuing!</div>")
print('Message sent!')
</code>4. Expected Result
The sent notification appears in the Enterprise WeChat client as a formatted text card.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.