首先登陆微信公众平台 找自己的模板消息设置, 设置自己想要的模板消息,拿到模板消息ID,再准备好自己小程序的appid,小程序秘钥。这三个都准备好了以后直接看代码。
js:Page({ data: { openid:"", session_key:"", access_token:"", }, onLoad: function (options) { var that = this //第一步获取openid wx.login({ success: function (data) { console.log(data.code, data) console.log("12345"); wx.request({ url: 'https://api.weixin.qq.com/sns/jscode2session', data:{ appid: "你的appid", secret: "小程序秘钥", js_code: data.code//wx.login获取到的code }, method: "post", header: { "Content-Type": "application/x-www-form-urlencoded" }, success: function (res) { console.log(res); that.setData({ openid: res.data.openid, session_key: res.data.session_key, }) } }) } }) //第二步 获取access_token wx.request({ url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=你的appid&secret=你的小程序秘钥', method: "GET", success: function (res) { console.log("xxx"); console.log(res); that.setData({ access_token: res.data.access_token,//获取到的access_token }) } }) }, form: function (e) { console.log(e); var that = this; var fId = e.detail.formId; // 网络请求 var l = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + that.data.access_token; var d = { touser: that.data.openid, //用户的openid template_id: '模板消息ID', page: '/pages/index/index', form_id: fId, data: { //模板消息要对应 有几个写几个 避免为空模板 "keyword1": { "value": "酒店", "color": "#4a4a4a" }, "keyword2": { "value": "2018-03-22", "color": "#9b9b9b", }, "keyword3": { "value": "$300", "color": "#9b9b9b" }, "keyword4": { "value": "中国", "color": "#9b9b9b" }, }, color: '#ccc', emphasis_keyword: 'keyword1.DATA' } wx.request({ url: l, data: JSON.stringify(d), method: 'POST', success: function (res) { console.log(res); }, fail: function (err) { console.log(err); } }); },})
以上是js
下面是wxml
其中有一个formid需要注意下,想要发送模板消息必须借助formid 或者payid
formid 有返回值 如果返回一串英文,那是因为你没有在真机调试,不会有formid返回给你,微信官方文档有关于formid的返回值
原因,在这我都不一 一解释了。
wxml<form bindsubmit="form" report-submit='true' ><button form-type="submit" class='xx'><text>123</text></button></form>
当到最后要成功时,你可能还会遇到坑,js中form方法最后请求微信官方服务器,success回调会有一个errorcode,这个errorcode有各种各样的返回值,这是我看了几种
还有一种是errorcode为0,原因可能是由于发送请求时没有设置UT8编码导致的,需设置编码,但是我将发送的data转了下json格式,应该不会出现什么问题,我的也返回了errorcode 为0 但是,模板消息发送成功了 收到了微信服务通知。
效果如下