微信小程序訂閱消息


訂閱消息

介紹

微信小程序端的訂閱消息主要是用於對用戶的消息提醒,如訂單提醒,消息提醒等。

官方文檔入口

小程序訂閱消息

實操

第一步:獲取模板ID

  1. 登陸微信小程序后台(微信公眾平台

    功能 -> 訂閱消息

    在公共模板庫找到適合自己的模板

  2. 在我的模板中選擇其中一個模板,點擊詳情

第二步:獲取下發權限

  1. 在wxml前端定義一個授權按鈕
<button bindtap="test1">訂閱消息</button>
  1. 在js里定義觸發函數test1
  test1: function () {
    wx.requestSubscribeMessage({
      tmplIds: ['你的模板id'], 
      success(res) {
        console.log(res)
      }
    })
  },
  1. 進入手機進行真機調試

第三步:調用接口下發訂閱消息

  1. 在前端定義發送按鈕
<button bindtap="test2">發送消息</button>
  1. 雲函數

    因為雲函數不需要從小程序方獲取access_token,因此選擇雲調用是很好的選

  2. 新建雲函數sendWeather

    1. 右鍵新建note.js雲函數

  1. 配置API權限

    在雲函數的config.json文件中寫入以下代碼

    {
      "permissions": {
        "openapi": [
          "subscribeMessage.send"
        ]
      }
    }
    
  2. 編寫雲函數index.js

    const cloud = require('wx-server-sdk')
    cloud.init()
    exports.main = async (event, context) => {
      try {
        const result = await cloud.openapi.subscribeMessage.send({
          touser: event.openid,
          page: 'pages/index/index',
          lang: 'zh_CN',
          data: {
            date1: {
              value: event.date
            },
            phrase3: {
              value: event.weather
            },
            character_string4: {
              value: event.temp
            },
            thing5: {
              value: event.sugg
            }
          },
          templateId: '你的模板id',
          miniprogramState: 'developer'
        })
        console.log(result)
        return result
      } catch (err) {
        console.log(err)
        return err
      }
    }
    
  3. 雲函數參數詳解

    屬性 說明
    touser 接收者(用戶)的 openid
    templateId 所需下發的訂閱模板id
    page 點擊模板卡片后的跳轉頁面,僅限本小程序內的頁面。支持帶參數,(index?foo=bar)
    data 模板內容,注意這部分的內容非常重要
    miniprogramState 跳轉小程序類型:developer為開發版;trial為體驗版;formal為正式版;默認為正式版
    lang 進入小程序查看”的語言類型,支持zh_CN(簡體中文)、en_US(英文)、zh_HK(繁體中文)、zh_TW(繁體中文),默認為zh_CN

    注意:data中的內容必須與模板詳情中的內容相對應

  4. 雲函數調用,在頁面的js文件中編寫test2觸發函數

      test2: function () {
        wx.cloud.callFunction({
    name: 'sendWeather',
          data: {
            openid: app.globalData.openid,
            date: '2019年10月1日',
            weather: '多雲',
            temp: '1234',
            sugg: '你好',
          },
          success: res => {
            console.log(res)
          },
          fail: err => {
            console.log(err)
          }
        })
      }
    
  5. 部署到雲端

  6. 測試


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM