如何下发小程序模板消息
1、获取 access_token和用户openid
需要在app.js中请求相应的接口, 其实获取access_token应该是后台请求微信的接口再返回access_token,前端最好不要出现秘钥重要信息
onLaunch: function () {
let setInfoSuccess = wx.getStorageSync('setInfoSuccess') || 0;
let bearer_token = wx.getStorageSync('bearer-token');
// 登录
wx.login({
success: res => {
this.globalData.js_code = res.code
//这部分是获取bearer-token,可以去掉
if (new Date().getTime() - setInfoSuccess > 86400000 || !bearer_token) {
api.mine.login({ code: res.code })
.then(d => {
wx.setStorageSync('bearer-token', d.data);
})
.catch(function (e) {
});
}
this.getOpenId_token()
},
complete: res => this.getSetting()
})
},
getOpenId_token: function() {
//获取access_token
wx.request({
url: 'https://api.weixin.qq.com/cgi-bin/token',
data: {
grant_type: 'client_credential',
appid: '小程序id',
secret: '小程序秘钥'
},
method: 'GET',
// header: header,
success: function (res) {
wx.setStorageSync('access_token', res.data.access_token);
},
fail: res => (res)
});
//获取openid
wx.request({
url: `https://api.weixin.qq.com/sns/jscode2session?appid=${this.globalData.appid}&secret=${this.globalData.secre}&js_code=${this.globalData.js_code}&grant_type=authorization_code`,
data: {},
method: 'GET',
success: function (res) {
var obj = {};
obj.openid = res.data.openid;
wx.setStorageSync('user', obj);//存储openid
}
});
},
2、在触发模板消息的页面中获取form_id或者prepay_id
自定义一个表单,需要加上report-submit属性才能获取form_id
<view class='first'>测试模板信息</view>
<form name='pushMsgFm' report-submit bindsubmit='test'>
<button class='index-btn' form-type="submit">开始测试</button>
</form>
test: function (e) {
//e.detail.formId如果在开发工具上请求,则获取的是the formId is a mock one
//需要用手机扫开发版获取formId,然后赋值到此 fId 再请求
//手机端请求不了是因为服务器不能配置api.weixin.qq.com
let fId = e.detail.formId;
wx.showToast({
title: fId,
duration: 3000
});
let url = `https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=${wx.getStorageSync('access_token')}`
let data = {
"touser": wx.getStorageSync('user').openid,
"template_id": "小程序模板id,看文档获取",
//点击模板跳转的页面路径,如果不填则不跳转
"page": "pages/index/index",
"form_id": fId,
"data": {
"keyword1": {
"value": "339208499",
"color": "#173177"
},
"keyword2": {
"value": "2015年01月05日 12:30",
"color": "#173177"
},
"keyword3": {
"value": "粤海喜来登酒店",
"color": "#173177"
},
"keyword4": {
"value": "广州市天河区天河路208号",
"color": "#173177"
},
"keyword5": {
"value": "今天天气很好",
"color": "#173177"
}
},
"emphasis_keyword": "keyword1.DATA"
}
//发送模板消息
wx.request({
url: url,
data: data,
method: 'POST',
success: function (res) {
}
});
}
结果如下: