小程序清空textarea_小程序云开发实现订阅消息

根据微信小程序官方文档说明:小程序模板消息接口将于2020年1月10日下线,将无法使用旧的小程序模板消息接口发送模板消息,取而代之的是新的一次性订阅消息和长期订阅消息

【查看旧的模板消息文档】

https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/template-message.html

【订阅消息文档】

https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/subscribe-message.html

订阅消息:一次性订阅消息和长久性订阅消息,由于长久性订阅消息很难申请到,这里以一次性订阅消息为例!

话不多说,直接进入正题,从实现订阅消息的发送(此时我们实现的用户订阅了后,服务端在某个时间内给用户发一条服务通知),为什么说是一条呢,一次性订阅消息,需要用户手动点击某个按钮去触发,弹出弹框后,若用户同意,那么在7天内我们可以给用户发送一条服务通知!再次发送时无效的哈~你也发不出去。

1、在小程序后台创建一个订阅消息的模板,如果没有订阅消息的模板可自行在公共模板库选择想要的模板!

5d8e77e337aa2e7d40144585be5d4bf4.png

2、查看选择的订阅消息模板详情,可以可到模板ID 和 订阅消息模板需要的参数

2ffff6ff8b02b6fefa7eafb50aa7ef36.png

3、创建一个云开发小程序项目

4bd1dc81af707be8acd7a624eb86b9c1.png

4、若小程序未开通云开发,可以再微信开发者工具自行开通就好了,选择免费版本的

dbad61a434ece495b02a033595a569b5.png

5、云开发允许创建2个环境一个用于生产环境,另一个可以用于测试环境,复制环境的 id

dbf079eae6e314f0445c83c554c67a13.png

云环境通了之后,后面的路就好走了,开始撸代码吧!

6、在app.json 下 的 pages 数组 中添加测试页面(pages/subscribe/subscribe),为什么说是在 app.json 中(添加完后 ctrl+s 编辑器会自动帮助你 建立 .wxml / .wxss / .js / .json 文件)

8219b79dedc9dcdd38dc965454d17308.png

7、新建云函

     getSubscribe /addSubscribe/sendSubscribe/autoSendSubscribe

5f38be8757ed48db1e19a7ea7b3dc137.png

8、在云开发控制台新建一个 subsribe 集合 用户存储 订阅消息的用户信息

9ae787207fd99c2ea14f3fd9a663ad5f.png

一 、先做一个订阅成功后就发送的服务通知

sendSubscribe 云函数的实现

