js:Page({data:{openid:"",session_key:"",access_token:"",},onLoad:function(options){varthat=this//第一步获取openidwx.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_tokenwx.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);varthat=this;varfId=e.detail.formId;//网络请求varl='https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='+that.data.access_token;vard={touser:that.data.openid,//用户的openidtemplate_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的返回值
原因,在这我都不一一解释了。
wxmlformbindsubmit="form"report-submit='true'buttonform-type="submit"class='xx'text123/text/button/form当到最后要成功时,你可能还会遇到坑,js中form方法最后请求微信官方服务器,success回调会有一个errorcode,这个errorcode有各种各样的返回值,这是我看了几种
还有一种是errorcode为0,原因可能是由于发送请求时没有设置UT8编码导致的,需设置编码,但是我将发送的data转了下json格式,应该不会出现什么问题,我的也返回了errorcode为0但是,模板消息发送成功了收到了微信服务通知。
效果如下













