美文网首页微信小程序开发
小程序云开发 · 消息推送功能

小程序云开发 · 消息推送功能

作者: 小西瓜Ly | 来源:发表于2020-05-09 19:45 被阅读0次

    参考官方文档:小程序订阅消息

    首先看一下效果图:


    image.png

    一、选择合适的模板消息

    在小程序管理后台功能-订阅消息-公共模板库选择自己需要的模板消息。目前小程序支持一次性订阅和长期订阅,一次性订阅是指用户订阅一次,可以为其推送一次消息;长期订阅则是可以发送多次消息,目前向政务、医疗、交通、金融、教育等线下公共服务开放,如果有需要可以在社区发帖申请,符合要求应该会给开放(这个我没申请过通过率不确定哈)。


    选择模板

    二、获取下发权限

    wx.requestSubscribeMessage调起客户端小程序订阅消息界面,返回用户订阅消息的操作结果。具体代码如下:(这里对于用户拒绝授权和关闭了设置中消息订阅主开关两种情况加了弹窗提示并直接跳转设置页)

        // 订阅消息
        subscribeMsg() {
            let that = this
            let tmplId = '你的模版ID'
            wx.requestSubscribeMessage({
                tmplIds: [tmplId],
                success(res) {
                    if (res[tmplId] == 'accept') {
                        that.cloudSendMsg();
                    } else if (res[tmplId] == 'reject') { // 用户拒绝授权
                        wx.showModal({
                            title: '温馨提示',
                            content: "您已关闭消息推送,如需要消息推送服务,请点击确定跳转设置页面打开授权后再次尝试。",
                            success: function(modal) {
                                if (modal.confirm) { // 点击确定
                                    wx.openSetting({ withSubscriptions: true })
                                }
                            }
                        })
                    }
                },
                fail(err) {
                    if (err.errCode == '20004') {
                        wx.showModal({
                            title: '温馨提示',
                            content: "您的消息订阅主开关已关闭,如需要消息推送服务,请点击确定跳转设置页面打开授权后再次尝试。",
                            success: function(modal) {
                                if (modal.confirm) { // 点击确定
                                    wx.openSetting({ withSubscriptions: true })
                                }
                            }
                        })
                    }
                }
            })
        },
        // 云函数-消息推送
        cloudSendMsg() {
            let that = this
            wx.cloud.callFunction({
                name: 'sendMsg',
                data: {
                    // 要传的数据
                }
            }).then(res => {
                console.log('cloud res:', res)
            }).catch(err => {
                console.log('err:', err)
            })
        },
    

    三、新建云函数

    新建Node.js云函数,自动生成index.js和package.json,config.json文件如果没有自动生成就自己新建一个。如果没有安装wx-server-sdk依赖的,先执行 npm install --save wx-server-sdk@latest 安装。

    新建云函数

    四、config.json权限配置

    在 config.json 中配置 openapi.subscribeMessage.send API 的权限

    {
        "permissions": {
            "openapi": [
                "subscribeMessage.send"
            ]
        }
    }
    

    五、云函数调用消息推送

    完整代码如下:

    // 云函数入口文件
    const cloud = require('wx-server-sdk');
    cloud.init();
    // 云函数入口函数
    exports.main = async (event, context) => {
        console.log(event); // 云函数中的console在云开发控制台-日志中查看
        return sendTemplateMessage(event);
    }
    
    //小程序模版消息推送
    async function sendTemplateMessage(event) {
        const {OPENID} = cloud.getWXContext(); // 用户的openId
        const templateId = '你的模板ID';
        const data = { // 这里根据自己实际订阅的消息模板来写
            'date1': {
                value: event.date,
            },
            'phrase2': {
                value: event.location,
            },
            'phrase3': {
                value: event.cond_txt,
            },
            'character_string4': {
                value: event.tmp,
            },
            'thing5': {
                value: event.tip,
            },
        };
        const sendResult = await cloud.openapi.subscribeMessage.send({
            touser: OPENID, 
            templateId: templateId,
            page: 'pages/index/index', // 点击消息跳转的小程序页面,非必填
            data: data,
            miniprogramState: 'developer' // 开发版/体验版/正式版
        })
    
        return sendResult;
    }
    

    六、上传并部署

    在云函数文件夹上右键,上传并部署


    上传并部署

    七、完成✅

    点击按钮后微信就收到消息推送啦


    收到消息推送
    几种报错情况:
    1. 错误信息为“……has no permission……”,缺少权限,检查config.json文件中是否配置了全部用到的api。
    2. 推送消息时错误代码为47003的,检查模板消息的参数是否传递正确,格式、字符串长度都可能出现问题,具体参考订阅消息参数值内容限制说明
    3. wx.requestSubscribeMessage调起失败,错误信息 {errCode: 20004, errMsg: "requestSubscribeMessage:fail the main switch is switched off"},原因为用户关闭了设置页面中消息订阅的总开关,做一下错误兼容即可。
    4. “错误码:20001,No template data return,vertify the template id exist”:模版ID错误,检查当前appId和templateId是否相对应。
    5. 云函数调用失败,走到fail里的情况,检查云函数初始化时环境是否正确
    wx.cloud.init({
      env: 'some-env-id' // 你自己的云开发环境
    })
    

    相关文章

      网友评论

        本文标题:小程序云开发 · 消息推送功能

        本文链接:https://www.haomeiwen.com/subject/zoiknhtx.html