1. 登陆企业微信后台管理 》创建应用
https://work.weixin.qq.com/
2. 配置企业可信IP
企业微信 》应用管理 》对应应用 》企业可信IP 》配置
注:url的ip需为外网ip,Token和EncodingAESKey值需要和回调服务的配置文件中配置的相同,sCorpID为企业id值
配置成功后就可以增加企业可信IP
不加入企业可信IP的情况会出现以下报错内容
{'errcode': 60020, 'errmsg': 'not allow to access from your ip, hint: [1672976067480131321651000], from ip: 116.227.240.215, more info at https://open.work.weixin.qq.com/devtool/query?e=60020'}
我们需要把116.227.240.215这个IP加入到可信ip名单中
多个IP地址以英文;分割
3. 执行python脚本
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import requests
import json
class WeChat:
def __init__(self):
self.CORPID = 'XXXXXX' #企业ID,在管理后台获取
self.CORPSECRET = 'XXXXXXX'#自建应用的Secret,每个自建应用里都有单独的secret
self.AGENTID = '1000002' #应用ID,在后台应用中获取
self.TOUSER = "ZhangMingMing|mming723" # 接收者用户名,多个用户用|分割
def _get_access_token(self):
url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
values = {'corpid': self.CORPID,
'corpsecret': self.CORPSECRET,
}
req = requests.post(url, params=values)
data = json.loads(req.text)
print(data["access_token"])
return data["access_token"]
def get_access_token(self):
try:
with open('D://data/access_token.conf', 'r') as f:
t, access_token = f.read().split()
except:
with open('D://data/access_token.conf', 'w') as f:
access_token = self._get_access_token()
cur_time = time.time()
f.write(' '.join([str(cur_time), access_token]))
return access_token
else:
cur_time = time.time()
if 0 < cur_time - float(t) < 7260:
return access_token
else:
with open('D://data/access_token.conf', 'w') as f:
access_token = self._get_access_token()
f.write(' '.join([str(cur_time), access_token]))
return access_token
def send_text_message(self, message):
send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self.get_access_token()+"&debug=1"
send_values = {
"touser": self.TOUSER,
"msgtype": "text",
"agentid": self.AGENTID,
"text": {
"content": message
},
"safe": "0"
}
send_msges=(bytes(json.dumps(send_values), 'utf-8'))
respone = requests.post(send_url, send_msges)
respone = respone.json() #当返回的数据是json串的时候直接用.json即可将respone转换成字典
print(respone)
return respone["errmsg"]
def get_media_id(self, filetype, path):
upload_file_url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={}&type={}".format(self.get_access_token(), filetype)
files = {filetype: open(path, 'rb')}
file_upload_result = requests.post(upload_file_url, files=files).json()
return file_upload_result["media_id"]
# 发送图片消息
def send_picture_message(self, media_id):
send_picture_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}".format(self.get_access_token())
data = {
"touser": "@all",
"msgtype": "image",
"agentid": 1000002,
"image": {
"media_id": media_id
},
"safe": 0,
}
picture_message_res = requests.post(url=send_picture_url,data=json.dumps(data)).json()
return picture_message_res
if __name__ == '__main__':
wx = WeChat()
wx.send_text_message("Python程序调用企业微信API,从自建应用“告警测试应用”发送给管理员的消息!")
wx.send_picture_message(wx.get_media_id("image", "D:\\data\\jj20.jpg"))
结果展示
回调代码参考
https://developer.work.weixin.qq.com/document/path/90307