微信小步伐订阅消息提醒-云函数

打印 上一主题 下一主题

主题 1052|帖子 1052|积分 3156

微信小步伐消息订阅分2种:
1.一次性订阅:用户订阅一次就可以推送一次,如果需要多次提醒需要多次订阅。
2.长期订阅:只有公共服务领域,如政务、医疗、交通、金融和教导等。‌在用户订阅后,在很长一段时间内多次推送消息。
步骤:
1.微信公众平台选择消息模板,选用后,我的模板-查看详情里会有模板id,消息格式等信息,代码里会用到

2.微信开辟者工具
(1)订阅消息按钮
  1. // index.wxml
  2. <button bindtap="requestMessage" type="default" disabled="{{isAdded}}">{{isAdded ? '已订阅新任务提醒':'订阅新任务提醒'}}</button>
复制代码
(2)点击按钮变乱引导用户授权
  1. async requestMessage() {
  2.       wx.requestSubscribeMessage({
  3.       tmplIds: ['xxxxxx'],   // xxxxxx填选用的模板ID
  4.       success: (res) => {
  5.           if (res[templateId] === 'accept') {
  6.             // 用户同意
  7.             this.saveOpenId() // 记录用户openId,页面可以以此判断用户有无订阅消息
  8.             
  9.             wx.showToast({
  10.               title: '授权成功'
  11.             })
  12.           } else if (res[templateId] === 'reject'){
  13.             // 用户拒绝,弹窗和用户确认是否取消订阅(防止用户误操作)引导用户去设置界面重新订阅
  14.             this.setData({
  15.               showSetModel: true // 自定义弹窗
  16.             })
  17.           } else {
  18.             wx.showToast({
  19.               title: '授权订阅信息有误'
  20.             })
  21.           }
  22.          
  23.       },
  24.       fail: (err) => {
  25.           // 20004:用户关闭了主开关,无法进行订阅,引导开启
  26.           if(err.errCode === 20004) {
  27.             this.setData({
  28.               showSetModel: true
  29.             })
  30.           } else {
  31.             wx.showModal({
  32.               title: '提示',
  33.               content: err.errMsg,
  34.               showCancel: false
  35.             })
  36.           }
  37.       },
  38.       })
  39.   },
复制代码

如果用户点击拒绝,引导用户去设置页打开开关

  1. // index.wxml
  2. <view class="jumpSetModel" wx:if="{{showSetModel}}">
  3.       <view class="box">
  4.       <view class="title">提示</view>
  5.         <view class="content">您已取消订阅通知消息,如果想重新订阅该消息可以点击去设置开启</view>
  6.         <view class="button">
  7.           <button class="cancel" catchtap="closeSetModel">不了</button>
  8.           <button class="confirm" open-type="openSetting" bindopensetting="openSetCallback">去设置</button>
  9.         </view>
  10.       </view>
  11.     </view>
复制代码
  1. // 用户从设置页返回会触发下面的事件,从而得知用户有没有打开开关
  2. openSetCallback (callback) {
  3.   wx.getSetting({
  4.     withSubscriptions: true,
  5.     success: res => {
  6.       const tempId = 'xxx' //templateId
  7.             // 判断用户允许或拒绝总是保持是否推送消息的选择, 如果选择过的话再点击就不显示了,判断有没有itemSettings并且有没有这个订阅消息的模板id
  8.             if (res.subscriptionsSetting.itemSettings && res.subscriptionsSetting.itemSettings[tempId]) {
  9.               if (res.subscriptionsSetting.itemSettings[tempId] == 'accept') {
  10.                 // 打开开关
  11.                 this.saveOpenId()
  12.               } else {
  13.                 // 未打开开关
  14.               }
  15.             } else {
  16.               // 没有对应templateId的数据
  17.             }
  18.     }
  19.   })
  20. },
复制代码
如果想表现用户是否订阅过消息,需要记载用户openid,在页面进来时查询一下数据库
  1. // index.js
  2. onLoad() {
  3.   this.checkStatus()
  4. },
  5. async checkStatus() {
  6.   const currentUser = await wx.cloud.callFunction({name: 'getOpenId'})
  7.   const currentOpenId = currentUser.result // 当前用户openid
  8.   wx.cloud.database().collection('user-list').where({_openid: getApp().globalData.currentOpenId}).get().then(res => {
  9.     this.setData({
  10.       isAdded: res.data.length > 0 // 如果查询到数据就代表订阅过
  11.     })
  12.   })
  13. }
