在微信小程序中 使用python推送微信消息

序言:最近开始做微信小程序,需要完成通过微信小程序给用户发生消息的功能,网上搜了很多的教程,都失败了,最大的问题就是 网上提供的API错误、代码给不清楚,以及各种杂七杂八的教程,都不明朗,经过三天的研究终于跑通了,所以我记录一下我的教程。代码如下复制后更换appid,openid,secret,template_id和data中的数据就行,代码亲测过 可以跑通 有什么不会的 可以加我微信:cuicxing


```python
def send_template_message(access_token, openid, template_id, data):
    url = f"https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={access_token}"
    url = f"https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={access_token}"
    headers = {'Content-Type': 'application/json'}
    body = {
        "url": url,
        "touser": openid,
        "template_id": template_id,
        "data": data,
        "miniprogram_state": "developer"
    }
    response = requests.post(url, headers=headers, data=json.dumps(body))

    return response.json()


def user_data(request):
    # 用你的实际值替换以下变量
    appid = "自己的appid"
    secret = "自己的secret"
    access_token_url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}"
    response = requests.get(access_token_url)
    access_token = response.json()["access_token"]
    openid = " 用户的openid"  # 用户的openid
    template_id = "模板消息ID"  # 模板消息ID
    data = {
        "thing2": {"value": 'name'},  #thing2 time7 thinh14 都是模板里面的内容
        "time7": {"value":  'time'},
        "thing14": {"value": 'content'},
    }  # 模板数据

    result = send_template_message(access_token, openid, template_id, data)
    print(result)
    return HttpResponse(result)

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值