1. 程式人生 > >微信小程式——傳送模板訊息

微信小程式——傳送模板訊息

步驟一:獲取模板ID 1、通過模版訊息管理介面獲取模版ID(詳見模版訊息管理 2、在微信公眾平臺手動配置獲取模版ID     登入 https://mp.weixin.qq.com  獲取模板,如果沒有合適的模板,可以申請新增新模板,稽核通過後可使用,

步驟二:頁面搭建         頁面的 <form/> 元件,屬性report-submittrue
時,可以宣告為需發模板訊息,此時點選按鈕提交表單可以獲取formId,用於傳送模板訊息。或者當用戶完成支付行為,可以獲取prepay_id用於傳送模板訊息。

        我寫了個充值成功的demo,使用form元件提交表單是傳送模板訊息,頁面如下(比較醜,主要測試):

        

html

<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 引數: grant_type:獲取 access_token 填寫 client_credential appid和secret都是通過上面獲取到的

當前頁面載入時獲取access_token(下面的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:'',
        secret:''
      },
      method:'get',
      success:function(res){
        _this.setData({
          access_token: res.data.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,
        "template_id": 'tbi5uRB44xz7pwZQWzPYmn7FSizCs-9I3X4JUWudEfc',
        "form_id": e.detail.formId,
        "data": {
          "k eyword1": {
            "value": "339208499",
            "color": "#173177"
          },
          "keyword2": {
            "value": "2018年3月26日",
            "color": "#173177"
          },
          "keyword3": {
            "value": "1000元",
            "color": "#173177"
          },
          "keyword4": {
            "value": "15999999999",
            "color": "#173177"
          }
        },
        "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’
然後在真機中測試就成功了: