TencentWeComController.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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.net.HttpURLConnection;
  22. import java.net.URL;
  23. import java.nio.file.Files;
  24. import java.nio.file.Paths;
  25. import java.util.Base64;
  26. import java.util.Map;
  27. import java.util.UUID;
  28. import static com.tzld.piaoquan.growth.common.common.enums.CorpEnum.*;
  29. @Slf4j
  30. @RestController
  31. @RequestMapping("/wecom/server")
  32. public class TencentWeComController {
  33. @Autowired
  34. private WeComUserService weComUserService;
  35. @Autowired
  36. private WeComAutoReply weComAutoReply;
  37. @Autowired
  38. private HttpPoolClient httpPoolClient;
  39. @GetMapping("/verify")
  40. public void verifyGet(HttpServletRequest request, HttpServletResponse response) {
  41. try {
  42. // 微信加密签名
  43. String msgSignature = request.getParameter("msg_signature");
  44. // 时间戳
  45. String timestamp = request.getParameter("timestamp");
  46. // 随机数
  47. String nonce = request.getParameter("nonce");
  48. // 随机字符串
  49. // 如果是刷新,需返回原echostr
  50. String echoStr = request.getParameter("echostr");
  51. // 微信加密签名
  52. WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(WeComServerConstant.TOKEN,
  53. WeComServerConstant.ENCODING_AES_KEY,
  54. WeComServerConstant.CORP_ID);
  55. String sEchoStr = ""; //需要返回的明文
  56. PrintWriter out;
  57. sEchoStr = wxcpt.VerifyURL(msgSignature, timestamp,
  58. nonce, echoStr);
  59. log.info("verifyurl echostr: " + sEchoStr);
  60. // 验证URL成功,将sEchoStr返回
  61. out = response.getWriter();
  62. out.print(sEchoStr);
  63. } catch (Exception e) {
  64. //验证URL失败,错误原因请查看异常
  65. log.error("verifyGet error", e);
  66. }
  67. }
  68. /**
  69. * 刷新 ticket
  70. */
  71. @PostMapping(value = "/verify")
  72. public String verifyPost(HttpServletRequest request) {
  73. try {
  74. // 微信加密签名
  75. String msg_signature = request.getParameter("msg_signature");
  76. // 时间戳
  77. String timestamp = request.getParameter("timestamp");
  78. // 随机数
  79. String nonce = request.getParameter("nonce");
  80. String id = WeComServerConstant.CORP_ID;
  81. WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(WeComServerConstant.TOKEN, WeComServerConstant.ENCODING_AES_KEY, id);
  82. StringBuilder postData = new StringBuilder(); // 密文,对应POST请求的数据
  83. //1.获取加密的请求消息:使用输入流获得加密请求消息postData
  84. ServletInputStream in = request.getInputStream();
  85. BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  86. String tempStr = ""; //作为输出字符串的临时串,用于判断是否读取完毕
  87. while (null != (tempStr = reader.readLine())) {
  88. postData.append(tempStr);
  89. }
  90. String suiteXml = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, postData.toString());
  91. log.info("suiteXml: " + suiteXml);
  92. Map suiteMap = WxUtil.transferXmlToMap(suiteXml);
  93. log.info("suiteMap = {}", JSONObject.toJSONString(suiteMap));
  94. if (suiteMap != null) {
  95. String changeType = (String) suiteMap.get("ChangeType");
  96. if (StringUtils.isNotEmpty(changeType) && changeType.equals("add_external_contact")) {
  97. String userId = (String) suiteMap.get("UserID");
  98. String externalUserId = (String) suiteMap.get("ExternalUserID");
  99. String welcomeCode = (String) suiteMap.get("WelcomeCode");
  100. log.info("addStaffWithUser userId={} externalUserId={}", userId, externalUserId);
  101. weComUserService.addStaffWithUser(externalUserId, userId, HNWQ.getId());
  102. weComAutoReply.AutoReplyMessage(welcomeCode, externalUserId, userId, HNWQ.getId());
  103. }
  104. if (StringUtils.isNotEmpty(changeType) && changeType.equals("del_follow_user")) {
  105. String userId = (String) suiteMap.get("UserID");
  106. String externalUserId = (String) suiteMap.get("ExternalUserID");
  107. log.info("delStaffWithUser userId={} externalUserId={}", userId, externalUserId);
  108. weComUserService.delStaffWithUser(externalUserId, userId, HNWQ.getId(), System.currentTimeMillis());
  109. }
  110. }
  111. } catch (Exception e) {
  112. log.error("verifyPost error", e);
  113. }
  114. String success = "success";
  115. return success;
  116. }
  117. //优量圈验证接口
  118. @GetMapping("/ylq/verify")
  119. public void ylqVerifyGet(HttpServletRequest request, HttpServletResponse response) {
  120. try {
  121. // 微信加密签名
  122. String msgSignature = request.getParameter("msg_signature");
  123. // 时间戳
  124. String timestamp = request.getParameter("timestamp");
  125. // 随机数
  126. String nonce = request.getParameter("nonce");
  127. // 随机字符串
  128. // 如果是刷新,需返回原echostr
  129. String echoStr = request.getParameter("echostr");
  130. // 微信加密签名
  131. WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(WeComServerConstant.YLQ_TOKEN,
  132. WeComServerConstant.YLQ_ENCODING_AES_KEY,
  133. WeComServerConstant.YLQ_CORP_ID);
  134. String sEchoStr = ""; //需要返回的明文
  135. PrintWriter out;
  136. sEchoStr = wxcpt.VerifyURL(msgSignature, timestamp,
  137. nonce, echoStr);
  138. log.info("verifyurl echostr: " + sEchoStr);
  139. // 验证URL成功,将sEchoStr返回
  140. out = response.getWriter();
  141. out.print(sEchoStr);
  142. } catch (Exception e) {
  143. //验证URL失败,错误原因请查看异常
  144. log.error("verifyGet error", e);
  145. }
  146. }
  147. //优量圈回调消息接口
  148. @PostMapping(value = "/ylq/verify")
  149. public String ylqVerifyPost(HttpServletRequest request) {
  150. try {
  151. // 微信加密签名
  152. String msg_signature = request.getParameter("msg_signature");
  153. // 时间戳
  154. String timestamp = request.getParameter("timestamp");
  155. // 随机数
  156. String nonce = request.getParameter("nonce");
  157. String id = WeComServerConstant.YLQ_CORP_ID;
  158. WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(WeComServerConstant.YLQ_TOKEN, WeComServerConstant.YLQ_ENCODING_AES_KEY, id);
  159. StringBuilder postData = new StringBuilder(); // 密文,对应POST请求的数据
  160. //1.获取加密的请求消息:使用输入流获得加密请求消息postData
  161. ServletInputStream in = request.getInputStream();
  162. BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  163. String tempStr = ""; //作为输出字符串的临时串,用于判断是否读取完毕
  164. while (null != (tempStr = reader.readLine())) {
  165. postData.append(tempStr);
  166. }
  167. String suiteXml = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, postData.toString());
  168. log.info("suiteXml: " + suiteXml);
  169. Map suiteMap = WxUtil.transferXmlToMap(suiteXml);
  170. log.info("suiteMap = {}", JSONObject.toJSONString(suiteMap));
  171. if (suiteMap != null) {
  172. String changeType = (String) suiteMap.get("ChangeType");
  173. if (StringUtils.isNotEmpty(changeType) && changeType.equals("add_external_contact")) {
  174. String userId = (String) suiteMap.get("UserID");
  175. String externalUserId = (String) suiteMap.get("ExternalUserID");
  176. String welcomeCode = (String) suiteMap.get("WelcomeCode");
  177. log.info("YLQ addStaffWithUser userId={} externalUserId={}", userId, externalUserId);
  178. weComUserService.addStaffWithUser(externalUserId, userId, YLQ.getId());
  179. weComAutoReply.AutoReplyMessage(welcomeCode, externalUserId, userId, YLQ.getId());
  180. }
  181. if (StringUtils.isNotEmpty(changeType) && changeType.equals("del_follow_user")) {
  182. String userId = (String) suiteMap.get("UserID");
  183. String externalUserId = (String) suiteMap.get("ExternalUserID");
  184. log.info("YLQ delStaffWithUser userId={} externalUserId={}", userId, externalUserId);
  185. weComUserService.delStaffWithUser(externalUserId, userId, YLQ.getId(), System.currentTimeMillis());
  186. }
  187. }
  188. } catch (Exception e) {
  189. log.error("verifyPost error", e);
  190. }
  191. String success = "success";
  192. return success;
  193. }
  194. //赛博成行验证接口
  195. @GetMapping("/sbcx/verify")
  196. public void sbcxVerifyGet(HttpServletRequest request, HttpServletResponse response) {
  197. try {
  198. // 微信加密签名
  199. String msgSignature = request.getParameter("msg_signature");
  200. // 时间戳
  201. String timestamp = request.getParameter("timestamp");
  202. // 随机数
  203. String nonce = request.getParameter("nonce");
  204. // 随机字符串
  205. // 如果是刷新,需返回原echostr
  206. String echoStr = request.getParameter("echostr");
  207. // 微信加密签名
  208. WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(WeComServerConstant.SBCX_TOKEN,
  209. WeComServerConstant.SBCX_ENCODING_AES_KEY,
  210. WeComServerConstant.SBCX_CORP_ID);
  211. String sEchoStr = ""; //需要返回的明文
  212. PrintWriter out;
  213. sEchoStr = wxcpt.VerifyURL(msgSignature, timestamp,
  214. nonce, echoStr);
  215. log.info("verifyurl echostr: " + sEchoStr);
  216. // 验证URL成功,将sEchoStr返回
  217. out = response.getWriter();
  218. out.print(sEchoStr);
  219. } catch (Exception e) {
  220. //验证URL失败,错误原因请查看异常
  221. log.error("verifyGet error", e);
  222. }
  223. }
  224. //优量圈回调消息接口
  225. @PostMapping(value = "/sbcx/verify")
  226. public String sbcxVerifyPost(HttpServletRequest request) {
  227. try {
  228. // 微信加密签名
  229. String msg_signature = request.getParameter("msg_signature");
  230. // 时间戳
  231. String timestamp = request.getParameter("timestamp");
  232. // 随机数
  233. String nonce = request.getParameter("nonce");
  234. String id = WeComServerConstant.SBCX_CORP_ID;
  235. WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(WeComServerConstant.SBCX_TOKEN, WeComServerConstant.SBCX_ENCODING_AES_KEY, id);
  236. StringBuilder postData = new StringBuilder(); // 密文,对应POST请求的数据
  237. //1.获取加密的请求消息:使用输入流获得加密请求消息postData
  238. ServletInputStream in = request.getInputStream();
  239. BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  240. String tempStr = ""; //作为输出字符串的临时串,用于判断是否读取完毕
  241. while (null != (tempStr = reader.readLine())) {
  242. postData.append(tempStr);
  243. }
  244. String suiteXml = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, postData.toString());
  245. log.info("suiteXml: " + suiteXml);
  246. Map suiteMap = WxUtil.transferXmlToMap(suiteXml);
  247. log.info("suiteMap = {}", JSONObject.toJSONString(suiteMap));
  248. if (suiteMap != null) {
  249. String changeType = (String) suiteMap.get("ChangeType");
  250. if (StringUtils.isNotEmpty(changeType) && changeType.equals("add_external_contact")) {
  251. String userId = (String) suiteMap.get("UserID");
  252. String externalUserId = (String) suiteMap.get("ExternalUserID");
  253. String welcomeCode = (String) suiteMap.get("WelcomeCode");
  254. log.info("SBCX addStaffWithUser userId={} externalUserId={}", userId, externalUserId);
  255. weComUserService.addStaffWithUser(externalUserId, userId, SBCX.getId());
  256. weComAutoReply.AutoReplyMessage(welcomeCode, externalUserId, userId, SBCX.getId());
  257. }
  258. if (StringUtils.isNotEmpty(changeType) && changeType.equals("del_follow_user")) {
  259. String userId = (String) suiteMap.get("UserID");
  260. String externalUserId = (String) suiteMap.get("ExternalUserID");
  261. log.info("SBCX delStaffWithUser userId={} externalUserId={}", userId, externalUserId);
  262. weComUserService.delStaffWithUser(externalUserId, userId, SBCX.getId(), System.currentTimeMillis());
  263. }
  264. }
  265. } catch (Exception e) {
  266. log.error("verifyPost error", e);
  267. }
  268. String success = "success";
  269. return success;
  270. }
  271. @PostMapping("/send/post")
  272. public String sendPost(@RequestBody SendRequestParam sendRequestParam) throws IOException {
  273. log.info("sendPost sendRequestParam={}", sendRequestParam);
  274. String res = httpPoolClient.post(sendRequestParam.getUrl(), sendRequestParam.getParam());
  275. log.info("sendPost sendRequestParam={}, res={}", sendRequestParam, res);
  276. return res;
  277. }
  278. @GetMapping("/send/post/file")
  279. public String sendPostFile(@RequestParam String url, @RequestParam() String cover) throws IOException {
  280. byte[] decodedBytes = Base64.getDecoder().decode(url);
  281. String targetUrl = new String(decodedBytes);
  282. byte[] coverDecodedBytes = Base64.getDecoder().decode(cover);
  283. String targetCover = new String(coverDecodedBytes);
  284. log.info("sendPostFile url={},cover={}", targetUrl, targetCover);
  285. String filePath = UUID.randomUUID() + ".jpg"; // 临时文件路径
  286. HttpURLConnection httpUrl = (HttpURLConnection) new URL(targetCover).openConnection();
  287. httpUrl.connect();
  288. InputStream inputStream = httpUrl.getInputStream();
  289. // 将文件内容写入临时文件
  290. try (OutputStream outputStream = Files.newOutputStream(Paths.get(filePath))) {
  291. byte[] buffer = new byte[4096];
  292. int bytesRead;
  293. while ((bytesRead = inputStream.read(buffer)) != -1) {
  294. outputStream.write(buffer, 0, bytesRead);
  295. }
  296. }
  297. inputStream.close();
  298. httpUrl.disconnect();
  299. File file = new File(filePath);
  300. String res = httpPoolClient.post(targetUrl, file);
  301. log.info("sendPostFile url={},cover={},res={}", targetUrl, targetCover, res);
  302. return res;
  303. }
  304. @GetMapping("/send/get")
  305. public String sendGet(@RequestParam String url) throws IOException {
  306. byte[] decodedBytes = Base64.getDecoder().decode(url);
  307. String originalString = new String(decodedBytes);
  308. log.info("sendGet url={}", originalString);
  309. String res = httpPoolClient.get(originalString);
  310. log.info("sendGet url={} res={}", originalString, res);
  311. return res;
  312. }
  313. }