当前位置:   article > 正文

python --发送微信订阅消息,公众号模板消息_python微信公众号订阅通知

python微信公众号订阅通知

小程序订阅消息

获取accesstoken

class AuthgetAccessToken(object):
'''获取小程序access_token'''

    def __init__(self):
        self.url = f'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}'
        self.template_id = template_id
        self.page = None
        self.miniprogram_state = 'developer'  # formal

    def get_access_token(self):
        '''获取accesstoken'''
        res = requests.get(url=self.url).json().get('access_token')
        if res:
            return res
        raise IOError('IO ERROR')

    def send_mes(self, openid, data):
        '''发送消息'''
        datas = {
            "touser": openid,
            "template_id": self.template_id,
            "page": self.page,
            "miniprogram_state": self.miniprogram_state,
            "lang": "zh_CN",
            "data": data
        }
        access_token = self.get_access_token()
        url_ = f'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={access_token}'
        res = requests.post(url=url_, json=datas).json()
        return res
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

视图

@api_view(['POST', ])
def send_mes(request: HttpRequest) -> HttpResponse:
    '''发送消息'''
    user_id = request.data.get('USER_ID')
    activity_name = request.data.get('activity_name')  # 发送内容
    if len(activity_name) > 20:
        return Response({'code': 500, 'message': '发送字符不可大于20'})

    start_date = request.data.get('start_date')

    user = User.objects.filter(user_id=user_id).first()
    if user:
        if user.openid:
            t = time.strftime('%Y-%m-%d-%H:%M').split('-')
            t = t[0] + '年' + t[1] + '月' + t[2] + '日' + ' ' + t[3] 
            send = AuthgetAccessToken()
            data = {
                "thing1": {
                    "value": activity_name},
                "date2": {
                    "value": start_date},
                "time7": {
                    "value": t,
                }
            }
            res = send.send_mes(openid=user.openid, data=data)
            if res.get('errcode') == 0 or not res.get('errcode'):
                response = {'code': 200, 'message': '发送成功'}
            elif res.get('errcode') == 43101:
                response = {'code': 500, 'message': '用户拒绝接受消息,如果用户之前曾经订阅过,则表示用户取消了订阅关系'}
            elif res.get('errcode') == 47003:
                response = {'code': 500, 'message': '模板参数不准确,可能为空或者不满足规则'
                    , 'errmsg': res.get('errmsg')}
            else:
                response = {'code': 500, 'message': res.get('errcode')}
        else:
            response = {'code': 500, 'message': '请确保当前用户至少授权登陆过一次'}
    else:
        response = {'code': 500, 'message': '找不到用户对象'}
    return Response(response)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

公众号模板消息

class SendMessage(object):
    '''发送消息'''

    def __init__(self):
        res = requests.get(
            f'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={gzh_appid}&secret={gzh_secret}').json()
        logger.debug(f'获取token:【{res}】')
        self.access_token = res.get('access_token')


    def send(self, body) -> None:
        '''发消息'''
        mes = requests.post(url=f'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={self.access_token}',
                            json=body).json()
        logger.success(f'发送结果【{mes}】')

    def _async_send_message(self, body) -> None:
        '''异步发送消息'''
        threading.Thread(target=self.send, args=(body,)).start()

    def appointment_successful_message(self, dingdan_instance) -> None:
        '''预约成功通知'''
        riqi = dingdan_instance.riqi.split('-')
        hour = dingdan_instance.shijian.split(':')[0]
        riqi = f'{riqi[0]}{riqi[1]}{riqi[2]}{dingdan_instance.shijian}'

        body = {
            "touser": dingdan_instance.user.gzh_open_id,
            "template_id": "tM_wzFhAkia1I6TQUzt8oZrYclNvXlNityrwjAFjQaA",
            "appid": gzh_appid,
            "data": {
                "thing18": {
                    "value":dingdan_instance.yuyuekecheng.biaoti,
                # "color": "#666666"
                },
            "character_string9": {
                "value": dingdan_instance.dingdanhao
                },
            "time23": {
                "value": riqi
                },

            "thing37": {
                "value": dingdan_instance.mendian.mingzi
                }
            }
        }
        self._async_send_message(body)

    def appointment_cancellation_message(self, dingdan_instance) -> None:
        '''取消预约通知(开课前两小时依然处于等位中 取消)'''
        riqi = dingdan_instance.riqi.split('-')
        hour = dingdan_instance.shijian.split(':')[0]
        riqi = f'{riqi[0]}{riqi[1]}{riqi[2]}{dingdan_instance.shijian}~{hour}:45'

        body =  {
                   "touser": dingdan_instance.user.gzh_open_id,
                   "template_id":"EHRfXDhdG5LtRHxXWHRw2wJUgkUFZvrGk80Go5pmc9M",
                   "appid": gzh_appid,
                   "data":{
                           "thing13":{
                               "value":dingdan_instance.yuyuekecheng.biaoti,
                           },
                           "time14": {
                               "value":riqi
                           },
                           "time5": {
                               "value": time.strftime('%Y年%m月%d日 %H:%M:%S')
                           },

                           "number2": {
                               "value": dingdan_instance.dingdanhao
                           }
                   }
               }
        self._async_send_message(body)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/70733
推荐阅读
相关标签
  

闽ICP备14008679号