const cloud = require('wx-server-sdk')cloud.init({  env: cloud.DYNAMIC_CURRENT_ENV})exports.main = async (event, context) => {  try {    const {OPENID} = cloud.getWXContext()    await cloud.openapi.subscribeMessage.send({      touser: OPENID,      // 用户点击打开的页面      page: event.path,      // 模板ID      templateId: event.templateId,      // 模板的参数(不同模板参数不一样)      // 不同字段的参数的长度也是有限制      // https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html      // 查看参数的限制      data: {        thing2: {          value: event.orderName        },        time5: {          value: event.orderDate        },        name4: {          value: event.userInfo.nickName        },        thing7: {          value: event.remark        },        phrase10: {          value: event.status        }      }    })    return {      msg: 'sendok',      code: 200    }  } catch(err) {    return err  }}

前端部分的实现

app.js

//app.jsApp({  onLaunch: function () {    if (!wx.cloud) {      console.error('请使用 2.2.3 或以上的基础库以使用云能力')    } else {      wx.cloud.init({        env:'你的小程序云环境ID',        traceUser: true,      })    }    wx.getSetting({      success: res => {        console.log(res)        if(res.authSetting['scope.userInfo']) {          // 模仿数据加载延迟          setTimeout(()=>{            wx.getUserInfo({              success: info => {                this.globalData.userInfo = info.userInfo                // 处理异步回调                if(this.userInfoCallback) {                  this.userInfoCallback(info)                }              }            })          }, 2000)        }      }    })  },  globalData: {    templateId: '你的订阅消息模板ID',    userInfo: ''  }})

/utils/fomat.js

module.exports = (date) => {  let fmt = 'yyyy-MM-dd hh:mm:ss'  let obj = {    'M+': date.getMonth() + 1,    'd+': date.getDate(),    'h+': date.getHours(),    'm+': date.getMinutes(),    's+': date.getSeconds()  }  if(/(y+)/.test(fmt)) {    fmt = fmt.replace(RegExp.$1, date.getFullYear())  }  for( let key in obj ) {    if(new RegExp('(' + key +')').test(fmt)) {      fmt = fmt.replace(RegExp.$1, obj[key].toString().length>1?obj[key]:'0'+obj[key])    }  }  return fmt}

subscribe.wxml

            茶叶下单              您已下单        未开启订阅消息权限  

subscribe.wxss

page {  height: 100%;}.container {  height: 100%;  justify-content: center;}.flex-column {  display: flex;  flex-direction: column;  justify-content: center;}textarea {  border: 1px solid #ccc;  width: 90vw;  border-radius: 12rpx;  box-sizing: border-box;  padding: 12rpx;  margin-top: 12rpx;}

subscribe.js

const app = getApp()const formatTime = require('../../utils/format.js')Page({  data: {    hasSubscribe: false,    isAlwaysReject: false,    userInfo: '',    message: ''  },  onLoad() {    // 暂时用不到,每次点击 button 获取用户信息    if(app.globalData.userInfo) {      console.log(app.globalData.userInfo)    } else {      // 处理 onLaunch 中的 延迟      app.userInfoCallback = info => {        console.log(info,'xxxxx')      }    }  },  onShow() {    // 判断当前订阅消息的权限    wx.getSetting({      withSubscriptions: true,      success: s => {        if (!s.subscriptionsSetting.mainSwitch) {          this.setData({            isAlwaysReject: true          })        } else {          // 查询当前用户 订阅消息的 状态        }      }    })  },  // 引导用户打开设置  openSetting() {    wx.openSetting()  },  // 执行用户 订阅消息的操作  doSubscribeEvent(e) {    let templateId = app.globalData.templateId    wx.getSetting({      withSubscriptions: true,      success: m => {        // 未开启订阅消息        if (!m.subscriptionsSetting.mainSwitch) {          // 这里不能直接 openSetting,需要通过某个动作去引导          wx.showModal({            title: '温馨提示',            content: '您未开启订阅消息的权限!',            success: n => {              if (n.confirm) {                wx.openSetting()              }            }          })        } else {          // 向用户 发起订阅消息 询问          wx.requestSubscribeMessage({            tmplIds: [templateId],            success: res => {              // 再次根据 getSetting 来判断用户是一次还是始终的判断              wx.getSetting({                withSubscriptions: true,                success: res2 => {                  let sets = res2.subscriptionsSetting.itemSettings                  if (sets) {                    // 用户始终取消                    if (sets[templateId] == 'reject') {                      wx.showModal({                        title: '温馨提示',                        content: '您始终拒绝了消息订阅的功能,若需要使用请在设置中开启!',                        success: s => {                          if (s.confirm) {                            wx.openSetting()                          }                        }                      })                    } else if (sets[templateId] == 'accept') {                      // 用户选择始终允许                      this.acceptOrder()                    }                  } else {                    // 用户单次允许                    if (res[templateId] == 'accept') {                      console.log('用户单次允许~')                      this.acceptOrder()                    } else {                      // 用户单次的取消                      console.log('用户单次的取消~')                    }                  }                }              })            }          })        }      }    })  },  acceptOrder() {    //发送订阅消息    var date = formatTime(new Date())    console.log(date)    wx.cloud.callFunction({      name: 'sendSubscribe',      data: {        templateId: app.globalData.templateId,        page: 'pages/subscribe/subscribe',        orderName: '祁门红茶礼盒装一斤',        orderDate: date,        remark: this.data.message || '已发送下单需求,客服会联系您~',        hasSubscribe: false,        status: '已发送订单',        userInfo: this.data.userInfo      }    }).then(res=>{      console.log(res)    }).catch(err=>{      console.log(err)    })  },  doGetUserInfo(e) {    console.log(e)    if(e.detail.userInfo) {      this.setData({        userInfo: e.detail.userInfo      })    }  },  textareaChange(e) {    this.setData({      message: e.detail.value    })  }})

测试成功

c051a189919e184091944027ad9e0941.png

二、实现用户订阅一次,在 七天内 可在云服务端给用户自动发一次 服务通知

数据存储字段说明(订阅消息参数根据订阅消息的模板进行存储):

openid(openid)

templateId(模板ID)

orderName(订单商品名称)

orderDate(订单时间)

userName(用户微信昵称)

remark(备注)

status(状态)

hasSubscribe(是否需要发送订阅消息,后面)

由于时间关系,待续...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值