微信模板消息的使用


上星期公司項目需求加入模版消息推送功能,今天在這整理一下:

微信的模版消息分為公眾號的和小程序的。它們看起來差不多,但還是有點區別的:

模板推送位置:公眾號的是本公眾號頁面,小程序的是服務通知。

模板下發條件:公眾號可以像我們在原生app里推送通知一樣進行下發,客戶無需主動觸發;小程序里需用戶在微信體系內與頁面有交互行為后觸發,小程序不能推送消息,只有用戶主動發起的事件並確認需要收到后續反饋,才會收到消息。

模版次數的限制:公眾號有10w+,根據粉絲量來決定;小程序官方文檔里說的什么提交表單7天內推送條數有限,支付一次可以推送3條,如果不懂就每次都提交,這樣就沒有限制了。

只是小程序的模版消息必須使用表單<form>提交,因為需要用到form_id參數。這個參數需要多加注意,並且只能在真機上測試,要不這個form_id參數值你是拿不到的(報錯:the formId is a mock one);它們的api是不同的。

第一步,獲取用戶openId。有兩個方法,思路都一樣:調wx.login得到code(一次性的,不可重復利用),由code換取openId(這步有兩個方法,都應該在后台完成,前台測試時,請在開發工具里按如下配置)。一般使用第二種方法,因為它還可以返回用戶的基本信息,這貌似是一般小程序必用到的信息。第一種方法只會獲取到openId、session_key。

方法一:

wx.login({
  success: function (logincode) {
    if (logincode.code) {
      wx.request({
        url: 'https://api.weixin.qq.com/sns/jscode2session?appid=yourappid&secret=yoursecret&js_code=' + logincode.code + '&grant_type=authorization_code',
        header: {
          'content-type': 'application/json'
        },
        success: function (resle) {
          that.globalData.openId_true = resle.data.openid;
        }
      })
    }
  }
});

方法二:

注意點:當 withCredentials 為 true 時,要求此前有調用過 wx.login 且登錄態尚未過期,此時返回的數據會包含 encryptedData, iv 等敏感信息;當 withCredentials 為 false 時,不要求有登錄態,返回的數據不包含 encryptedData, iv 等敏感信息。

wx.login({
  success: function (loginres) {
    if (loginres.code) {

      wx.getUserInfo({
        withCredentials: true,
        lang: 'zh_CN',
        success: function (res) {
          wx.request({
            url: 'https://le.beiebi.com/lkt/api/scanLogin/appletScanLogin',
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: { code: loginres.code, encryptedData: res.encryptedData, iv: res.iv, unionid: '' },
            success: function (res) {
              openId = res.userInfo.openId
            }, fail: function () {

            }
          })
        }, fail: function () {

        }
      })
    }
  }
})

 

第二步,獲取access_token(也應該在后台完成)。

注意點:access_token有效時限兩個小時,每天的生成次數有限(2000次),所以需要在后台做緩存,這里只是模擬一下。

  getAccess_token:function (client_credential, appid, secret,formId) {

    var that = this;
    if (that.data.isTime){
      var dic = {
        grant_type: client_credential,
        appid: appid,
        secret: secret,
      }

      util.httpsGetRequest("https://api.weixin.qq.com/cgi-bin/token", dic, function (success) {

        console.info('-----access_token==' + success.access_token);
        access_token = success.access_token;
        wx.setStorageSync('access_token',success.access_token);
        that.sendMessage(formId);

        that.data.isTime = false;
        var date = new Date();
        that.data.timestamp = date.getTime();
        that.countdown(that, that.data.timestamp + 7200);
      })
    } else {
      access_token = wx.getStorageSync('access_token');
      that.sendMessage(formId);
    }
  },

 

第三步,發送模版消息。

注意點:下面寫了兩個字典裝參數,其中dic1為公眾號發送模版消息需要的參數,dic為小程序發送模版消息需要的參數。其中的formId,表單提交場景下,為 submit 事件帶上的 formId(e.detail.formId);支付場景下,為本次支付的 prepay_Id。

sendMessage: function (formId) {

  var dic1 = {
    "touser": app.globalData.openId_true,
    "template_id": "9I2cE23DPBi_nlYZLSJT-YK_DAMvGmmwyOnYTiSD523",
    "miniprogram": {
      "appid": appid,   //小程序的appid
      "pagepath": "pages/index/qqq/aaa/aaa?analysisReportId=2050&openId=1"
    },
    "color": "#173177",

    "data": {
      "first": {
        "value": "恭喜你購買成功!",
        "color": "#173177"
      },
      "keyword1": {
        "value": "vip1867332110254",
        "color": "#173177"
      },
      "keyword2": {
        "value": "深圳一起賺錢科技有限公司",
        "color": "#173177"
      },
      "keyword3": {
        "value": "1500元",
        "color": "#173177"
      },
      "remark": {
        "value": "歡迎再次購買!",
        "color": "#173177"
      }
    }
  }

  var dic = {
    "touser": app.globalData.openId_true,
    "template_id": "9I2cE23DPBi_nlYZLSJT-YK_DAMvGmmwyOnWFDFfgd”,
    "page": "pages/index/qqq/aaa/aaa?analysisReportId=2050&openId=1",
    "form_id": formId,
    "data": {
      "keyword1": {
        "value": "樂奔快遞",
        "color": "#173177"
      },
      "keyword2": {
        "value": "2017年11月13日 12:00",
        "color": "#173177"
      },
      "keyword3": {
        "value": "iPhone11",
        "color": "#173177"
      },
      "keyword4": {
        "value": "12545568461025",
        "color": "#173177"
      },
      "keyword5": {
        "value": "貝貝",
        "color": "#173177"
      }
    },
    "emphasis_keyword": "keyword1.DATA"
  }

//公眾號發送模版消息的api為:
https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN

  util.httpsPostRequest("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + access_token, dic, function (success) {
    console.info('access_tokenerrmsg==' + success.errmsg);
  })
},

 

