公众号消息推送

https://blog.csdn.net/Yzboyfriend1106/article/details/126384652

1. 添加IP白名单

2. 代码实现

settings.py

WECHAT_ACCOUNT_APP_ID = "wxf527cb31e2d59d32"
WECHAT_ACCOUNT_SECRET_KEY = "8f6517fa35b592c8e85efce05e70b65d"
import json
import requests


class WechatMessagePush:
    def __init__(self, app_id, app_secret, temple_id):
        self.app_id = app_id
        self.app_secret = app_secret

        # 模板ID
        self.temple_id = temple_id
        self.OpenIdList = None
        self.sucess_token = self.get_wechat_access_token()

    def get_wechat_access_token(self, force_refresh=False):
        url = "https://api.weixin.qq.com/cgi-bin/stable_token"
        data = {
            "grant_type": "client_credential",
            "appid": self.app_id,
            "secret": self.app_secret,
            "force_refresh": force_refresh
        }
        result = requests.post(url, data=json.dumps(data))
        print("access_token_data>>>", result.text)  # 如果公众号的IP白名单里没有会报错,里面会有当前IP
        access_token = json.loads(result.text).get("access_token")
        if not access_token:
            self.get_wechat_access_token(force_refresh=True)
            if not self.access_token:
                return
        self.access_token = access_token

    def get_all_open_id(self):
        """
        获取所有粉丝的open_id
        """
        self.get_wechat_access_token()
        next_openid = ''
        url = f"https://api.weixin.qq.com/cgi-bin/user/get?access_token={self.access_token}&next_openid={next_openid}"
        response = requests.get(url)
        data = json.loads(response.text).get("data")
        if not data:
            print("all_open_id_data", response.text)
        return data.get("openid")

    def send_message(self, json_data, appoint_open_id=None):
        body = {
            "touser": None,
            'template_id': self.temple_id,
            "topcolor": "#667F00",
            "data": json_data
        }
        url = f"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={self.access_token}"
        msgid_list = []
        # 将消息推送给指定用户
        if appoint_open_id:
            body["touser"] = appoint_open_id
            headers = {"Content-type": "application/json"}
            to_wechat_data = json.JSONEncoder().encode(body)
            print(to_wechat_data)
            res = requests.post(url=url, data=to_wechat_data, headers=headers)
            print("after_send_data>>>",res.text)
        # 将消息通知给所有用户
        else:
            # access_token = self.get_wechat_access_token()
            open_id_list = self.get_all_open_id()
            for open_id in open_id_list:
                body["touser"] = open_id
                headers = {"Content-type": "application/json"}
                to_wechat_data = json.JSONEncoder().encode(body)
                res = requests.post(url=url, data=to_wechat_data, headers=headers)
                print("after_send_data>>>",res.text)
        # 将msgid存到数据库中


if __name__ == '__main__':
    wechat_obj = WechatMessagePush(settings.WECHAT_ACCOUNT_APP_ID,settings.WECHAT_ACCOUNT_SECRET_KEY,
                                   "VvpIhSZU-9pj7w93o06M7UzMZTdMq5mFs_Rl9YcPXRw")
    data = {
        "thing2": {"value": "车库一"},
        "thing4": {"value": "一级告警"},
        "thing3": {"value": "未完成"},
        "thing6": {"value": "测试"},
        "time5": {"value": "2023-4-24"},
    }
    # 发送消息功能  这里的参数是open_id
    wechat_obj.send_message(data, "oLqI36J-8MnZ3mBsphyjSXRX5xX8")
posted @ 2023-04-24 11:39  河图s  阅读(64)  评论(0)    收藏  举报