微信开发工具实现订阅消息功能
1、新建文件夹,取名为:push1
2、push1.wxml写下如下代码:
<button bindtap="dingyue">订阅</button>
3、push1.js写下如下代码:
// pages/push1/push1.js
Page({/*** 页面的初始数据*/data: {openid: '',accessToken:"",},dingyue() {var that =this;//获取授权wx.requestSubscribeMessage({tmplIds: [‘你的模板ID’],success(res) {console.log("获取授权", res);if (res[‘你的模板ID’] === 'accept') {console.log("订阅成功!")} else if (res[‘你的模板ID’] === 'reject') {console.log("订阅失败")};//发送通知,调用云函数wx.cloud.callFunction({name:'subscribes',data:{openid:that.data.openid},success:res=>{console.log("发送成功");console.log(res)},fail:res=>{console.log("发送失败");console.log(res);}})},fail(res) {console.log(res)},complete(res) {// console.log(res)}})},onLoad(){var that =this;//获取openidwx.cloud.callFunction({name: "getOpenid" //这里的name指的是之前创建的云函数getOpenid}).then(res => {console.log("获取成功openid", res);this.setData({openid: res.result.openid})}).catch(res => {console.log("获取失败openid", res)});wx.cloud.callFunction({name: 'obtainAccess',success:res=>{console.log("获取access成功");this.setData({accessToken:res.result})}});
4、新建云函数subscribes文件夹,来发送通知
5、在index.js中 写下如下代码:
const cloud = require('wx-server-sdk')
cloud.init({env:cloud.DYNAMIC_CURRENT_ENV//同上})
exports.main = async (event, context) => {try {const result = await cloud.openapi.subscribeMessage.send({touser: event.openid,//需要发送用户的openid templateId:'你的模板ID',page: 'pages/index/index',//点击通知挑转的页面lang: 'zh_CN',//语言设置data: {time4: {value:'2022年7月1日10:06:00' //key必须和模版一样!!!},thing2:{value:"点击立即签到"}}, miniprogramState: 'developer'})return result} catch (err) {return err}
}
6、创建getOpenid获取用户openid
Index.js中填写如下代码:
// 云函数入口文件
const cloud = require('wx-server-sdk')cloud.init()// 云函数入口函数
exports.main = async (event, context) => {const wxContext = cloud.getWXContext()return {event,openid: wxContext.OPENID,appid: wxContext.APPID,unionid: wxContext.UNIONID,}
}
7、点击订阅,实现功能
8、感谢大家收看,希望有所帮助