复制代码
使用到的云函数:
  1. // getOpenId  获取用户openId
  2. // 云函数入口文件
  3. const cloud = require('wx-server-sdk')
  4. cloud.init({ // 初始化云开发环境
  5.   env: cloud.DYNAMIC_CURRENT_ENV // 当前环境的常量
  6. })
  7. // 云函数入口函数
  8. exports.main = async (event, context) => {
  9.   // 返回当前用户的身份信息,用于数据库记录和查询
  10.   return cloud.getWXContext().OPENID
  11. }
复制代码
  1. // saveOpenId  保存用户openId
  2. // 云函数入口文件
  3. const cloud = require('wx-server-sdk')
  4. cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
  5. // 云函数入口函数
  6. exports.main = async (event, context) => {
  7.   const wxContext = cloud.getWXContext()
  8.   const db = cloud.database()
  9.   return await db.collection('user-list').add({
  10.     data: {
  11.       _openid: wxContext.OPENID
  12.     }
  13.   })
  14. }
复制代码
当满足需求,发送订阅消息,可以是按钮触发或者别的逻辑,下面列出设置订阅消息表现的云函数
  1. // signMessage  订阅消息设置
  2. // 云函数入口文件
  3. const cloud = require('wx-server-sdk')
  4. cloud.init()
  5. exports.main = async (event, context) => {
  6.   try {
  7.    
  8.     await cloud.openapi.subscribeMessage.send({
  9.       touser: event._openid, // 发送通知给谁的openid
  10.       data: {
  11.         thing1: {
  12.           value: event.name // 调用云函数可传参进来
  13.         },
  14.         thing3: {
  15.           value: event.title
  16.         }
  17.       },
  18.       
  19.       templateId: 'xxx', // 模板ID
  20.       page: 'pages/home/index' // 这个是发送完服务通知用户点击消息后跳转的页面
  21.     })
  22.     // 发送完毕就清空记录用户openId的表,再次查询的时候,显示未订阅,按钮可再次点击进行订阅
  23.     return await cloud.callFunction({name: 'clearTable', data: {tableName: 'user-list'}})
  24.   } catch (err) {
  25.     console.log("Error while sending message:", err);
  26.     return err
  27.   }
  28. }
复制代码
  1. // clearTable  清空数据库中的表
  2. // 云函数入口文件
  3. const cloud = require('wx-server-sdk')
  4. cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
  5. // 云函数入口函数
  6. exports.main = async (event, context) => {
  7.   const db = cloud.database()
  8.   const _ = db.command
  9.   return await db.collection(event.tableName).where({
  10.     _id: _.neq(null)
  11.   })
  12.   .remove()
  13. }
复制代码
手动触发消息推送,就写一个按钮就好,如果需要定时,比如每日签到提醒就需要用到定时器
  1. // index.wxml
  2. <view class="save" bindtap="sendMessage">发送消息</view>
  3. // index.js
  4. //发送消息
  5.   sendMessage() {
  6.           wx.cloud.callFunction({
  7.             name: 'signMessage',
  8.             //data是用来传给云函数event的数据,你可以把你当前页面获取消息填写到服务通知里面
  9.             data: {
  10.                 action: 'sendSubscribeMessage',
  11.                 title:'xxx',
  12.                 name:'xxx',
  13.                 _openid: user._id, //需要发送用户的openid
  14.             },
  15.             success: res => {
  16.                 wx.showToast({
  17.                 title: '发送成功',
  18.                 })
  19.                 resolve(res);
  20.             },
  21.             fail: err => {
  22.                 wx.showToast({
  23.                 icon: 'none',
  24.                 title: '调用失败',
  25.                 })
  26.                 reject(new Error('[云函数] [openapi] subscribeMessage.send 调用失败'))
  27.             }
  28.           })
  29.   }
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

傲渊山岳

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表