python实现推送消息到微信公众号
使用到库:
Requests
实现方式:
微信已开放了对应的接口,直接通过python的requests库,发起请求,实现推送消息到公众号
微信公众号准备:
1、没有注册微信公众号,可以使用微信提供的测试公众号,来测试公众号的推送
https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
2、点击登录,使用自己微信账号,扫一扫登录
3、登录成功后,会生成一个自己的测试公众号,有测试号的appid、appsecret
4、要看推送的效果,要先关注当前的测试账号,关注成功后,可在列表查看当前的粉丝数和具体的open_id
使用微信公众号的接口:
1、 获取微信公众号的授权token:
2、 获取当前公众号的粉丝的open_id:
https://api.weixin.qq.com/cgi-bin/user/get?access_token={self.token}&next_openid={next_openid}
3、 发送模板消息的接口:
https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={self.token}
4、 发送普通消息的接口:
https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=xxx
实现逻辑:
发送消息的接口,需要验证token,和传入粉丝的open_id,进行发送,发送模板消息,需要传入模板id
微信公众号后台,模板管理,增加模板,模板内容需要配置对应
实现代码:
class WechatMessagePush: def __init__(self, appid, appsecret, temple_id): self.appid = appid self.appsecret = appsecret # 模板id,参考公众号后面的模板消息接口 -> 模板ID(用于接口调用):IG1Kwxxxx self.temple_id = temple_id self.token = self.get_Wechat_access_token() def get_Wechat_access_token(self): ''' 获取微信的access_token: 获取调用接口凭证 :return: ''' url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={self.appid}&secret={self.appsecret}" response = requests.get(url) res = response.json() if "access_token" in res: token = res["access_token"] return token def get_wechat_accout_fans_count(self): ''' 获取微信公众号所有粉丝的openid ''' next_openid = '' url = f"https://api.weixin.qq.com/cgi-bin/user/get?access_token={self.token}&next_openid={next_openid}" response = requests.get(url) res = response.json()['data']['openid'] def send_wechat_temple_msg(self, content): ''' 发送微信公众号的模板消息''' url = f"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={self.token}" fan_open_id = self.get_wechat_accout_fans_count() for open_id in fan_open_id: body = { "touser": open_id, 'template_id': self.temple_id, # 'url': 'http://www.jb51.net', "topcolor": "#667F00", "data": { "content": {"value": content} } } headers = {"Content-type": "application/json"} data = json.JSONEncoder().encode(body) res = requests.post(url=url, data=data, headers=headers)
调用方法,发送消息
if __name__ == '__main__': appid = "wx4d4xxxx" screct = "522xxxx4" template_id = 'IG1Kxxbxxxxxls' WechatMessagePush(appid, screct, template_id).send_wechat_txt_msg(msg="测试")
实现的推送的消息
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
2019-08-26 Appium服务器初始化参数(Capability)
2019-08-26 pytest执行用例:明明只写了5个测试用例, 怎么收集到33个!?