微信小程序——發送模板消息

微信小程序——發送模板消息

步驟一:獲取模板ID(templateId)
在微信公衆平臺(https://mp.weixin.qq.com)功能->模板消息-> 從模板庫裏獲取模板,如果沒有合適的模板,可以申請添加新模板,審覈通過後可使用。拿到模板id
在這裏插入圖片描述
在這裏插入圖片描述
步驟二:頁面搭建:頁面的 <form/> 組件,屬性report-submit爲true時,可以聲明爲需發模板消息,此時點擊按鈕提交表單可以獲取formId,用於發送模板消息。或者當用戶完成支付行爲,可以獲取prepay_id用於發送模板消息.

<form bindsubmit="formSubmit" report-submit='true'>
  <view class="section">
    <view class="section__title">input</view>
    <input name="input" placeholder="please input here" />
  </view>
  <view class="btn-area">
    <text>---模板消息發送要在真機上測試,否則不能獲取正確的formid----</text>
    <button formType="submit">發送模板消息</button>
  </view>
</form>

步驟三:獲取 access_token(發送模板消息的接口需要用到的參數)
開發者可以使用 AppID 和 AppSecret 調用本接口來獲取 access_token。 AppID 和 AppSecret 可登錄微信公衆平臺官網-設置-開發設置中獲得(需要已經綁定成爲開發者,且帳號沒有異常狀態)。AppSecret 生成後請自行保存,因爲在公衆平臺每次生成查看都會導致 AppSecret 被重置。注意調用所有微信接口時均需使用 https 協議。
在這裏插入圖片描述
接口地址:
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET(填寫對應的appid和secret)
參數:
grant_type:獲取 access_token 填寫 client_credential
appid和secret都是通過上面獲取到的

/**
   * 頁面的初始數據
   */
  data: {
    access_token:''
  },
 
  /**
   * 生命週期函數--監聽頁面加載
   */
  onLoad: function (options) {
    var _this = this;
    wx.request({
      url: 'https://api.weixin.qq.com/cgi-bin/token',
      data:{
        grant_type:'client_credential',
        appid:'',  //填寫對應的appid
        secret:'' //填寫對應的secret
      },
      method:'get',
      success:function(res){
        _this.setData({
          access_token: res.data.access_token  //得到access_token
        })
      }
    })
  }

步驟三:獲取openid(發送模板消息的接口需要用到的參數)
openid是在app.js中微信登錄成功後返回的code參數(用戶登錄憑證(有效期五分鐘)。開發者需要在開發者服務器後臺調用 api,使用 code 換取 openid 和 session_key 等信息)來獲得openid。代碼如下:

//app.js
App({
  onLaunch: function () {
    // 展示本地存儲能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    let _this = this;
    // 登錄
    wx.login({
      success: res => {
        // 發送 res.code 到後臺換取 openId, sessionKey, unionId
        console.log(res.code)
        var code = res.code
        if (res.code) {
 
          //發起網絡請求
          wx.request({
            url: 'https://api.weixin.qq.com/sns/jscode2session',
            data: {
              appid: '',
              secret: '',
              js_code: code,
              grant_type: 'authorization_code'
            },
            success: function (res) {
              // console.log(res.data.openid)
              _this.globalData.openid = res.data.openid;
            }
          })
        } else {
          console.log('登錄失敗!' + res.errMsg)
        }
      }
    })

步驟四:發送模板消息
接口地址:(ACCESS_TOKEN 需換成上文獲取到的 access_token)
https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN

請求方式:post請求
參數:
touser(必填):        接收者(用戶)的 openid
template_id(是):   所需下發的模板消息的id(上面已經說明)
page(否):            點擊模板卡片後的跳轉頁面,僅限本小程序內的頁面。支持帶參數,(示例index?	foo=bar)。該字段不填則模板無跳轉。
form_id(是):        表單提交場景下,爲 submit 事件帶上的 formId;支付場景下,爲本次支付 的 prepay_id
data(是):            模板內容,不填則下發空模板
color(否):        模板內容字體的顏色,不填默認黑色
emphasis_keyword(否):模板需要放大的關鍵詞,不填則默認無放大

form表單提交時,執行formSubmit函數:

formSubmit: function (e) {
    var _this=this;
    console.log(_this.data.access_token,'access_token')
    console.log(app.globalData.openid,'openid')
    console.log(e.detail.formId,'formid');//formid是設置了form的屬性report-submit爲true時,通過e.detail.formId獲取
    wx.request({
      url: 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + _this.data.access_token
      data:{
        "touser": app.globalData.openid,  //用戶的openid
        "template_id": 'tbi5uRB44xz7pwZQWzPYmn7FSizCs-9I3X4JUWudEfc', //用戶的模板id
        "form_id": e.detail.formId,  //表單提交場景下,爲 submit 事件帶上的 formId;支付場景下,爲本次支付的 prepay_id
        "data": {   //模板內容
          "k eyword1": {
            "value": "339208499"
          },
          "keyword2": {
            "value": "2018年3月26日"
          },
          "keyword3": {
            "value": "1000元"
          },
          "keyword4": {
            "value": "15999999999"
          }
        },
        "emphasis_keyword": "keyword3.DATA" 
      },
      method:'post',
      header: {
        'content-type': 'application/json' // 默認值
      },
      success: function (res) {
        console.log(res.data)
      }
    })
  },

到這裏,模板消息就可以成功發送了,但是在開發者工具上測試發現formId的值是‘the formId is a mock one’,查了一下:

formId需要在真實的手機上纔會生成,
小程序開發工具是一個模擬環境,
所以獲取不到,
會提示‘the formId is a mock one’

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章