当前位置:   article > 正文

Java微信公众号发送消息-保姆级教程附源码_java微信公众号发消息给用户

java微信公众号发消息给用户

目录

1. 概念说明:

2. 开发准备:

3. 测试demo(更改配置信息即可使用)

3.1. 服务器配置

 3.1.1.配置填写说明

3.1.2.校验服务器有效性:

3.1.3.URL后端接口代码和校验代码(servlet)

 3.1.4.配置内网穿透,完成本地调试

 3.1.5. 可能存在的问题

3.2 模板消息

3.2.1. 搞定 template_id 即模板消息id:

3.2.2. 搞定 touser 即openid

3.2.3. 从获取openid的请求中我们发现需要access_token:

3.2.4. 发送模板消息的url参数

3.2.5. topcolor

3.2.5. data

3.3. 源码

3.3.1 模板消息DTO

3.3.2. 模板消息内容DTO

3.3.3. access_token缓存类:

3.3.4.http请求工具类:

3.3.5. 最终的Servlet(controller自行转换)(为方便观看所有逻辑都写在这里了,自行优化):

3.4.测试

官方文档:

微信公众平台开发概述 | 微信开放文档

全局返回码文档 :微信开放文档

1. 概念说明:

  • access_token:是公众号的全局唯一接口调用凭据,公众号调用各接口的必要参数(2小时内有效,过期需要重新获取,但1天内获取次数有限,需自行存储)

  • OpenID :为了识别用户每个公众号针对,每个用户会产生一个OpenID(用户id:对用户的操作需要用到)

  • UnionID: 同一开放平台账号下不同公众号或应用下用户的共同id(这里不需要用到)

  • 消息会话(这里用到模板消息)

    • 公众号是以微信用户的一个联系人形式存在的,消息会话是公众号与用户交互的基础。

    • 公众号内主要有这样几类消息服务的类型,分别用于不同的场景:

      • 群发消息:订阅号为每天1次,服务号为每月4次

      • 被动回复消息:在用户给公众号发消息后,公众号可以回复一个消息

      • 客服消息:用户在公众号内发消息/触发特定行为后,公众号可以给用户发消息

      • 模板消息:在需要对用户发送服务通知(如刷卡提醒、服务预约成功通知等)时,公众号可以用特定内容模板,主动向用户发送消息。

2. 开发准备:

  1. 开发者在公众平台网站中创建服务号、获取接口权限后方可开始

    https://kf.qq.com/faq/120911VrYVrA150918fMZ77R.html?scene_id=kf3386

  2. 个人研究测试:通过手机微信扫描二维码获得测试号

    https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login

3. 测试demo(更改配置信息即可使用)

3.1. 服务器配置

这里坑比较多,服务器配置不是随便填一个url就完事了,需要后端接口配合校验。

界面:

 测试号界面:

 3.1.1.配置填写说明

  • URL:服务器地址--是开发者用来接收微信消息和事件的接口URL (在提交配置修改时微信会向该URL接口发送请求验证服务器地址的有效性)

  • Token:任意填写,用作生成签名(微信向上述URL接口发送的请求是携带token的,需要在接口中校验token一致以确保安全性)这个token与上述的access_token不是一回事。这个token只用于验证开发者服务器。

  • EncodingAESKey: 由开发者手动填写或随机生成,将用作消息体加解密密钥

  • 消息加解密方式 :明文模式、兼容模式和安全模式

3.1.2.校验服务器有效性:

这是重点:点击完提交修改后,微信会向url发起一个请求并将token携带过去,这个请求要能正确被你的后端服务器所响应并返回正确的结果,服务器配置才算修改成功

校验请求说明:

  • 开发者提交信息后,微信服务器将发送GET请求到填写的服务器地址URL上,GET请求携带参数如下表所示:
    • signature:微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。

    • timestamp:时间戳

    • nonce :随机数

    • echostr:随机字符串

  • 开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。