其余代碼:

//表單提交
formSubmit: function (e) {
  if (wx.getStorageSync('isTime') != '') {
    this.data.isTime = wx.getStorageSync('isTime');
    console.log('sync=isTime=', wx.getStorageSync('isTime'));
    console.log('sync=access_token=', wx.getStorageSync('access_token'));
  }

  this.getAccess_token('client_credential', appid, secret, e.detail.formId);
},
countdown: function (that, time) {
  if (time < that.data.timestamp + 60) {
    console.log('=shijiandao=')
    that.data.isTime = true;
    wx.setStorageSync('isTime', that.data.isTime);
    return;
  }
  setTimeout(function () {
    time = time - 1;
    that.countdown(that, time);
  }, 1000)
},



.wxml
<!-- 注意點:report-submit必須設為true,才可以拿到其formId -->

<form bindsubmit="formSubmit" bindreset="formReset" report-submit="true">

  <button formType="submit" class="mybtn" type="primary">發送模板消息</button>

</form>

 


一次性訂閱消息:
參考鏈接-https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1500374289_66bvB

https://www.jianshu.com/p/39446d4a906d?open_source=weibo_search

開發者可以通過一次性訂閱消息授權讓微信用戶授權第三方移動應用(接入說明:https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1500434436_aWfqW&token=&lang=zh_CN)或公眾號,獲得發送一次訂閱消息給到授權微信用戶的機會。授權微信用戶可以不需要關注公眾號。微信用戶每授權一次,開發者可獲得一次下發消息的權限。(注意:同一用戶在同一scene場景值下的多次授權不累積下發權限,只能下發一條。若要訂閱多條,需要不同scene場景值)

第一步:先掃描下面鏈接生成的二維碼
https://mp.weixin.qq.com/mp/subscribemsg?action=get_confirm&appid=wxdbc106ba7b394900&scene=10&template_id=AGgtLkckms5H7MK-Be32QdoeBAlMgFgQV5wRbPoop5q&redirect_url=http%3a%2f%2flegogo.com&reserved=test#wechat_redirect
 
注意點:template_id:接口權限--一次性訂閱消息--查看模版id
redirect_url:授權后重定向的回調地址,請使用UrlEncode對鏈接進行處理。 注:要求redirect_url的域名要跟登記的業務域名一致,且業務域名不能帶路徑。 業務域名需登錄公眾號,在設置-公眾號設置-功能設置里面對業務域名設置。
 
如果用戶點擊同意或取消授權,頁面將跳轉至: redirect_url/?openid=OPENID&template_id=TEMPLATE_ID&action=ACTION&scene=SCENE   就可以獲得openid和scene了(點擊取消無openid返回)
 
第二步:調用接口下發消息推送
sendOnceMessage: function () {
  console.log('一次性訂閱消息-liandan')
  
  var dic = {
    "touser": "o1kPvwjSyokfy0uDAZclj3uCgR7k", 
    "template_id": "AGgtLkckms5H7MK-Be32QdoeBAlMgFgQV5wRbPoop5q",
    "url": "http://liandan100.com",
    //只能填寫該公眾號關聯的小程序,否則報錯
    "miniprogram": {miniprogram
       "appid": "wxc1a5693865f7800s",
       "pagepath":"pages/index/qqq/aaa/aaa?analysisReportId=2050&openId=1"
    }, 
"scene": "10", //鏈接里有,必須一樣,每次可相同
"title": "一次性訂閱消息10",
"data": {
"content": {
"value": "content一次性訂閱消息--一次性訂閱消息--一次性訂閱消息",
"color": "#270077",
}
}
}

util.httpsPostRequest("https://api.weixin.qq.com/cgi-bin/message/template/subscribe?access_token=5_oGeRXuo4G6xmPknexHyrciSfvfUQm6f0GeP_e06_s9hr78naIhVtrxbFxeBw4mCrMmZFDA_hureKGClg25ZxLZqRJnMfAZ01391QTtR7fgs08A4Oqq9MzSUPfibghLIrpVVdEkJTtIy9hYZjCBLiAIARQA", dic, function (success) {
console.info('一次性訂閱消息-errmsg==' + success.errmsg);
})
}


 



 


免責聲明!

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



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