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

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

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

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

下面看代码吧:

这个是前台页面

 

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

 

 

这是js

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

 

版权声明:本文为sanfor原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/sanfor/p/9295604.html