鉴于目前网络上都还找不到小程序下发模板消息的相关资源,在多次阅读了官方文档今天终于把小程序的模版消息给测通了,接下来介绍在不使用服务器的情况下,前端开发人员在本地怎么测试模板消息的发送。
1、在微信公众平台-小程序的模板中心先申请一个下发消息模板
2、根据文档提及的下发模板消息做法分两个步骤
2-1、获取token,这里我直接使用微信公众平台接口调试工具【http://mp.weixin.qq.com/debug/】上得到token串,在有效期内测试。假如多处请求需要token的话,最好设置一个公共变量存储,这里我提前把appid、secret、token存储在app.js的globalData里头了。
2-2、发起模版消息请求,根据接口post参数说明,还需要提前获取openid,也就是接收者(登录小程序用户)的openid。
2-2-1、获取openid,这里我是在app.js发起请求得到openid在存储到本地上,具体代码如下:【将这段代码放入onLoad生命周期内】
//获取openidvar user=wx.getStorageSync('user') || {};if(!user.openid || (user.expires_in || Date.now()) < (Date.now() + 600)){//不要在30天后才更换openid-尽量提前10分钟更新wx.login({success: function(res){// successvar d=that.globalData.wxData;//这里存储了appid、secret、token串var l='https://api.weixin.qq.com/sns/jscode2session?appid='+d.appId+'&secret='+d.appSecret+'&js_code='+res.code+'&grant_type=authorization_code';wx.request({url: l,data: {},method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT// header: {}, // 设置请求的 headersuccess: function(res){var obj={};obj.openid=res.data.openid;obj.expires_in=Date.now()+res.data.expires_in;wx.setStorageSync('user', obj);//存储openid}});}});}else{console.log(user);}
test.wxml::
<form name='pushMsgFm' report-submit bindsubmit='orderSign'>enter product:<input type="text" name="product" value='' placeholder="enter your name" />detail: <input type="text" name='detail' placeholder="enter desc" />select sex:<switch type="switch" name='sex' /><button form-type="submit">submit</button>
</form>
注意form组件一定要加report-submit属性,否则获取不到formId。
test.js::
orderSign: function (e) {var fId = e.detail.formId;var fObj = e.detail.value;var l = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + App.globalData.wxData.token;var d = {touser: wx.getStorageSync('user').openid,template_id: 'dKyw9dIDjncWW3VuFIRK9o',//这个是1、申请的模板消息id,page: '/pages/index/index',form_id: fId,value: {//测试完发现竟然value或者data都能成功收到模板消息发送成功通知,是bug还是故意??【鄙视、鄙视、鄙视...】 下面的keyword*是你1、设置的模板消息的关键词变量"keyword1": {"value": fObj.product,"color": "#4a4a4a"},"keyword2": {"value": fObj.detail,"color": "#9b9b9b"},"keyword3": {"value": new Date().getDate(),"color": "#9b9b9b"},"keyword4": {"value": "201612130909","color": "#9b9b9b"},"keyword5": {"value": "$300","color": "red"}},color: '#ccc',emphasis_keyword: 'keyword1.DATA'}wx.request({url: l,data: d,method: 'POST',success: function(res){console.log("push msg");console.log(res);},fail: function(err) {// failconsole.log("push err")console.log(err);}});}
最后编译,输入文本点击提交发起请求,这里只能手机调试,我用开发工具打印出来的formId: "the formId is a mock one"并不是数字串。最终微信助手下发如下信息,表示成功发送模板消息了
这里需要注意一点,如果提示合法域名问题,那是你没有在公众平台把微信的域名也添加进去。具体进入微信公众平台 | 小程序中心--设置--开发设置--服务器域名配置,点击修改,将请求的域名添加进去。如下: