微信公众号注册
https://mp.weixin.qq.com/
微信公众号测试
https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
里面appID、appsecret、模板ID、用户微信号 搞到就行了
模板范例
尊敬的 {{name.DATA}} 注册码是:{{code.DATA}}
WXMsg.py
import json
import requests
class WXMsg(object):
APPID =
"wxf9e32f8"
APPSECRET =
"316f5409"
# 消息接收者
TOUSER =
'o_fQLsVxu8gaQ'
# 消息模板id
TEMPLATE_ID =
'Hz6O2pUZuZARD_OiiEuKec'
# 点击跳转链接(可无)
CLICK_URL =
'https://www.baidu.com/'
def __init__(self,
touser=TOUSER,
template_id=TEMPLATE_ID,
click_url=CLICK_URL,
app_id=APPID,
app_secret=APPSECRET) -> None:
"""
构造函数
:param touser: 消息接收者
:param template_id: 消息模板id
:param click_url: 点击跳转链接(可无)
"""
self.app_id = app_id
self.app_secret = app_secret
self.access_token =
self.get_access_token()
self.touser = touser
self.template_id = template_id
self.click_url = click_url
def
get_access_token(self) -> str:
"""
获取access_token凭证
:return: access_token
"""
resp =
requests.get(url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential',
params={"appid": self.app_id,
"secret": self.app_secret})
result = resp.json()
if 'access_token' in result:
return
result["access_token"]
else:
print(result)
def get_send_data(self,
json_data) -> object:
"""
获取发送消息data
:param json_data: json数据对应模板
:return: 发送的消息体
"""
return {
"touser":
self.touser,
"template_id": self.template_id,
"url":
self.click_url,
"topcolor": "#FF0000",
#
json数据对应模板
"data":
{
"name": {
"value": json_data["name"],
# 字体颜色
"color": "#173177"
},
"code": {
"value": json_data["code"],
"color": "#173177"
},
}
}
def send_message(self,
json_data) -> None:
"""
发送消息
:param json_data: json数据
:return:
"""
# 模板消息请求地址
url =
f"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={self.access_token}"
data =
json.dumps(self.get_send_data(json_data))
resp = requests.post(url, data=data)
result = resp.json()
#
有关响应结果,我有整理成xml文档(官方全1833条),免费下载:https://download.csdn.net/download/sxdgy_/86263090
if result["errcode"] == 0:
print("消息发送成功")
else:
print(result)
def get_user_list(self)
-> None:
res =
requests.get(url='https://api.weixin.qq.com/cgi-bin/user/get',
params={"access_token":self.access_token,"next_openid":""})
print(res.text)
test.py
import requests
from WXMsg import WXMsg
if __name__ == '__main__':
sm = WXMsg()
# 获取接口返回数据
json_data = {"name":
"uuu", "code": "8787"}
# 发送消息
sm.send_message(json_data=json_data)
sm.get_user_list()
加载中,请稍候......