如何实现小程序的订阅消息功能
本篇文章将会通过一个小案例实现订阅消息功能
1 订阅消息
订阅消息能力是小程序能力中的重要组成,以便实现服务的闭环和更优的体验。
订阅消息推送位置:服务通知
订阅消息下发条件:用户自主订阅
订阅消息卡片跳转能力:点击查看详情可跳转至该小程序的页面
2 实现步骤
1.获取模板ID
在微信公众平台手动配置获取模板 ID,如果没有合适的模板,可以申请添加新模板,审核通过后可使用
2.获取下发权限
使用小程序API wx.requestSubscribeMessage(),详细使用请看官方文档。
3.调用接口下发订阅消息
小案例代码
messageSubscription: function () {
    // 订阅消息
    let that = this;
    //获取下发权限
    wx.requestSubscribeMessage({
    tmplIds: ['模板ID名'],  // 模板ID
    success (res1) {
        if(res1['模板ID名'] == "accept"){
            console.log('消息订阅成功');
            // 调用后端订阅消息接口   
            that.acceptMessage(); 
        }else {
        console.log('拒绝推送订阅消息');
        wx.showModal({
            title: '温馨提示',
            content: '请允许我们向您发送订阅消息,请打开设置勾选订阅消息,这样能够随时接收到提醒',
            showCancel: false,
            success (res2) {
                console.log(res2);
                wx.openSetting({
                    withSubscriptions: true,
                    success(res3) {
                    console.log(res3);
                        // 调用后端订阅消息接口
                        that.acceptMessage();     
                    }
                })
            }
        })
        }
    },
    fail (res) {
        console.log(res);
    },
    complete (res) {
        console.log(res);
    }
    })
},
acceptMessage: function () {
    // 后端订阅消息调用接口
    let that = this;
    let openId='';
    wx.getStorage({
    key: 'openid',
    success(res) {
        openId = res.data;
        console.log('openid:'+ openId);
        // 调用后端订阅消息接口
        wx.request({
            url: 'https:xxxxxx' + openId, 
            header: {
            'content-type': 'application/json'
            },
            success (res) {
                console.log('调用后端返回的订阅消息结果');
                console.log(res.data)
                wx.showToast({
                    title: '订阅成功',
                    icon: 'success',
                    duration: 3000
                })
            },
            fail(res){
                console.log('调用后端接口失败')
                console.log(res)
                wx.showToast({
                    title: '订阅失败',
                    duration: 3000
                })   
            }
    })
    }
})       
}
      
      
- 本文作者: étoile
 
- 版权声明: 本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。转载请注明出处!