- 注册企业微信账号
- 在我的企业中获取企业的id
corpID = wwfe6edfd511b002e2 - 应用管理中,推送消息的应用。并获取应用的AgentId和Secret
AgentId = 1000003
Secret = 5TbU2fubWcfbGeeAQEs8mgm0ZZAc5FJdaGk20KfeUl0 - 获取access_token, 请求url如下图所示。
https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRET
corpid和Secret为第2步和第3步获取到的信息
即
https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwfe6edfd511b002e2&corpsecret=5TbU2fubWcfbGeeAQEs8mgm0ZZAc5FJdaGk20KfeUl0 - 构造消息体,使用post请求发送数据
{
"touser" : "abelzhu|ZhuShengben",
"msgtype" : "text",
"agentid" : 1000002,
"text" : {
"content" : "我就试一下"
},
"safe":0
}
- 发送消息。使用第4步的token值和第5步的data信息,发送消息
https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRET - 代码示例
python代码
import json
import requests
def getToken():
r = requests.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwfe6edfd511b002e2&corpsecret=5TbU2fubWcfbGeeAQEs8mgm0ZZAc5FJdaGk20KfeUl0")
if r.status_code == 200:
data = json.loads(r.text)
if data["errcode"] == 0:
return data["access_token"]
pass
else:
return str(data["errcode"]) + "parameter error"
else:
return "network failure"
def sendMsg():
data = {
"touser" : "xdz|WangChaoHua",
"msgtype" : "text",
"agentid" : 1000003,
"text" : {
"content" : "hhh world"
},
"safe":0
}
access_token = getToken()
r = requests.post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}".format(access_token), data=json.dumps(data))
print(r.text)
if __name__ == "__main__":
sendMsg()