模板信息是一个非常重要的事项,关系到小程序跟微信自身的连通问题,合理的利用模板信息,可以让你的小程序更进一步,所以十分值得研究和学习;这篇文章中,兜兜乐客把自己的实践分享了一下,感谢作者的分享;
今天分享一篇关于消息模板的简易教程。
老规矩先把官方的定义再讲一下,消息模板是基于微信的通知渠道,为我们开发者提供了触发模板消息的能力,以便实现服务的闭环和更好的用户体验。
发起消息模板是有限制条件的,必须用户本人在微信体系与小程序页面有交互行为后才能触发,只有两种情况允许。
第一种是用户在小程序完成支付的行为,可允许开发者向用户在7天内推送有限的模板消息,一次支付可发一条。
第二种是通过提交表单行为且表单需要声明为要发模板消息的,可以允许开发者向用户在7天内推送有限条数的模板消息,一次提交表单可发一条。
好了,废话就不多说了,还是看代码吧。更多官方的定义打开这个地址即可。https://mp.weixin.qq.com/debug/wxadoc/dev/api/notice.html
表单触发模板消息
基于微信的消息提示
由于没有正式上线,目前只能收到这样的信息,就表示模板消息发送成功了。
我用的是表单触发的模板消息,index.wxml部分很简单:代码如下
-
<form bindsubmit="formSubmit" report-submit="true">
-
<button formType="submit">提交表单发起通知</button>
-
</form>
复制代码
需要注意的是要在form加上 report-submit="true" 的属性和值。官方要求的,要遵循。
然后再看index.js部分
-
var app = getApp()
-
Page({
-
data: {
-
token: "",
-
openid: "",
-
appid: "你的appid",
-
secret: "你的secret",
-
template_id: "消息模板id,在小程序管理员账号中模板消息中设置获取"
-
},
-
onLoad: function () {
-
console.log('onLoad')
-
},
-
onLoad: function () { //登录获取openid并保存
-
var that = this
-
wx.login({
-
success: function (res) {
-
if (res.code) {
-
wx.request({
-
url: 'https://www.zgdnbxg.com/login.php', //后端处理页面返回openid
-
data: {
-
appid: that.data.appid,
-
secret: that.data.secret,
-
js_code: res.code,
-
grant_type: "authorization_code"
-
-
},
-
method: 'GET',
-
success: function (res) {
-
that.setData({
-
openid: res.data.openid
-
-
})
-
-
},
-
fail: function (res) {
-
console.log(res)
-
},
-
complete: function (res) {
-
console.log(res)
-
}
-
})
-
}
-
},
-
fail: function () {
-
// fail
-
},
-
complete: function () {
-
// complete
-
}
-
})
-
},
-
onReady: function () {
-
//判断toke有没有值,没有就settokentoken 有的话就获取缓存并设置token
-
var that = this
-
if (that.data.token == "") {
-
console.log("token 为空")
-
that.setToken()
-
} else {
-
console.log("token 不为空")
-
that.setData({
-
token: wx.getStorageSync('token')
-
})
-
}
-
},
-
//表单事件 触发模板消息
-
formSubmit: function (e) {
-
var that = this
-
-
-
wx.request({
-
url: 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + wx.getStorageSync('token'),
-
data: {
-
touser: that.data.openid,
-
form_id: e.detail.formId,
-
template_id: that.data.template_id,
-
value: "",
-
},
-
method: 'POST',
-
success: function (res) {
-
console.log(res)
-
-
},
-
fail: function (res) {
-
console.log(res)
-
-
},
-
complete: function () {
-
-
}
-
})
-
-
-
},
-
-
//获取token并保存在本地
-
setToken: function () {
-
var that = this
-
wx.request({
-
url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + that.data.appid + '&secret=' + that.data.secret,
-
data: {},
-
method: 'GET',
-
success: function (res) {
-
var token = res.data.access_token
-
that.setData({
-
token: token
-
})
-
wx.setStorageSync('token', token)
-
},
-
fail: function (res) {
-
console.log("获取token失败")
-
console.log(res)
-
}
-
})
-
}
-
})
复制代码
[size=1em]
你可以把这段代码全部复制,然后把appid,secret,template_id换成你自己的,并通过小程序管理员配置下request,加上www.zgdnbxg.com,即可真机体验。
|