微信小程序云开发定时推送订阅消息

微信小程序云开发定时推送订阅消息

1.找到自己想要的模板

(1)点击订阅消息
在这里插入图片描述
(2)点击公共模板库,然后找到想要选用的模板,点击选用。

在这里插入图片描述
(3)在我的模板里面,复制模板id。
在这里插入图片描述

如果找不到想要用的模板,可以在公共模板的最后一页,点击下图中圈出来的,去申请自己想要的模板。
在这里插入图片描述

2.代码部分

(1)云函数部分的代码

config.json
云函数配置文件,用于定时提醒,具体规则可以去参考一下微信的定时触发器

"permissions": {
    "openapi": ["uniformMessage.send"] //使用subscribeMessage.send
  },
  "triggers": [
    {
      "name": "myTrigger",
      "type": "timer",
      "config": "0 0 9 * * * *" 
    }
  ]

index.js

// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate
// 云函数入口函数
exports.main = async (event, context) => {
  try {
    //订餐提醒
    const userList =await db.collection('user').where({
      order_type: _.not(_.eq('a'))
    }).get()
    console.log("userList",userList)
    console.log("time",timeStampToTime(new Date()))
    //循环消息队列
    const sendPromises=userList.data.map(async user=>{
      try {
         // 发送订阅消息
         await cloud.openapi.subscribeMessage.send({
          "touser": user.openId, //要推送给那个用户
          "page": 'pages/login/login',
          "data": {//推送的内容
            "date2": {
              "value": timeStampToTime(new Date())
            },
            "phrase3": {
              "value": user.user_name
            },
            "thing4": {
              "value": '如果已经点餐,请忽略该消息,点击查看详情'
            },
            "thing5": {
              "value": '如果已经点餐,请忽略该消息,点击查看详情'
            }
          },
          "templateId": '模板id',//模板id
          "miniprogramState": 'trial' //developer为开发版;trial为体验版;formal为正式版;默认为正式版
        })
      } catch (err) {
        console.log(err)
        return err
      }
      return Promise.all(sendPromises)
    })
  } catch(err){
    console.log(err)
    return err
  }
}
//转换成消息模版所需要的格式,date 年/月/日 时:分:秒
function timeStampToTime(date) {
  const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : `0${n}`
  }
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}


(2)页面逻辑层js代码

这个事件触发需要与按钮绑定,不能再页面初次渲染时(也就是onLoad函数)进行触发。

 //去食堂管理页面
  toCanteen(e) {
    //查询用户是否选择了一只接收了订阅消息
    wx.getSetting({
      withSubscriptions:true,
      success:res=>{
        console.log(res.subscriptionsSetting)
        console.log(!res.subscriptionsSetting.mainSwitch)
        console.log(res.subscriptionsSetting.itemSettings)
        // 订阅消息里面的itemSettings属性是否为空
        if(res.subscriptionsSetting.itemSettings==null){
          this.requestSubscribeMessage()
        }
        else{
          //关于用户对提醒模版id的授权是否为接受
          if (res.subscriptionsSetting.itemSettings['模板id']=='accept')  {
            console.log('用户点击了“总是保持以上,不再询问”')
          } else {
            console.log('用户没有点击“总是保持以上,不再询问”,每次都会调起授权页面')
            this.requestSubscribeMessage()
          }
        }
      }
    })
    wx.navigateTo({
      url: '/pages/canteen/canteen'
    })
  },
  //获取订阅消息授权
  requestSubscribeMessage(){
    wx.requestSubscribeMessage({
      tmplIds: ['模板id'],
      success:res=>{
        console.log("订阅消息",res)
      },
      fail:err=>{
        this.showtoast('出错了')
        console.log("订阅消息失败",err)
      }
    })
  }

自此,定时推送订阅消息就实现了。

### 微信小程序定时触发推送订阅消息实现方法 #### 配置云函数权限 为了使云函数能够执行定时推送操作,需在`config.json`文件中声明必要的API权限。具体来说,在`permissions`字段下添加`uniformMessage.send`权限以便调用微信统一下发接口发送订阅消息[^3]。 ```json { "permissions": { "openapi": [ "uniformMessage.send" ] } } ``` #### 设置定时触发器 通过定义`triggers`数组项创建一个名为`myTrigger`的定时触发器,其类型设定为`timer`,并按照cron表达式的语法指定触发时间规则。例如下面的例子表示每天早上9点触发一次: ```json "triggers": [ { "name": "myTrigger", "type": "timer", "config": "0 0 9 * * ?" } ] ``` 此部分同样位于`config.json`内。 #### 编写云函数逻辑 编写实际处理业务逻辑的JavaScript代码作为云函数主体。该函数负责接收来自定时触发器的通知,并据此向目标用户群组发出订阅消息。通常情况下会涉及到查询数据库获取待通知用户的列表以及构建符合要求的消息模板等工作[^5]。 ```javascript // index.js - Cloud Function Entry Point const cloud = require('wx-server-sdk') cloud.init() exports.main = async (event, context) => { try { const result = await cloud.openapi.subscribeMessage.send({ touser: 'OPENID', // 用户openid page: '/index/index', data: { keyword1: { value: '测试标题' }, keyword2: { value: '这是描述内容' } }, templateId: 'TEMPLATE_ID' // 订阅消息模版id }) console.log(result) } catch(err){ console.error(err) } }; ``` 上述代码片段展示了如何利用微信提供的SDK发起一条订阅消息请求给特定用户。其中`touser`, `page`, 和`templateId`参数均需依据实际情况调整[^4]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值