Q:微信小程序一次性订阅消息(前台收集)

说明:官方文档(https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/subscribe-message.html)很详细,在此简单记录下

需求:虽说是一次性订阅,但前台可以通过bindtop点击触发微信订阅api收集用用户点击订阅次数。方便后台可以发更多的消息

第一步,定义全局模板ID 和 收集方法

// 统一模板ID
export const COMPLATEMESSAGE = 'agFxPZurLwE5CYrFTGTWcgXuknS06sVWfVdUdQaDhcF'

export function onSubscribe(templateIds, e){
  return new Promise((resolve, reject) => {
    wx.requestSubscribeMessage({
      tmplIds: [templateIds],
      success(res) {
        console.log('获取订阅消息权限',res)
        // 申请订阅成功
        if (res.errMsg === 'requestSubscribeMessage:ok') {
          resolve(true)
        }
      },
      fail (err){
        reject(false)
        console.log(err)
      }
    });
  })
}

第二步:页面点击收集

import { execteGet,onSubscribe, COMPLATEMESSAGE, } from '@/utils/require'

goDetail: async function(e){
       // 页面有跳转做点击同步,防止用户未允许页面跳走
      await onSubscribe(COMPLATEMESSAGE)
      wx.navigateBack({
          delta: 1
      });
}    
changeState: async function(e){
       // 页面无跳转点击做异步,requestSubscribeMessage收集方法有一秒延时体验不好
      onSubscribe(COMPLATEMESSAGE)
}   

 requestSubscribeMessage方法使用时最好处理下兼容,不然弹框没有默认允许勾,一直弹。或者微信开放平台设置基础版本 > 2.9.2

猜你喜欢

转载自www.cnblogs.com/chuanq/p/11956252.html
今日推荐