微信小程序的消息推送簡單的說就是發送一條微信通知給用戶,用戶點開消息可以查看消息內容,可以鏈接進入到小程序的指定頁面。
微信小程序消息推送需要用戶觸發動作才能發送消息,比如用戶提交訂單、支付成功。一次只能發一條,當然可以通過某種方法發送多條,小的就不在這里贅述了。下面就介紹一下如何推送消息。
一、準備工作
首先,在微信公眾平臺開通消息推送功能,并添加消息模板??梢詮哪0鍘爝x擇模板也可以創建一個模板,模板添加之后,模板ID我們接下來要用的。
發送模板消息需要用到accesstoken、formId和openID。accesstoken獲取及更新可以看我的上一篇文章;formID就是消息模板ID,openID我們最好在獲取用戶信息或用戶登錄時儲存到全局變量里。
二、獲取formID
在需要觸發消息推送的頁面添加提交表單的事件。目的是得到formID,formID是消息推送時必須的參數。
<form name='pushMsgFm' report-submit='true' bindsubmit='getFormID'> <button form-type="submit" class="zan-btn zan-btn--large zan-btn--danger payButton">立即支付</button></form>
以上代碼中“getFormID”是提交表單時觸發的事件。
getFormID: function (e) {this.setData({formId: e.detail.formId }) }
以上方法是獲取formId。
三、配置消息模板參數,并傳給后臺
var config = require('../config.js')var app = getApp();function pushMsg(formID, access_token){ var openId = app.globalData.userInfo.openId; var messageDemo = { touser: openId,//openId template_id: 'PjtLeqq-UeF49r5jr88s27HBzBDobijr6QfiwJwIkPg',//模板消息id, page: 'pages/index/index',//點擊詳情時跳轉的主頁 form_id: formID,//formID data: {//下面的keyword*是設置的模板消息的關鍵詞變量 "keyword1": { "value": "keyword1", "color": "#4a4a4a" }, "keyword2": { "value": "keyword2", "color": "#9b9b9b" }, "keyword3": { "value": "keyword3", "color": "red" } }, color: 'red',//顏色 emphasis_keyword: 'keyword3.DATA'//需要著重顯示的關鍵詞 } wx.request({ url: config.service.sendMsgUrl, data: { value: messageDemo, access_token: access_token}, method: 'POST', success: function (res) { console.log("push msg"); console.log(res); }, fail: function (err) { console.log("push err") console.log(err); } });}module.exports = { pushMsg: pushMsg }
四、推送消息
const request = require('../tools/ih_request');var conf = require('../config.js')module.exports = async (ctx, next) => { var body = ctx.request.body.valueawait request.postJson({ url: 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + ctx.request.body.access_token, body: body, success: function (res) { ctx.body = { result: res } console.log('res=',res); }, error: function (err) { ctx.body = { result: err } console.log(err); }});}
ih_request.js
const request = require('request');var ih_request = {};module.exports = ih_request;ih_request.postJson = async function (option) { var res = await request({ url: option.url, method: 'post', headers: { 'content-type': 'application/json' }, body: JSON.stringify(option.body), }, function (err, res, body) { res ? option.success(body) : option.error(res.msg); console.log('MSGresult=', body); });}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答