首页 > 编程语言 >微信小程序消息推送(订阅消息)接入 前端+后端

微信小程序消息推送(订阅消息)接入 前端+后端

时间:2023-03-17 13:57:06浏览次数:52  
标签:订阅 微信 access token api 消息 res 推送 data

1. 第一步是需要在微信公众平台配置,具体参考官方文档订阅消息配置

image

2.然后需要在前端代码中调用微信消息订阅api,调起客户端小程序订阅消息界面,具体api参考订阅消息api

点击查看代码
wx.requestSubscribeMessage({
  tmplIds: [''],
  success (res) { }
})

3.后台调用,根据相应触发条件调用微信发送订阅消息api。首先调用获取access_token的api 获取接口调用凭据 ,然后根据获取到的access_token调用发送订阅消息api,文档参考:服务端订阅消息api

后台用的是node.js写的,看参考以下代码

点击查看代码
const axios = require('axios')
const baseApi = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send"
router.get('/sendmsg', function (req, res) {


    axios.post("https://api.weixin.qq.com/cgi-bin/stable_token",{
        "grant_type": "client_credential",
        "appid": "wxcc5c77f7c83b70c3",
        "secret": "5adf6eedc5b5d6eb1f7d93ab8b2ed046",
        "force_refresh": false
    }).then((resT)=>{
        res.send(resT.data)
        if (resT.data.access_token) {
            console.log(resT.data);
            let access_token = resT.data.access_token
            axios.post(baseApi + "?access_token=" + access_token, {
                "touser": "o5CWU5EZCHx4d1021eCWJBGthI8k",
                "template_id": "0a0GLcJOQUsb3er_LIeWROvP5HzEY0jjtSt9ItlhjK8",
                "page": "pages/index/index",
                "data": {
                    "thing2": {
                        "value": "2023 争创辉煌"
                    },
                    "thing4": {
                        "value": "上海标源2023誓师大会"
                    },
                    "thing6": {
                        "value": "经开区15大街255号"
                    },
                    "thing11": {
                        "value": "奔波儿灞"
                    },
                    "date5": {
                        "value": "2023-03-08"
                    }
                }
            }).then((resMsg) => {
                console.log(resMsg.data);
                if (resMsg.data.errcode == 0) {
                    res.send("发送成功!")
                }else{
                    res.send("发送失败!"+JSON.stringify(resMsg.data))
                }
            })
        } else {
            res.send(resT.data)
        }
    })

标签:订阅,微信,access,token,api,消息,res,推送,data
From: https://www.cnblogs.com/yanzhenkui-blogs/p/17226475.html

相关文章