微信小程序基于微信的通知渠道,也提供了消息通知能力,即模板消息,但这种消息只有在提交表单和支付时才能进行。模板推送位置:服务通知。
步骤:
1.微信小程序后台配置模板(他会生成一个模板id,发送模板消息的时候要用的)注:总共可添加25个模板
2.获取ACCESS_TOKEN(凭证有效时间,单位:秒。目前是7200秒之内的值即2小时。)
wx.request({
url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET',
data: {},
method: 'GET',
success: function (res) {
// success
console.log('get AccessToken')
console.log(res.data.access_token)
},
fail: function () {
// fail
},
complete: function () {
// complete
}
})
将获取到的access_token进行保存,用来获取openid和提交模板消息。
3.获取OPENID
wx.request({
url: 'https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code',
data: {},
method: 'GET',
// header: {}, // 设置请求的 header
success: function (res) {
// success
console.log('get openid')
console.log(res.data.openid)
},
fail: function () {
// fail
},
complete: function () {
// complete
}
})
其中JSCODE为wx.login成功后返回的res.code。
保存返回的openid。
4.获取模板ID
登录https://mp.weixin.qq.com/wxopen/tmplmsg?action=self_list&token=1588033132&lang=zh_CN获取模板,如果没有合适的模板,可以申请添加新模板,审核通过后即可使用。
5.提交模板消息(注:提交的from表单上必须加report-submit="true")
wx.request({
url: 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + access_token,
data: {
"touser": openid,
"template_id": templateid,
"form_id": e.detail.formId,
"data": {
"keyword1": {
"value": "w的博客",
"color": "#173177"
},
"keyword2": {
"value": "2017年01月22日 17:30",
"color": "#173177"
},
"keyword3": {
"value": "可乐加冰可乐",
"color": "#173177"
},
"keyword4": {
"value": "上海市徐汇区",
"color": "#173177"
}
},
"emphasis_keyword": "keyword1.DATA"
},
method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
// header: {}, // 设置请求的 header
success: function (res) {
// success
console.log(res)
}
})
点击submit按钮后,就会在微信的服务器通知中受到对应的消息。
需要注意的地方:
1.一个from表单提交只能生成一个fromId,一个fromId只能使用一次,
想要发多个通知的话可以收集一些fromId持久化到数据库。
2.fromId的有效期是7天