微信小程序发送模板消息(最通俗易懂)

公司需要用到微信小程序推送   经过一下午的资料查阅,得出以下经验。

首先得去微信公众平台小程序的模板消息  创建模板  也能通过接口去创建,但是我觉得挺麻烦的  还不如去后台创建

下面是我写的测试代码,只有具体数据都是测试的模拟数据,实际业务肯定需要拿到业务数据,大家后面可以自我发挥。

对了,还有一点,电脑的小程序的开发工具是拿不到formid 的  会提示 the formId is a mock one ,只能用手机测试才能拿到formid

下面看代码吧:

这个是前台页面

 

1 <button class=‘btn‘ type=‘primary‘ bindtap=‘test4‘>获取access_token</button>2 <button class=‘btn‘ type=‘primary‘ bindtap=‘test5‘>获取openid</button>3 <form bindsubmit=‘formSubmit‘ report-submit=‘true‘>4 <input name=‘msg‘ value=‘我是测试消息‘></input>5 <button form-type=‘submit‘ >提交</button>6 </form>

 

 

这是js

 1  data: { 2 access_token: ‘‘, 3 openid: ‘‘, 4  }, 5 // 获取access_token 6 test4: function() { 7 var that = this; 8  wx.request({ 9 url: ‘https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET‘,10 method: ‘GET‘,11 success: function(r) {12  console.log(r);13  that.setData({14  access_token: r.data.access_token15  })16  }17  })18  },19 // 获取openid20 test5: function() {21 var that = this;22  wx.login({23 success: res => {24 // 发送 res.code 到后台换取 openId, sessionKey, unionId25 // console.log(res)26  wx.request({27 url: ‘https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=APPSECRET&js_code=‘ + res.code + ‘&grant_type=authorization_code‘,28 method: ‘POST‘,29 success: function(r) {30  console.log(r);31  that.setData({32  openid: r.data.openid33  });34  }35  })36  }37  })38  },39 40 // 表单提交拿到formid 并且发送模板消息41 42 formSubmit: function(e) {43  console.log(e);44 var that = this;45 //return;46  wx.request({47 url: ‘https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=‘ + that.data.access_token,48 method: ‘POST‘,49  data: {50 "touser": that.data.openid,51 "template_id": "AUuKzlgGti-H5_ZgcxnieY0AGvyZvUXwVtrhLa-GhNk",52 "form_id": e.detail.formId,53 "data": {54 "keyword1": {55 "value": "我想咨询一个问题"56  },57 "keyword2": {58 "value": "Sanfor"59  },60 "keyword3": {61 "value": "2018年7月11日 16:28:25"62  },63 "keyword4": {64 "value": "儿童咨询"65  },66 "keyword5": {67 "value": "小孩子有点胖怎么办"68  },69  }70  },71 success: function(r) {72  console.log(r)73  }74  })75 }


效果图如下 :

技术分享图片

 

 

相关文章