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="测试")
实现的推送的消息