上星期公司項目需求加入模版消息推送功能,今天在這整理一下:json
微信的模版消息分爲公衆號的和小程序的。它們看起來差很少,但仍是有點區別的:小程序
模板推送位置:公衆號的是本公衆號頁面,小程序的是服務通知。api
模板下發條件:公衆號能夠像咱們在原生app裏推送通知同樣進行下發,客戶無需主動觸發;小程序裏需用戶在微信體系內與頁面有交互行爲後觸發,小程序不能推送消息,只有用戶主動發起的事件並確認須要收到後續反饋,纔會收到消息。緩存
模版次數的限制:公衆號有10w+,根據粉絲量來決定;小程序官方文檔裏說的什麼提交表單7天內推送條數有限,支付一次能夠推送3條,若是不懂就每次都提交,這樣就沒有限制了。微信
只是小程序的模版消息必須使用表單<form>提交,由於須要用到form_id參數。這個參數須要多加註意,而且只能在真機上測試,要不這個form_id參數值你是拿不到的(報錯:the formId is a mock one);它們的api是不一樣的。session
第一步,獲取用戶openId。有兩個方法,思路都同樣:調wx.login獲得code(一次性的,不可重複利用),由code換取openId(這步有兩個方法,都應該在後臺完成,前臺測試時,請在開發工具裏按以下配置)。通常使用第二種方法,由於它還能夠返回用戶的基本信息,這貌似是通常小程序必用到的信息。第一種方法只會獲取到openId、session_key。app
方法一:工具
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; } }) } } });
方法二:oop
注意點:當 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場景值)
第一步:先掃描下面連接生成的二維碼
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);
})
}