微信小程序消息推送功能如何開發(fā)實(shí)現(xiàn)
微信小程序消息推送功能指的就是通過實(shí)現(xiàn)微信小程序推送小程序給用戶,以便用戶點(diǎn)開消息就可以查看消息內(nèi)容并點(diǎn)擊鏈接進(jìn)入到小程序的指定頁面。那么開發(fā)人員怎么去實(shí)現(xiàn)這個(gè)功能呢?
步驟一:獲取模板ID
登錄 https://mp.weixin.qq.com 獲取模板,如果沒有合適的模板,可以申請?zhí)砑有履0澹瑢徍送ㄟ^后可使用。
步驟二:獲取formID
在需要觸發(fā)消息推送的頁面添加提交表單的事件。目的是得到formID,這是消息推送時(shí)必須的參數(shù)。
以上代碼中“getFormID”是提交表單時(shí)觸發(fā)的事件。
getFormID: function (e) {
this.setData({
formId: e.detail.formId }) }
以上方法是獲取formID。
步驟三:配置消息模板參數(shù),并傳給后臺(tái)
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’,//點(diǎn)擊詳情時(shí)跳轉(zhuǎn)的主頁
form_id: formID,//formID
data: {//下面的keyword*是設(shè)置的模板消息的關(guān)鍵詞變量
“keyword1”: {
“value”: “keyword1”,
“color”: “#4a4a4a”
},
“keyword2”: {
“value”: “keyword2”,
“color”: “#9b9b9b”
},
“keyword3”: {
“value”: “keyword3”,
“color”: “red”
}
},
color: ‘red’,//顏色
emphasis_keyword: ‘keyword3.DATA’//需要著重顯示的關(guān)鍵詞
}
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.value
await 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);
});
}
以上就是微信小程序消息推送功能開發(fā)實(shí)現(xiàn)的基本流程,希望能幫助到大家!
版權(quán)聲明:
本站所有文章和圖片均來自用戶分享和網(wǎng)絡(luò)收集,文章和圖片版權(quán)歸原作者及原出處所有,僅供學(xué)習(xí)與參考,請勿用于商業(yè)用途,如果損害了您的權(quán)利,請聯(lián)系網(wǎng)站客服處理。