当前位置:   article > 正文

微信公众号发送模板消息,并且点击可以直接转到小程序。(开发篇)_公众号模板消息跳转到小程序

公众号模板消息跳转到小程序

1、微信侧文档 模板消息 | 微信开放文档

参数说明:

说明:发送模板消息,是一个post请求。

touser:是接收者openid,这个openid是公众号h5网页获取的openid,与小程序侧的openid是不一样的。(必填)如果开通了开放平台会有一个UnionID。

        如果开发者拥有多个移动应用、网站应用、和公众账号(包括小程序),可通过 UnionID 来区分用户的唯一性,因为只要是同一个微信开放平台账号下的移动应用、网站应用和公众账号(包括小程序),用户的 UnionID 是唯一的。换句话说,同一用户,对同一个微信开放平台下的不同应用,unionid是相同的。UnionID 机制说明 | 微信开放文档

template_id:模板ID,这个就是公众号--模板消息--我的模板--类目模板。

url:跳转的url,这个可以是一个h5的页面。(非必填)

miniprogram:设置跳转到小程序(非必填)。

        appid:小程序的appid(必填,如果你指定要跳转小程序。)

        appid,是要在公众号平台里进行绑定的,那小程序是一定要发布一版本的。

        公众号-- 小程序管理--进行绑定,输入小程序appid,然后就可以。

        pagepath:小程序的访问位置+参数,比如pages/index/index?id=1,传入参数id=1,然后我们在小程序里就可以接收id参数,并且进行相关数据的获取直接展示或者进行页面的跳转等等。

data:上述模板消息中的详情中的页面的相关参数(必填):

client_msg_id:(非必填),可以不传。

2、根据文档,我们进行编码。

 1) pom.xml中加入fastjson

  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>fastjson</artifactId>
  4. <version>1.2.73</version>
  5. </dependency>

2) 编写相关发送工具类中的方法:

  1. /**
  2. * 公众号模板消息发送
  3. *
  4. * @param openid 接收用户openid
  5. * @param access_token 全局访问令牌
  6. * @param data 测试模板:发送的内容
  7. * @param rdate 时间
  8. * @param id 维修单id
  9. * @param fybxdh 申请单号
  10. * @param realname 申请人
  11. * @param result 审批结果
  12. * @param companyname 所在单位
  13. * @return
  14. */
  15. public static String sendMsg2WeChat(String path, String openid, String rdate,
  16. Integer id, String result, String fybxdh, String realname, String companyname) {
  17. // SvrPrint.print("sendMsg2Usr");
  18. String access_token = getAccessToken(path, WxConstant.AppId, WxConstant.AppSecret);
  19. String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
  20. System.out.println("请求微信的Url:" + url);
  21. JSONObject json = new JSONObject();
  22. String template_id = "";
  23. try {
  24. JSONObject data = new JSONObject();
  25. json.put("touser", openid);
  26. // 维修单申请审批结果通知
  27. template_id = templateId_repair_result;
  28. // 申请单号{{character_string1.DATA}}
  29. data.put("character_string1", JSONObject.parse("{\"value\":\"" + fybxdh + "\"}"));
  30. // 申请时间{{time4.DATA}}
  31. data.put("time4", JSONObject.parse("{\"value\":\"" + rdate + "\"}"));
  32. // 申请人{{thing5.DATA}}
  33. data.put("thing5", JSONObject.parse("{\"value\":\"" + realname + "\"}"));
  34. // 所属单位{{thing3.DATA}}
  35. data.put("thing3", JSONObject.parse("{\"value\":\"" + companyname + "\"}"));
  36. //审批结果{{const2.DATA}} 管理枚举值(审核通过\驳回申请)
  37. data.put("const2", JSONObject.parse("{\"value\":\"" + result + "\"}"));
  38. json.put("template_id", template_id);
  39. String pagepath = "pages/index/index?id=" + id;
  40. JSONObject json_miniprogram = new JSONObject();
  41. json_miniprogram.put(WxConstant.kAPPID, WxConstant.AppIdx);
  42. json_miniprogram.put(WxConstant.kPAGEPATH, pagepath);
  43. json.put(WxConstant.kMINIPROGRAM, json_miniprogram);
  44. json.put("data", data);
  45. } catch (JSONException e) {
  46. System.out.println("sendMsg2Usr:" + e.getMessage());
  47. e.printStackTrace();
  48. }
  49. String resultStr = HttpRequest.sendPost(url, json.toString());
  50. try {
  51. JSONObject parseObject = JSONObject.parseObject(resultStr);
  52. System.out.println("resultStr:" + resultStr);
  53. String errmsg = parseObject.getString("errmsg");
  54. if (!"ok".equals(errmsg)) {
  55. String status = "发送通知失败";
  56. String note = "发送通知,单号:" + fybxdh + ",错误:" + resultStr;
  57. int type = 1;
  58. // 日志
  59. //addLog("admin", "127.0.0.1", status, type, note, fybxdh);
  60. System.out.println("发送通知错误:" + resultStr);
  61. return "error";
  62. }
  63. } catch (JSONException e) {
  64. System.out.println("发送通知异常:" + e.getMessage());
  65. String status = "发送通知异常";
  66. String note = "发送通知,单号:" + fybxdh + ",错误:" + e.getMessage();
  67. int type = 1;
  68. // 日志
  69. // addLog("admin", "127.0.0.1", status, type, note, fybxdh);
  70. return "error";
  71. }
  72. return "success";
  73. }