3.1.3.URL后端接口代码和校验代码(servlet)

  1. @WebServlet(urlPatterns = {
  2. "/wx"})
  3. public class WxServlet extends HttpServlet {
  4. // 服务器配置填写的token
  5. private static final String wxToken = "888888";
  6. @Override
  7. protected void doGET(HttpServletRequest request, HttpServletResponse response)
  8. throws ServletException, IOException {
  9. doGetWx(request, response);
  10. }
  11. /**
  12. * @Description 校验配置URL服务器的合法性
  13. * @date 2023年5月29日下午4:17:40
  14. * @param request
  15. * @param response
  16. * @throws ServletException
  17. * @throws IOException
  18. */
  19. public void doGetWx(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  20. String signature = request.getParameter("signature");
  21. String timestamp = request.getParameter("timestamp");
  22. String nonce = request.getParameter("nonce");
  23. String echostr = request.getParameter("echostr");
  24. // 将微信echostr返回给微信服务器
  25. try (OutputStream os = response.getOutputStream()) {
  26. String sha1 = getSHA1(wxToken, timestamp, nonce, "");
  27. // 和signature进行对比
  28. if (sha1.equals(signature)) {
  29. // 返回echostr给微信
  30. os.write(URLEncoder.encode(echostr, "UTF-8").getBytes());
  31. os.flush();
  32. }
  33. } catch (Exception e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. /**
  38. * 用SHA1算法生成安全签名
  39. *
  40. * @param token 票据
  41. * @param timestamp 时间戳
  42. * @param nonce 随机字符串
  43. * @param encrypt 密文
  44. * @return 安全签名
  45. * @throws Exception
  46. */
  47. public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws Exception {
  48. try {
  49. String[] array = new String[] { token, timestamp, nonce, encrypt };
  50. StringBuffer sb = new StringBuffer();
  51. // 字符串排序
  52. Arrays.sort(array);
  53. for (int i = 0; i < 4; i++) {
  54. sb.append(array[i]);
  55. }
  56. String str = sb.toString();
  57. // SHA1签名生成
  58. MessageDigest md = MessageDigest.getInstance("SHA-1");
  59. md.update(str.getBytes());
  60. byte[] digest = md.digest();
  61. StringBuffer hexstr = new StringBuffer();
  62. String shaHex = "";
  63. for (int i = 0; i < digest.length; i++) {
  64. shaHex = Integer.toHexString(digest[i] & 0xFF);
  65. if (shaHex.length() < 2) {
  66. hexstr.append(0);
  67. }
  68. hexstr.append(shaHex);
  69. }
  70. return hexstr.toString();
  71. } catch (Exception e) {
  72. e.printStackTrace();
  73. }
  74. return "";
  75. }
  76. }

项目路径是/xjsrm,因此服务器url地址就是:http://localhost:8080/xjsrm/wx

直接将http://localhost:8080/xjsrm/wx地址填到服务配置的url可以吗?答案是不可以!

 3.1.4.配置内网穿透,完成本地调试

 3.1.4.1. 内网穿透的必要性:

  • 微信需要检验服务器有效性,因此这个url必须是公网资源,就是外网能访问的,不支持本地127.0.0.1/localhost ,而且这样调试起来非常的不方便。
  • 因此这里使用内网穿透将本地资源映射到公网。(直接部署到服务器上调试的可以跳过)

 3.1.4.2. 用到的工具cpolar:

  •  也可以使用花生壳、natapp、ngrok等;但不建议使用natapp、ngrok,这两个工具都不能直接访问到服务资源,中间会多一层手动校验(提示用户是否要访问该网站),会造成不必要的麻烦。

 3.1.4.3. cpolar配置内网穿透的教程

 3.1.4.4. 获取本地项目的公网路径

        配置完cpolar后在在线隧道列表中找到本地项目的地址,我项目是localhost:8080,因此公网地址对应(最好用https协议)https://22717eef.r6.vip.cpolar.cn

        因此完整的服务器Url就是: https://22717eef.r6.vip.cpolar.cn/xjsrm/wx

        浏览器访问该url,看后端是否接受到了请求,如果接收到说明接口没问题,此时将URL填到对应的配置栏中点击提交即可。

 3.1.5. 可能存在的问题

        如果你在使用点击修改配置的提交发现微信发送的请求根本就没有进到后端的项目中

        此时查看sandboxinfo这个包。如果出现 errorcode=-1多半是内网穿透工具的问题。

        出现其他错误代码可以去错误大全中根据信息排查

         ngrok错误排查示例:         

3.2 模板消息

 模板消息的官方文档:微信公众平台 (qq.com)

从官方给出的请求示例入手,看需要准备的接口和数据:

  1. POST请求
  2. https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN
  3. 请求包为一个json:
  4. {
  5. "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
  6. "touser":"OPENID",
  7. "url":"http://weixin.qq.com/download",
  8. "topcolor":"#FF0000",
  9. "data":{
  10. "User": {
  11. "value":"黄先生",
  12. "color":"#173177"
  13. },
  14. "Date":{
  15. "value":"06月07日 19时24分",
  16. "color":"#173177"
  17. },
  18. "CardNumber": {
  19. "value":"0426",
  20. "color":"#173177"
  21. },
  22. "Type":{
  23. "value":"消费",
  24. "color":"#173177"
  25. },
  26. "Money":{
  27. "value":"人民币260.00元",
  28. "color":"#173177"
  29. },
  30. "DeadTime":{
  31. "value":"06月07日19时24分",
  32. "color":"#173177"
  33. },
  34. "Left":{
  35. "value":"6504.09",
  36. "color":"#173177"
  37. }
  38. }
  39. }

3.2.1. 搞定 template_id 即模板消息id:

新增模板消息(以测试号为例)

模板内容可设置参数(模板标题不可),供接口调用时使用,参数需以{{开头,以.DATA}}结尾(具体传参看后续代码)

3.2.2. 搞定 touser 即openid

查看用户管理的官方文档;微信开放文档 (qq.com),通过官方接口获取

因为我们是公众号,所以选用获取用户列表的接口:微信开放文档 (qq.com)

  1. http请求方式: GET(请使用https协议)
  2. https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID
  3. 参数 是否必须 说明
  4. access_token 是 调用接口凭证
  5. next_openid 是 第一个拉取的OPENID,不填默认从头开始拉取
  6. 返回说明
  7. 正确时返回JSON数据包:
  8. {
  9. "total":2,
  10. "count":2,
  11. "data":{
  12. "openid":["OPENID1","OPENID2"]},
  13. "next_openid":"NEXT_OPENID"
  14. }

3.2.3. 从获取openid的请求中我们发现需要access_token

获取access_token官方文档:微信开放文档 (qq.com)

  1. https请求方式: GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
  2. 参数说明
  3. 参数 是否必须 说明
  4. grant_type 是 获取access_token填写client_credential
  5. appid 是 第三方用户唯一凭证
  6. secret 是 第三方用户唯一凭证密钥,即appsecret
  7. 返回说明
  8. 正常情况下,微信会返回下述JSON数据包给公众号:
  9. {"access_token":"ACCESS_TOKEN","expires_in":7200}

3.2.4. 发送模板消息的url参数

        这个是发送消息后用户点击卡片跳转的地址(自定义)可以不填

3.2.5. topcolor

       消息卡片的顶部颜色(自定义)

3.2.5. data

       消息的内容(了解结构即可,后续代码中会体现)

3.3. 源码

拷贝完再理解

3.3.1 模板消息DTO

  1. import java.util.Map;
  2. /**
  3. * @Description 微信公众号模板消息请求对象
  4. * @author isymi
  5. * @version
  6. * @date 2023年5月29日下午4:28:09
  7. *
  8. */
  9. public class TemplateMessage {
  10. /**
  11. * 发送消息用户的openid
  12. */
  13. private String touser;
  14. /*
  15. * 模板消息id
  16. */
  17. private String template_id;
  18. /**
  19. * 点击模板信息跳转地址;置空:则在发送后,点击模板消息会进入一个空白页面(ios),或无法点击(android)
  20. */
  21. private String url;
  22. /**
  23. * 卡片顶部颜色
  24. */
  25. private String topcolor;
  26. /**
  27. * key为模板中参数内容"xx.DATA"的xx,value为参数对应具体的值和颜色
  28. */
  29. private Map<String, WeChatTemplateMsg> data;
  30. // private String data;
  31. public TemplateMessage() {
  32. }
  33. public TemplateMessage(String touser, String template_id, String url, String topcolor, Map<String, WeChatTemplateMsg> data) {
  34. this.touser = touser;
  35. this.template_id = template_id;
  36. this.url = url;
  37. this.topcolor = topcolor;
  38. this.data = data;
  39. }
  40. public String getTouser() {
  41. return touser;
  42. }
  43. public void setTouser(String touser) {
  44. this.touser = touser;
  45. }
  46. public String gettemplate_id() {
  47. return template_id;
  48. }
  49. public void settemplate_id(String template_id) {
  50. this.template_id = template_id;
  51. }
  52. public String getUrl() {
  53. return url;
  54. }
  55. public void setUrl(String url) {
  56. this.url = url;
  57. }
  58. public String getTopcolor() {
  59. return topcolor;
  60. }
  61. public void setTopcolor(String topcolor) {
  62. this.topcolor = topcolor;
  63. }
  64. public Map<String, WeChatTemplateMsg> getData() {
  65. return data;
  66. }
  67. public void setData(Map<String, WeChatTemplateMsg> data) {
  68. this.data = data;
  69. }
  70. @Override
  71. public String toString() {
  72. return "TemplateMessage [touser=" + touser + ", template_id=" + template_id + ", url=" + url + ", topcolor="
  73. + topcolor + ", data=" + data + "]";
  74. }
  75. }

3.3.2. 模板消息内容DTO

  1. import java.io.Serializable;
  2. /**
  3. * @Description 模板消息内容类
  4. * @author isymi
  5. * @version
  6. * @date 2023年5月29日下午4:33:27
  7. *
  8. */
  9. public class WeChatTemplateMsg implements Serializable{
  10. /**
  11. * 消息实参
  12. */
  13. private String value;
  14. /**
  15. * 消息颜色
  16. */
  17. private String color;
  18. public WeChatTemplateMsg(String value) {
  19. this.value = value;
  20. this.color = "#173177";
  21. }
  22. public WeChatTemplateMsg(String value, String color) {
  23. this.value = value;
  24. this.color = color;
  25. }
  26. @Override
  27. public String toString() {
  28. return "WeChatTemplateMsg [value=" + value + ", color=" + color + "]";
  29. }
  30. public String getValue() {
  31. return value;
  32. }
  33. public void setValue(String value) {
  34. this.value = value;
  35. }
  36. public String getColor() {
  37. return color;
  38. }
  39. public void setColor(String color) {
  40. this.color = color;
  41. }
  42. }

3.3.3. access_token缓存类:

  1. /**
  2. * @Description access_token缓存类
  3. * @author
  4. * @version
  5. * @date 2023年5月30日上午10:40:08
  6. *
  7. */
  8. public class AccessToken {
  9. private String accessToken;
  10. //过期时间 当前系统时间+微信传来的过期时间
  11. private Long expiresTime;
  12. public AccessToken(String accessToken, String expiresIn) {
  13. this.accessToken = accessToken;
  14. this.expiresTime = System.currentTimeMillis()+Integer.parseInt(expiresIn)*1000;
  15. }
  16. /**
  17. * 判断token是否过期
  18. * @return
  19. */
  20. public boolean isExpired(){
  21. return System.currentTimeMillis()>expiresTime;
  22. }
  23. public String getAccessToken() {
  24. return accessToken;
  25. }
  26. public void setAccessToken(String accessToken) {
  27. this.accessToken = accessToken;
  28. }
  29. public Long getExpiresTime() {
  30. return expiresTime;
  31. }
  32. public void setExpiresTime(Long expiresTime) {
  33. this.expiresTime = expiresTime;
  34. }
  35. public AccessToken(String accessToken, Long expiresTime) {
  36. this.accessToken = accessToken;
  37. this.expiresTime = expiresTime;
  38. }
  39. public AccessToken() {
  40. }
  41. }

3.3.4.http请求工具类:

  1. import java.io.BufferedReader;
  2. import java.net.*;
  3. import java.nio.charset.StandardCharsets;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.io.OutputStream;
  7. import java.net.HttpURLConnection;
  8. import java.net.URL;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. import com.alibaba.fastjson.JSON;
  12. import com.alibaba.fastjson.JSONArray;
  13. import com.alibaba.fastjson.JSONObject;
  14. import com.xx.xx.pojo.TemplateMessage;
  15. /**
  16. * @Description 微信公众号http请求工具类
  17. * @author isymi
  18. * @version
  19. * @date 2023年5月29日下午4:07:39
  20. *
  21. */
  22. public class WXPublicAccountHttpUtil {
  23. /**
  24. * @Description 根据请求获取返回结果字符串(根据请求获取accessToken)
  25. * @date 2023年5月29日下午4:04:21
  26. * @param url
  27. * @return
  28. * @throws IOException
  29. */
  30. public static String get(String url) throws IOException {
  31. HttpURLConnection connection = null;
  32. BufferedReader reader = null;
  33. try {
  34. URL requestUrl = new URL(url);
  35. connection = (HttpURLConnection) requestUrl.openConnection();
  36. connection.setRequestMethod("GET");
  37. int responseCode = connection.getResponseCode();
  38. if (responseCode == HttpURLConnection.HTTP_OK) {
  39. reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  40. StringBuilder response = new StringBuilder();
  41. String line;
  42. while ((line = reader.readLine()) != null) {
  43. response.append(line);
  44. }
  45. return response.toString();
  46. } else {
  47. // Handle error response
  48. System.out.println("HTTP GET request failed with response code: " + responseCode);
  49. return null;
  50. }
  51. } finally {
  52. if (reader != null) {
  53. reader.close();
  54. }
  55. if (connection != null) {
  56. connection.disconnect();
  57. }
  58. }
  59. }
  60. /**
  61. * @Description 根据URl获取JSONObject:根据请求获取关注用户列表数据
  62. * @date 2023年5月29日下午4:02:16
  63. * @param url
  64. * @return
  65. * @throws IOException
  66. */
  67. public static JSONObject getJsonObject(String url) throws IOException {
  68. HttpURLConnection connection = null;
  69. BufferedReader reader = null;
  70. try {
  71. URL urlObj = new URL(url);
  72. connection = (HttpURLConnection) urlObj.openConnection();
  73. connection.setRequestMethod("GET");
  74. StringBuilder response = new StringBuilder();
  75. reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
  76. String line;
  77. while ((line = reader.readLine()) != null) {
  78. response.append(line);
  79. }
  80. /*
  81. * 正确返回的格式
  82. * {
  83. "total":2,
  84. "count":2,
  85. "data":{
  86. "openid":["OPENID1","OPENID2"]},
  87. "next_openid":"NEXT_OPENID"
  88. }
  89. */
  90. return JSON.parseObject(response.toString());
  91. } finally {
  92. if (reader != null) {
  93. reader.close();
  94. }
  95. if (connection != null) {
  96. connection.disconnect();
  97. }
  98. }
  99. }
  100. /**
  101. * @Description 获取关注用户的 openid 集合
  102. * @date 2023年5月29日下午4:04:02
  103. * @param url
  104. * @return
  105. * @throws IOException
  106. */
  107. public static List<String> getOpenidList(String url) throws IOException {
  108. // 获取关注用户列表数据
  109. JSONObject jsonObject = getJsonObject(url);
  110. System.out.println(jsonObject);
  111. // 错误情况
  112. if (jsonObject.containsKey("errcode")) {
  113. int errcode = jsonObject.getIntValue("errcode");
  114. String errmsg = jsonObject.getString("errmsg");
  115. throw new RuntimeException("Failed to get openid list. errcode: " + errcode + ", errmsg: " + errmsg);
  116. }
  117. int total = jsonObject.getIntValue("total");
  118. // 无用户关注 {"total":0,"count":0,"next_openid":""}
  119. if (total == 0) {
  120. throw new RuntimeException("No openid found. Total is 0.");
  121. }
  122. // 有用户关注:
  123. /**
  124. * {"total":1,
  125. * "data":{
  126. * "openid":["o-tgG5-VaQfsgdjerHA-z2PeZFls"]},
  127. * "count":1,
  128. * "next_openid":"o-tgG5-VaQfsgdjerHA-z2PeZFls"}
  129. */
  130. JSONObject dataObject = jsonObject.getJSONObject("data");
  131. int count = dataObject.getIntValue("count");
  132. System.out.println("关注总人数:"+count);
  133. JSONArray openidArray = dataObject.getJSONArray("openid");
  134. // 将 openid 数组封装为 List 集合
  135. List<String> openidList = new ArrayList<>();
  136. for (int i = 0; i < openidArray.size(); i++) {
  137. String openid = openidArray.getString(i);
  138. openidList.add(openid);
  139. }
  140. return openidList;
  141. }
  142. /**
  143. * @Description 发送消息
  144. * @date 2023年5月29日下午4:58:02
  145. * @param accessToken
  146. * @param templateMessage
  147. * @return
  148. * @throws IOException
  149. */
  150. public static String sendMessage( String accessToken, TemplateMessage templateMessage) throws IOException {
  151. String requestUrl ="https://api.weixin.qq.com/cgi-bin/message/template/send" + "?access_token=" + accessToken;
  152. URL urlObject = new URL(requestUrl);
  153. HttpURLConnection connection = (HttpURLConnection) urlObject.openConnection();
  154. connection.setRequestMethod("POST");
  155. connection.setDoOutput(true);
  156. connection.setRequestProperty("Content-Type", "application/json");
  157. String requestBody = JSON.toJSONString(templateMessage);
  158. byte[] requestBodyBytes = requestBody.getBytes(StandardCharsets.UTF_8);
  159. connection.setRequestProperty("Content-Length", String.valueOf(requestBodyBytes.length));
  160. OutputStream outputStream = connection.getOutputStream();
  161. outputStream.write(requestBodyBytes);
  162. outputStream.close();
  163. int responseCode = connection.getResponseCode();
  164. BufferedReader reader;
  165. if (responseCode >= 200 && responseCode <= 299) {
  166. reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  167. } else {
  168. reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
  169. }
  170. StringBuilder response = new StringBuilder();
  171. String line;
  172. while ((line = reader.readLine()) != null) {
  173. response.append(line);
  174. }
  175. reader.close();
  176. connection.disconnect();
  177. System.out.println("Response Code: " + responseCode);
  178. System.out.println("Response Body: " + response.toString());
  179. return response.toString();
  180. }
  181. }

3.3.5. 最终的Servlet(controller自行转换)(为方便观看所有逻辑都写在这里了,自行优化):

  1. import java.io.IOException;
  2. import java.io.InputStream;
  3. import java.io.OutputStream;
  4. import java.io.OutputStreamWriter;
  5. import java.io.UnsupportedEncodingException;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import java.net.URLEncoder;
  9. import java.security.MessageDigest;
  10. import java.security.NoSuchAlgorithmException;
  11. import java.util.ArrayList;
  12. import java.util.Arrays;
  13. import java.util.HashMap;
  14. import java.util.List;
  15. import java.util.Map;
  16. import javax.servlet.ServletException;
  17. import javax.servlet.annotation.WebServlet;
  18. import javax.servlet.http.HttpServlet;
  19. import javax.servlet.http.HttpServletRequest;
  20. import javax.servlet.http.HttpServletResponse;
  21. import javax.servlet.http.HttpSession;
  22. import com.alibaba.fastjson.JSON;
  23. import com.alibaba.fastjson.JSONArray;
  24. import com.alibaba.fastjson.JSONObject;
  25. import com.xx.srm.pojo.AccessToken;
  26. import com.xx.xx.pojo.TemplateMessage;
  27. import com.xx.xx.pojo.WeChatTemplateMsg;
  28. import com.xx.xx.utils.WXPublicAccountHttpUtil;
  29. @WebServlet(urlPatterns = {
  30. "/wx",
  31. "/wx/message" })
  32. public class WxServlet extends HttpServlet {
  33. // 必须替换
  34. private static final String wxToken = "xxxxxm8";
  35. // 必须替换
  36. public static final String APPID = "wx3xxxxxx1795fa";
  37. // 必须替换
  38. public static final String SECRET = "57b96fxxxxxxxxeab62bfe3";
  39. // 必须替换
  40. public static final String MESSAGE_TEMPLATE_ID = "N6MyyAF0Ucxxxxxxxxxxxxxxxxp-OGsWnQut_niUAaY";
  41. /**
  42. * 全局AccessToken
  43. */
  44. private static AccessToken at;
  45. @Override
  46. protected void service(HttpServletRequest request, HttpServletResponse response)
  47. throws ServletException, IOException {
  48. if ("/wx".equals(request.getServletPath())) {
  49. doGetWx(request, response);
  50. } else if ("/wx/message".equals(request.getServletPath())) {
  51. doSendMessage(request, response);
  52. }
  53. }
  54. /**
  55. * @Description 校验配置URL服务器的合法性
  56. * @date 2023年5月29日下午4:17:40
  57. * @param request
  58. * @param response
  59. * @throws ServletException
  60. * @throws IOException
  61. */
  62. public void doGetWx(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  63. String signature = request.getParameter("signature");
  64. String timestamp = request.getParameter("timestamp");
  65. String nonce = request.getParameter("nonce");
  66. String echostr = request.getParameter("echostr");
  67. // 将微信echostr返回给微信服务器
  68. try (OutputStream os = response.getOutputStream()) {
  69. String sha1 = getSHA1(wxToken, timestamp, nonce, "");
  70. // 和signature进行对比
  71. if (sha1.equals(signature)) {
  72. // 返回echostr给微信
  73. os.write(URLEncoder.encode(echostr, "UTF-8").getBytes());
  74. os.flush();
  75. }
  76. } catch (Exception e) {
  77. e.printStackTrace();
  78. }
  79. }
  80. /**
  81. * @Description 发送模板消息
  82. * @date 2023年5月30日上午10:57:45
  83. * @param request
  84. * @param response
  85. * @throws IOException
  86. */
  87. private void doSendMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {
  88. String token = getToken();
  89. String url = "https://api.weixin.qq.com/cgi-bin/user/get?" + "access_token=" + token;
  90. // 获取 openid 数组
  91. List<String> userOpenids = WXPublicAccountHttpUtil.getOpenidList(url);
  92. // 主要的业务逻辑:
  93. for (String openId : userOpenids) {
  94. TemplateMessage templateMessage = new TemplateMessage();
  95. templateMessage.setTouser(openId);
  96. templateMessage.settemplate_id(MESSAGE_TEMPLATE_ID);
  97. templateMessage.setTopcolor("#FF0000");
  98. // key对应创建模板内容中的形参
  99. //{{title.DATA}} {{username.DATA}} {{quote.DATA}} {{date.DATA}}
  100. // WeChatTemplateMsg对应实参和字体颜色
  101. Map<String, WeChatTemplateMsg> data = new HashMap<String, WeChatTemplateMsg>();
  102. data.put("title", new WeChatTemplateMsg("你有一条新的消息", "#173177"));
  103. data.put("username", new WeChatTemplateMsg("黄先生", "#173177"));
  104. data.put("date", new WeChatTemplateMsg("2023年05月29日 16时24分", "#173177"));
  105. data.put("quote", new WeChatTemplateMsg("你好", "#173177"));
  106. templateMessage.setData(data);
  107. System.out.println(templateMessage);
  108. WXPublicAccountHttpUtil.sendMessage(getToken(), templateMessage);
  109. }
  110. }
  111. /**
  112. * @Description 获取token,本地缓存有就直接返回,没有就发送请求获取(wx官方api获取token每天有限制,因此需做缓存)
  113. * @date 2023年5月29日下午4:13:17
  114. * @return
  115. */
  116. public static String getToken() {
  117. if (at == null || at.isExpired()) {
  118. getAccessToken();
  119. }
  120. return at.getAccessToken();
  121. }
  122. /**
  123. * 给AccessToken赋值
  124. */
  125. private static void getAccessToken() {
  126. // 发送请求获取token
  127. String token = null;
  128. try {
  129. String url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential"+ "&appid=" + APPID + "&secret=" + SECRET;
  130. token = WXPublicAccountHttpUtil.get(url);
  131. } catch (Exception e) {
  132. e.printStackTrace();
  133. }
  134. JSONObject jsonObject = JSONObject.parseObject(token);
  135. String accessToken = (String) jsonObject.get("access_token");
  136. Integer expiresIn = (Integer) jsonObject.get("expires_in");
  137. // 创建token对象,并存储
  138. at = new AccessToken(accessToken, String.valueOf(expiresIn));
  139. System.out.println(token);
  140. }
  141. /**
  142. * 用SHA1算法生成安全签名
  143. *
  144. * @param token 票据
  145. * @param timestamp 时间戳
  146. * @param nonce 随机字符串
  147. * @param encrypt 密文
  148. * @return 安全签名
  149. * @throws Exception
  150. */
  151. public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws Exception {
  152. try {
  153. String[] array = new String[] { token, timestamp, nonce, encrypt };
  154. StringBuffer sb = new StringBuffer();
  155. // 字符串排序
  156. Arrays.sort(array);
  157. for (int i = 0; i < 4; i++) {
  158. sb.append(array[i]);
  159. }
  160. String str = sb.toString();
  161. // SHA1签名生成
  162. MessageDigest md = MessageDigest.getInstance("SHA-1");
  163. md.update(str.getBytes());
  164. byte[] digest = md.digest();
  165. StringBuffer hexstr = new StringBuffer();
  166. String shaHex = "";
  167. for (int i = 0; i < digest.length; i++) {
  168. shaHex = Integer.toHexString(digest[i] & 0xFF);
  169. if (shaHex.length() < 2) {
  170. hexstr.append(0);
  171. }
  172. hexstr.append(shaHex);
  173. }
  174. return hexstr.toString();
  175. } catch (Exception e) {
  176. e.printStackTrace();
  177. }
  178. return "";
  179. }
  180. }

3.4.测试

关注公众号

浏览器访问 http://22717eef.r6.vip.cpolar.cn/xjsrm/wx/message(替换为自己的)

查看微信消息

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

闽ICP备14008679号