TencentWeComController.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. package com.tzld.piaoquan.api.controller;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.tzld.piaoquan.growth.common.model.vo.SendRequestParam;
  4. import com.tzld.piaoquan.api.service.WeComAutoReply;
  5. import com.tzld.piaoquan.growth.common.common.constant.WeComServerConstant;
  6. import com.tzld.piaoquan.growth.common.component.HttpPoolClient;
  7. import com.tzld.piaoquan.growth.common.service.WeComUserService;
  8. import com.tzld.piaoquan.growth.common.utils.wecom.WXBizMsgCrypt;
  9. import com.tzld.piaoquan.growth.common.utils.wecom.WxUtil;
  10. import lombok.extern.slf4j.Slf4j;
  11. import lombok.val;
  12. import org.apache.commons.lang3.StringUtils;
  13. import org.apache.ibatis.annotations.Param;
  14. import org.springframework.beans.factory.annotation.Autowired;
  15. import org.springframework.web.bind.annotation.*;
  16. import org.springframework.web.multipart.MultipartFile;
  17. import javax.servlet.ServletInputStream;
  18. import javax.servlet.http.HttpServletRequest;
  19. import javax.servlet.http.HttpServletResponse;
  20. import java.io.*;
  21. import java.nio.file.Files;
  22. import java.nio.file.Paths;
  23. import java.util.Base64;
  24. import java.util.Map;
  25. import java.util.UUID;
  26. import static com.tzld.piaoquan.growth.common.common.enums.CorpEnum.HNWQ;
  27. import static com.tzld.piaoquan.growth.common.common.enums.CorpEnum.YLQ;
  28. @Slf4j
  29. @RestController
  30. @RequestMapping("/wecom/server")
  31. public class TencentWeComController {
  32. @Autowired
  33. private WeComUserService weComUserService;
  34. @Autowired
  35. private WeComAutoReply weComAutoReply;
  36. @Autowired
  37. private HttpPoolClient httpPoolClient;
  38. @GetMapping("/verify")
  39. public void verifyGet(HttpServletRequest request, HttpServletResponse response) {
  40. try {
  41. // 微信加密签名
  42. String msgSignature = request.getParameter("msg_signature");
  43. // 时间戳
  44. String timestamp = request.getParameter("timestamp");
  45. // 随机数
  46. String nonce = request.getParameter("nonce");
  47. // 随机字符串
  48. // 如果是刷新,需返回原echostr
  49. String echoStr = request.getParameter("echostr");
  50. // 微信加密签名
  51. WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(WeComServerConstant.TOKEN,
  52. WeComServerConstant.ENCODING_AES_KEY,
  53. WeComServerConstant.CORP_ID);
  54. String sEchoStr = ""; //需要返回的明文
  55. PrintWriter out;
  56. sEchoStr = wxcpt.VerifyURL(msgSignature, timestamp,
  57. nonce, echoStr);
  58. log.info("verifyurl echostr: " + sEchoStr);
  59. // 验证URL成功,将sEchoStr返回
  60. out = response.getWriter();
  61. out.print(sEchoStr);
  62. } catch (Exception e) {
  63. //验证URL失败,错误原因请查看异常
  64. log.error("verifyGet error", e);
  65. }
  66. }
  67. /**
  68. * 刷新 ticket
  69. */
  70. @PostMapping(value = "/verify")
  71. public String verifyPost(HttpServletRequest request) {
  72. try {
  73. // 微信加密签名
  74. String msg_signature = request.getParameter("msg_signature");
  75. // 时间戳
  76. String timestamp = request.getParameter("timestamp");
  77. // 随机数
  78. String nonce = request.getParameter("nonce");
  79. String id = WeComServerConstant.CORP_ID;
  80. WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(WeComServerConstant.TOKEN, WeComServerConstant.ENCODING_AES_KEY, id);
  81. StringBuilder postData = new StringBuilder(); // 密文,对应POST请求的数据
  82. //1.获取加密的请求消息:使用输入流获得加密请求消息postData
  83. ServletInputStream in = request.getInputStream();
  84. BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  85. String tempStr = ""; //作为输出字符串的临时串,用于判断是否读取完毕
  86. while (null != (tempStr = reader.readLine())) {
  87. postData.append(tempStr);
  88. }
  89. String suiteXml = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, postData.toString());
  90. log.info("suiteXml: " + suiteXml);
  91. Map suiteMap = WxUtil.transferXmlToMap(suiteXml);
  92. log.info("suiteMap = {}", JSONObject.toJSONString(suiteMap));
  93. if (suiteMap != null) {
  94. String changeType = (String) suiteMap.get("ChangeType");
  95. if (StringUtils.isNotEmpty(changeType) && changeType.equals("add_external_contact")) {
  96. String userId = (String) suiteMap.get("UserID");
  97. String externalUserId = (String) suiteMap.get("ExternalUserID");
  98. String welcomeCode = (String) suiteMap.get("WelcomeCode");
  99. log.info("addStaffWithUser userId={} externalUserId={}", userId, externalUserId);
  100. weComUserService.addStaffWithUser(externalUserId, userId, HNWQ.getId());
  101. weComAutoReply.AutoReplyMessage(welcomeCode, externalUserId, userId, HNWQ.getId());
  102. }
  103. if (StringUtils.isNotEmpty(changeType) && changeType.equals("del_follow_user")) {
  104. String userId = (String) suiteMap.get("UserID");
  105. String externalUserId = (String) suiteMap.get("ExternalUserID");
  106. log.info("delStaffWithUser userId={} externalUserId={}", userId, externalUserId);
  107. weComUserService.delStaffWithUser(externalUserId, userId, HNWQ.getId(), System.currentTimeMillis());
  108. }
  109. }
  110. } catch (Exception e) {
  111. log.error("verifyPost error", e);
  112. }
  113. String success = "success";
  114. return success;
  115. }
  116. //优量圈验证接口
  117. @GetMapping("/ylq/verify")
  118. public void ylqVerifyGet(HttpServletRequest request, HttpServletResponse response) {
  119. try {
  120. // 微信加密签名
  121. String msgSignature = request.getParameter("msg_signature");
  122. // 时间戳
  123. String timestamp = request.getParameter("timestamp");
  124. // 随机数
  125. String nonce = request.getParameter("nonce");
  126. // 随机字符串
  127. // 如果是刷新,需返回原echostr
  128. String echoStr = request.getParameter("echostr");
  129. // 微信加密签名
  130. WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(WeComServerConstant.YLQ_TOKEN,
  131. WeComServerConstant.YLQ_ENCODING_AES_KEY,
  132. WeComServerConstant.YLQ_CORP_ID);
  133. String sEchoStr = ""; //需要返回的明文
  134. PrintWriter out;
  135. sEchoStr = wxcpt.VerifyURL(msgSignature, timestamp,
  136. nonce, echoStr);
  137. log.info("verifyurl echostr: " + sEchoStr);
  138. // 验证URL成功,将sEchoStr返回
  139. out = response.getWriter();
  140. out.print(sEchoStr);
  141. } catch (Exception e) {
  142. //验证URL失败,错误原因请查看异常
  143. log.error("verifyGet error", e);
  144. }
  145. }
  146. //优量圈回调消息接口
  147. @PostMapping(value = "/ylq/verify")
  148. public String ylqVerifyPost(HttpServletRequest request) {
  149. try {
  150. // 微信加密签名
  151. String msg_signature = request.getParameter("msg_signature");
  152. // 时间戳
  153. String timestamp = request.getParameter("timestamp");
  154. // 随机数
  155. String nonce = request.getParameter("nonce");
  156. String id = WeComServerConstant.YLQ_CORP_ID;
  157. WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(WeComServerConstant.YLQ_TOKEN, WeComServerConstant.YLQ_ENCODING_AES_KEY, id);
  158. StringBuilder postData = new StringBuilder(); // 密文,对应POST请求的数据
  159. //1.获取加密的请求消息:使用输入流获得加密请求消息postData
  160. ServletInputStream in = request.getInputStream();
  161. BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  162. String tempStr = ""; //作为输出字符串的临时串,用于判断是否读取完毕
  163. while (null != (tempStr = reader.readLine())) {
  164. postData.append(tempStr);
  165. }
  166. String suiteXml = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, postData.toString());
  167. log.info("suiteXml: " + suiteXml);
  168. Map suiteMap = WxUtil.transferXmlToMap(suiteXml);
  169. log.info("suiteMap = {}", JSONObject.toJSONString(suiteMap));
  170. if (suiteMap != null) {
  171. String changeType = (String) suiteMap.get("ChangeType");
  172. if (StringUtils.isNotEmpty(changeType) && changeType.equals("add_external_contact")) {
  173. String userId = (String) suiteMap.get("UserID");
  174. String externalUserId = (String) suiteMap.get("ExternalUserID");
  175. String welcomeCode = (String) suiteMap.get("WelcomeCode");
  176. log.info("YLQ addStaffWithUser userId={} externalUserId={}", userId, externalUserId);
  177. weComUserService.addStaffWithUser(externalUserId, userId, YLQ.getId());
  178. weComAutoReply.AutoReplyMessage(welcomeCode, externalUserId, userId, YLQ.getId());
  179. }
  180. if (StringUtils.isNotEmpty(changeType) && changeType.equals("del_follow_user")) {
  181. String userId = (String) suiteMap.get("UserID");
  182. String externalUserId = (String) suiteMap.get("ExternalUserID");
  183. log.info("YLQ delStaffWithUser userId={} externalUserId={}", userId, externalUserId);
  184. weComUserService.delStaffWithUser(externalUserId, userId, YLQ.getId(), System.currentTimeMillis());
  185. }
  186. }
  187. } catch (Exception e) {
  188. log.error("verifyPost error", e);
  189. }
  190. String success = "success";
  191. return success;
  192. }
  193. @PostMapping("/send/post")
  194. public String sendPost(@RequestBody SendRequestParam sendRequestParam) throws IOException {
  195. log.info("sendPost sendRequestParam={}", sendRequestParam);
  196. return httpPoolClient.post(sendRequestParam.getUrl(), sendRequestParam.getParam());
  197. }
  198. @PostMapping("/send/post/file")
  199. public String sendPostFile(@RequestParam String url, @RequestParam("media") MultipartFile multipartFile) throws IOException {
  200. String filePath = UUID.randomUUID() + ".jpg";
  201. if (multipartFile.isEmpty()) {
  202. log.error("multipartFile is empty");
  203. }
  204. File file = new File(filePath);
  205. // 将MultipartFile的内容传输到File中
  206. multipartFile.transferTo(file);
  207. byte[] decodedBytes = Base64.getDecoder().decode(url);
  208. String originalString = new String(decodedBytes);
  209. log.info("sendPostFile url={}", originalString);
  210. String post = httpPoolClient.post(url, file);
  211. log.info("sendPostFile post={}", post);
  212. Files.delete(Paths.get(filePath));
  213. return post;
  214. }
  215. @GetMapping("/send/get")
  216. public String sendGet(@RequestParam String url) throws IOException {
  217. byte[] decodedBytes = Base64.getDecoder().decode(url);
  218. String originalString = new String(decodedBytes);
  219. log.info("sendGet url={}", originalString);
  220. return httpPoolClient.get(originalString);
  221. }
  222. }