微信小程序(订阅消息)功能

小程序模板消息即将被废弃掉,于是有了新接口wx.requestSubscribeMessage

订阅消息文档

步骤:

1、获取用户openid 、access_token
2、获取模板 ID
3、获取下发权限(api)
4、发送订阅消息 (api)

模板id


 

 

小程序代码:

获取下发权限:

// login.js
requestMsg(){
 return new Promise((resolve, reject) => {
 wx.requestSubscribeMessage({
 tmplIds: ["MUtLwsw0xCndRULTgNHiXwGDyHJ-ZwAFL-b3kALcl0c"],
 success: (res) => {
  if (res['MUtLwsw0xCndRULTgNHiXwGDyHJ-ZwAFL-b3kALcl0c'] === 'accept'){
  wx.showToast({
  title: '订阅OK!',
  duration: 1000,
  success(data) {
  //成功
  resolve()
  }
  })
  }
 },
 fail(err) {
  //失败
  console.error(err);
  reject()
 }
 })
 })
 }
// index.wxml
<button class="v-btn mt40" bindtap="sendMsg">发生订阅消息</button>

// index.js 
// 点击发生订阅
sendMsg:function(e){
 wx.request({
 url: 'https://cff.mynatapp.cc/wxXcx/sendMessage',
 method: 'POST',
 data: { },
 header: {
 'content-type': 'application/json' // 默认值
 },
 success(res) {
 console.log(res)
 }
 })
 }

nodejs(koa2)代码:

发送订阅消息:

// index.js
const router = require('koa-router')()
const request = require('superagent')
let AppID = 'xxxxx'
let AppSecret = 'xxxxx'
let access_token = 'xxxxx'
let openid = 'xxxxx'

// 点击发生订阅消息
router.post('/wxXcx/sendMessage', async (ctx, next) => {
 let requestData ={
 "touser": openid,
 "template_id": "MUtLwsw0xCndRULTgNHiXwGDyHJ-ZwAFL-b3kALcl0c",
 "page": "index",
 "data": {
  "phrase1": {
  "value": "王小二"
  },
  "date5": {
  "value": "2019年10月1日 15:01"
  },
  "phrase4": {
  "value": "王老师"
  },
  "thing2": {
  "value": "ps入门到精通"
  },
  "character_string6": {
  "value": "1/10"
  }
 }
 }

 // 2、发送模板消息
 let res = await request
  .post(`https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${access_token}`)
  .send(requestData)
  .set('Accept', 'application/json')

 console.log(res)

 ctx.body = { 
 code: '200', 
 data: null, 
 msg: '操作成功'
 }
})



 

 

总结

以上所述是小编给大家介绍的微信小程序(订阅消息)功能,希望对大家有所帮助

 

 

 

 

原文链接:https://blog.csdn.net/qq_14993375/article/details/102693209

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.duanlonglong.com/qdjy/1127.html