微信小程序推送模板消息demo

作者: ropon 分类: Flask 发布时间: 2019-05-11 11:59
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/5/8 13:38
# @Author  : Ropon
# @File    : send_msg.py

import requests
from westkq.utils.config import wxData


def get_access_token():
    req = requests.get('https://api.weixin.qq.com/cgi-bin/token', params=wxData, timeout=3)
    access_token = req.json().get('access_token', "")
    return access_token


def template_push(openid, form_id, kqinfo, access_token):
    data = {
        "touser": openid,
        "template_id": "",
        "form_id": form_id,
        'page': 'pages/search/search',
        "data": {
            'keyword1': {
                'value': kqinfo.get("name")
            },
            'keyword2': {
                'value': kqinfo.get("date")
            },
            'keyword3': {
                'value': kqinfo.get("banci")
            }
        },
        "emphasis_keyword": 'keyword3.DATA'
    }
    push_url = f'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={access_token}'
    result = requests.post(push_url, json=data, timeout=3)
    return result


def auto_push(nickName):
    import datetime
    riqi = str(datetime.date.today() + datetime.timedelta(days=1))
    nickName = nickName
    from westkq.models import User
    user_obj = User.query.filter_by(nickName=nickName).first()
    print(user_obj.userName)
    print(user_obj.openidval)
    if not user_obj:
        return f"{nickName}昵称对应用户不存在"
    data = {
        "ukey": "",
        "uname": user_obj.userName,
        "udate": riqi
    }
    openid = user_obj.openidval
    from westkq import create_app
    my_app = create_app()
    with my_app.app_context():
        from westkq import db
        from westkq.models import FormId
        ftemp_obj = FormId.query.filter(FormId.openidval == openid)
        if not ftemp_obj:
            return f"{nickName}昵称对应用户无FormId"
        form_id = ftemp_obj.first().formidval
        FormId.query.filter(FormId.formidval == form_id).delete()
        db.session.commit()
    req = requests.get('https://dev2.ropon.top/kaoqin', params=data, timeout=3)
    kqinfo = req.json().get("data")
    access_token = get_access_token()

    res = template_push(openid, form_id, kqinfo, access_token)
    return res.json()

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!