getAccessToken: 只是获取方法,并没有进行存储,实际开发是要存到服务器磁盘文件,有效期

是2小时,7200秒。

  1. public static String getAccessToken(String APPID, String APPSECRET) {
  2. //https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxd76a692bcec1f4df&secret=daedcccd73b1a23a071d2e0f2gf41dc1
  3. String url = "https://api.weixin.qq.com/cgi-bin/token";
  4. String params = "grant_type=client_credential&appid=" + APPID
  5. + "&secret=" + APPSECRET;
  6. System.out.println(url+":"+params);
  7. String resultStr = "" ;
  8. try {
  9. resultStr = HttpRequest.sendGet(url, params);
  10. }catch(Exception e) {
  11. System.out.println(e.toString());
  12. }
  13. return resultStr;
  14. }

微信开放文档 获取access_token

  1. /**
  2. * All rights Reserved, Designed By 花花鱼
  3. * @Title: HttpRequest.java
  4. * @Description:
  5. * @author: 花花鱼
  6. * @date: 2016年8月8日 上午9:27:31
  7. * @version v1.0
  8. */
  9. package com.jstonesoft.qd.util;
  10. import java.io.BufferedReader;
  11. import java.io.IOException;
  12. import java.io.InputStreamReader;
  13. import java.io.OutputStreamWriter;
  14. import java.io.PrintWriter;
  15. import java.net.URL;
  16. import java.net.URLConnection;
  17. public class HttpRequest {
  18. /**
  19. * 向指定URL发送GET方法的请求
  20. *
  21. * @param url
  22. * 发送请求的URL
  23. * @param param
  24. * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  25. * @return URL 所代表远程资源的响应结果
  26. */
  27. public static String sendGet(String url, String param) {
  28. String result = "";
  29. BufferedReader in = null;
  30. try {
  31. String urlNameString = url + "?" + param;
  32. URL realUrl = new URL(urlNameString);
  33. // 打开和URL之间的连接
  34. URLConnection connection = realUrl.openConnection();
  35. // 设置通用的请求属性
  36. connection.setRequestProperty("accept", "*/*");
  37. connection.setRequestProperty("connection", "Keep-Alive");
  38. connection.setRequestProperty("user-agent",
  39. "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  40. // 建立实际的连接
  41. connection.connect();
  42. // 获取所有响应头字段
  43. // Map<String, List<String>> map = connection.getHeaderFields();
  44. // 遍历所有的响应头字段
  45. // for (String key : map.keySet()) {
  46. // System.out.println(key + "--->" + map.get(key));
  47. // }
  48. // 定义 BufferedReader输入流来读取URL的响应
  49. // 获取URLConnection对象对应的输出流
  50. in = new BufferedReader(new InputStreamReader(
  51. connection.getInputStream(), "utf-8"));
  52. String line;
  53. while ((line = in.readLine()) != null) {
  54. result += line;
  55. }
  56. // System.out.println(result);
  57. } catch (Exception e) {
  58. System.out.println("发送GET请求出现异常!" + e);
  59. e.printStackTrace();
  60. }
  61. // 使用finally块来关闭输入流
  62. finally {
  63. try {
  64. if (in != null) {
  65. in.close();
  66. }
  67. } catch (Exception e2) {
  68. e2.printStackTrace();
  69. }
  70. }
  71. return result;
  72. }
  73. /**
  74. * 向指定 URL 发送POST方法的请求
  75. *
  76. * @param url
  77. * 发送请求的 URL
  78. * @param param
  79. * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  80. * @return 所代表远程资源的响应结果
  81. */
  82. public static String sendPost(String url, String param) {
  83. PrintWriter out = null;
  84. BufferedReader in = null;
  85. String result = "";
  86. try {
  87. URL realUrl = new URL(url);
  88. // 打开和URL之间的连接
  89. URLConnection conn = realUrl.openConnection();
  90. //设置通用的请求属性
  91. conn.setRequestProperty("user-agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0)");
  92. // 发送POST请求必须设置如下两行
  93. conn.setDoOutput(true);
  94. conn.setDoInput(true);
  95. // 获取URLConnection对象对应的输出流
  96. OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
  97. out = new PrintWriter(outWriter);
  98. // 发送请求参数
  99. out.print(param);
  100. // flush输出流的缓冲
  101. out.flush();
  102. // 定义BufferedReader输入流来读取URL的响应
  103. in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
  104. String line;
  105. while ((line = in.readLine()) != null) {
  106. in = new BufferedReader(new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")));
  107. result += line;
  108. }
  109. } catch (Exception e) {
  110. System.out.println("发送 POST 请求出现异常!"+e);
  111. e.printStackTrace();
  112. }
  113. //使用finally块来关闭输出流、输入流
  114. finally{
  115. try{
  116. if(out!=null){
  117. out.close();
  118. }
  119. if(in!=null){
  120. in.close();
  121. }
  122. }
  123. catch(IOException ex){
  124. ex.printStackTrace();
  125. }
  126. }
  127. return result;
  128. }
  129. }

3) 编写测试用例

  1. @Controller
  2. @RequestMapping("wx")
  3. public class WxTplController {
  4. /**
  5. * 维修申请单结果推送消息调用
  6. *
  7. * @return
  8. */
  9. @ResponseBody
  10. @RequestMapping(path = "/repairresult", method = RequestMethod.GET)
  11. public String RepairResultSend(Repairreq repairreq, HttpServletRequest req) {
  12. repairreq = new Repairreq();
  13. repairreq.setId(1);
  14. repairreq.setRdate(getCurrentDateStr2());
  15. repairreq.setRtitle("维修申请001");
  16. repairreq.setRcontent("维修申请001");
  17. repairreq.setCompanyName("花花鱼");
  18. repairreq.setFybxdh("WXSQ-2024-05-001");
  19. repairreq.setRealname("管理员");
  20. repairreq.setUserId(105);
  21. Userinfo userinfo = userinfoService.getById(repairreq.getUserId());
  22. if (userinfo != null) {
  23. String path = req.getSession().getServletContext().getRealPath("/wx/");
  24. String openid = userinfo.getOpenidg();
  25. if (openid != null && !openid.equals("")) {
  26. String rtitle = repairreq.getRtitle();
  27. if (rtitle.length() > 20) {
  28. rtitle = rtitle.substring(0, 18) + "..";
  29. }
  30. String rdate = repairreq.getRdate();
  31. String fybxdh = repairreq.getFybxdh();
  32. String realname = repairreq.getRealname();
  33. String companyname = repairreq.getCompanyName();
  34. // 发送订阅消息
  35. String kind = WxConstant.kNotifyRepairResult;
  36. Integer id = repairreq.getId();// 维修单id
  37. String result = "审核通过";
  38. result = WXPublicUtils.sendMsg2WeChat(path, openid, rtitle, rdate, id, result, fybxdh,
  39. realname, companyname);
  40. if (result != null && result.equals("success")) {
  41. System.err.println(result);
  42. }
  43. } else {
  44. System.err.println("openid is null");
  45. }
  46. } else {
  47. System.err.println("userinfo is null");
  48. }
  49. return "ok";
  50. }
  51. }

以上是实现发送模板消息的基本代码,注意,这个一定要先获取公众号下的openid才可以,一般我们会通过小程序直接通过授权域名的h5网页来进行绑定操作。这样就可以实现通过手机号来获取openid的方法。 

小程序中去获取参数:

  1. onLoad(options) {
  2. console.log(options.id); //接收到的id值。
  3. }

下面我们就要进行调试了......

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/808171
推荐阅读
相关标签
  

闽ICP备14008679号