微信小程序之發送模板消息(通過openid推送消息給用戶)

一、獲取access_token
access_token是接口調用的憑證,目前有效期爲兩個小時,需要定時刷新,重複獲取將導致上次獲取的access_token失效。(注:不建議每次調用需要access_token的接口,都去重新獲取access_token,會導致失敗)
獲取access_token的接口地址:

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

返回參數格式:

{"access_token": "ACCESS_TOKEN", "expires_in": 7200}

二、發送模板消息
先在微信公衆平臺選用怒需要的模板id,例如
選用模板消息:

https://mp.weixin.qq.com/wxopen/tmplmsg?action=self_list&token=264012870&lang=zh_CN

選用的是購買成功的模板,關鍵字可以自己定義順序,如果不符合你的情況,還可以自定義關鍵字

選用好了之後,可以在我的模板中查看。然後將其模板id複製過來。
類似於這樣 : _CfGS7SqVyNPg9Op8OXzMp6aOl7X9rCkrRfiMcccms8

發送模板的消息接口地址:

https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN

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

例如
html

 <form bind:submit="testSubmit" report-submit="true">
      <button formType="submit">發送模板消息</button>
 </form>

js

testSubmit:function(e){
    var self= this;
    let _access_token = '5_E1pZJQzTC-lC0r-JJz9wVAZv5Zv22CNtmV_7C1T0sqC9TV7mGE4FTmDX2B0PVM4LaGtaTfXwzfJLnD7fDKTg8DOICJNkKBQgn_Ot2zYmBJyY1g1VXoBNdtwUE0QaP8_9tWlbR-Zq7L1OyrrPKCIjAEAOGM';
    let url='https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='+_access_token

;    let _jsonData = {
      access_token: _access_token,
      touser: openid,
      template_id: '_CfGS7SqVyNPg9Op8OXzMp6aOl7X9rCkrRfiMcccms8',
      form_id: e.detail.formId,
      page: "pages/index/index",
      data: {
        "keyword1": { "value": "測試數據一", "color": "#173177" },
        "keyword2": { "value": "測試數據二", "color": "#173177" },
        "keyword3": { "value": "測試數據三", "color": "#173177" },
        "keyword4": { "value": "測試數據四", "color": "#173177" },
      }
    }
    wx.request({
        url: url,
        data: data,
        method: method,
        success: function (res) {
          console.log(res)
        },
        fail: function (err) {
          console.log('request fail ', err);
        },
        complete: function (res) {
          console.log("request completed!");
        }

 })

結果: 
類似於這種 


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