TWechatServiceImpl.java 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. package com.szwl.service.impl;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.szwl.constant.ConfigConsts;
  4. import com.szwl.model.bean.WeChatTemplateMsg;
  5. import com.szwl.model.entity.TAdmin;
  6. import com.szwl.model.entity.TWechat;
  7. import com.szwl.mapper.TWechatMapper;
  8. import com.szwl.service.TAdminService;
  9. import com.szwl.service.TWechatService;
  10. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  11. import lombok.extern.slf4j.Slf4j;
  12. import org.apache.commons.lang.StringUtils;
  13. import org.springframework.beans.factory.annotation.Autowired;
  14. import org.springframework.data.redis.core.StringRedisTemplate;
  15. import org.springframework.http.ResponseEntity;
  16. import org.springframework.stereotype.Service;
  17. import org.springframework.web.client.RestTemplate;
  18. import javax.annotation.Resource;
  19. import java.io.BufferedReader;
  20. import java.io.IOException;
  21. import java.io.InputStreamReader;
  22. import java.io.PrintWriter;
  23. import java.net.URL;
  24. import java.net.URLConnection;
  25. import java.text.SimpleDateFormat;
  26. import java.util.Date;
  27. import java.util.HashMap;
  28. import java.util.Map;
  29. import java.util.concurrent.TimeUnit;
  30. /**
  31. * <p>
  32. * 服务实现类
  33. * </p>
  34. *
  35. * @author wuhs
  36. * @since 2023-05-22
  37. */
  38. @Slf4j
  39. @Service
  40. public class TWechatServiceImpl extends ServiceImpl<TWechatMapper, TWechat> implements TWechatService {
  41. @Autowired
  42. TAdminService adminService;
  43. @Resource
  44. private StringRedisTemplate redisTemplate;
  45. private static final String SZ_ACCESS_TOKEN_KEY = "sz_wechat_access_token";
  46. private static final String SC_ACCESS_TOKEN_KEY = "sc_wechat_access_token";
  47. /**
  48. * 缓存1个半小时(90分钟)
  49. */
  50. private static final long EXPIRATION_TIME = 90 * 60;
  51. @Override
  52. public void sendNoworkMessage(String openId, String clientId, String name, String ifForeign, String companyType) {
  53. // 模板参数
  54. Map<String, WeChatTemplateMsg> sendMag = new HashMap();
  55. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  56. String alarmTime = format.format(new Date());
  57. if(name.length() > 20) {
  58. name = name.substring(0, 16) + "...";
  59. }
  60. if (StringUtils.isEmpty(ifForeign) || ifForeign.equals("0")) {
  61. // 国内
  62. sendMag.put("thing11", new WeChatTemplateMsg(name));
  63. sendMag.put("character_string14", new WeChatTemplateMsg(clientId.substring(clientId.length()-6)));
  64. sendMag.put("thing4", new WeChatTemplateMsg("严重"));
  65. sendMag.put("time5", new WeChatTemplateMsg(alarmTime));
  66. sendMag.put("thing6", new WeChatTemplateMsg("机器可能出现断网或突然断电,请及时处理!"));
  67. } else {
  68. // 国外
  69. sendMag.put("thing11", new WeChatTemplateMsg(name));
  70. sendMag.put("character_string14", new WeChatTemplateMsg(clientId.substring(clientId.length()-6)));
  71. sendMag.put("thing4", new WeChatTemplateMsg("Serious"));
  72. sendMag.put("time5", new WeChatTemplateMsg(alarmTime));
  73. sendMag.put("thing6", new WeChatTemplateMsg("Power/Network loss."));
  74. }
  75. sendWechatMessage(openId, sendMag, companyType);
  76. }
  77. @Override
  78. public void sendAlarmMessage(String openId, String clientId, String name, String companyType, String alarmContent, Date occurrenceTime) {
  79. // 模板参数
  80. Map<String, WeChatTemplateMsg> sendMag = new HashMap();
  81. // 转换时间为String类型
  82. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  83. String alarmTime = format.format(occurrenceTime);
  84. // 模版参数
  85. if(name.length() > 20) {
  86. sendMag.put("thing11", new WeChatTemplateMsg(name.substring(0, 16) + "..."));
  87. } else {
  88. sendMag.put("thing11", new WeChatTemplateMsg(name));
  89. }
  90. sendMag.put("character_string14", new WeChatTemplateMsg(clientId.substring(clientId.length()-6)));
  91. sendMag.put("thing4", new WeChatTemplateMsg("高"));
  92. sendMag.put("time5", new WeChatTemplateMsg(alarmTime));
  93. sendMag.put("thing6", new WeChatTemplateMsg(alarmContent));
  94. sendWechatMessage(openId, sendMag, companyType);
  95. }
  96. @Override
  97. public String getAccessToken(String companyType) {
  98. String url= "";
  99. String accessToken = "";
  100. if(StringUtils.isEmpty(companyType) || companyType.equals("0")) {
  101. url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
  102. + ConfigConsts.SZ_WX_SUB_APP_ID + "&secret=" + ConfigConsts.SZ_WX_APP_SECRET;
  103. TAdmin admin = adminService.getById(2738L);
  104. admin.setApiKey(accessToken);
  105. adminService.updateById(admin);
  106. } else {
  107. url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
  108. + ConfigConsts.SC_WX_SUB_APP_ID + "&secret=" + ConfigConsts.SC_WX_APP_SECRET;
  109. TAdmin admin = adminService.getById(2739L);
  110. admin.setApiKey(accessToken);
  111. adminService.updateById(admin);
  112. }
  113. PrintWriter out = null;
  114. BufferedReader in = null;
  115. String line;
  116. StringBuffer stringBuffer = new StringBuffer();
  117. try {
  118. URL realUrl = new URL(url);
  119. // 打开和URL之间的连接
  120. URLConnection conn = realUrl.openConnection();
  121. // 设置通用的请求属性 设置请求格式
  122. //设置返回类型
  123. conn.setRequestProperty("contentType", "text/plain");
  124. //设置请求类型
  125. conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
  126. //设置超时时间
  127. conn.setConnectTimeout(1000);
  128. conn.setReadTimeout(1000);
  129. conn.setDoOutput(true);
  130. conn.connect();
  131. // 获取URLConnection对象对应的输出流
  132. out = new PrintWriter(conn.getOutputStream());
  133. // flush输出流的缓冲
  134. out.flush();
  135. // 定义BufferedReader输入流来读取URL的响应 设置接收格式
  136. in = new BufferedReader(
  137. new InputStreamReader(conn.getInputStream(), "UTF-8"));
  138. while ((line = in.readLine()) != null) {
  139. stringBuffer.append(line);
  140. }
  141. JSONObject jsonObject = JSONObject.parseObject(stringBuffer.toString());
  142. log.info("获取token:{}",jsonObject.toString());
  143. accessToken = jsonObject.getString("access_token");
  144. if(StringUtils.isEmpty(companyType) || companyType.equals("0")) {
  145. TAdmin admin = adminService.getById(2738L);
  146. admin.setApiKey(accessToken);
  147. adminService.updateById(admin);
  148. } else {
  149. TAdmin admin = adminService.getById(2739L);
  150. admin.setApiKey(accessToken);
  151. adminService.updateById(admin);
  152. }
  153. } catch (Exception e) {
  154. e.printStackTrace();
  155. } finally {
  156. //使用finally块来关闭输出流、输入流
  157. try {
  158. if (out != null) {
  159. out.close();
  160. }
  161. if (in != null) {
  162. in.close();
  163. }
  164. } catch (IOException ex) {
  165. ex.printStackTrace();
  166. }
  167. }
  168. return accessToken;
  169. }
  170. /**
  171. * 获取accessToken推送消息
  172. * @param openId
  173. * @param sendMag
  174. * @param companyType
  175. * @return
  176. */
  177. public void sendWechatMessage(String openId, Map<String, WeChatTemplateMsg> sendMag, String companyType) {
  178. String url = "";
  179. String accessToken = "";
  180. try {
  181. if(StringUtils.isEmpty(companyType) || companyType.equals("0")) {
  182. TAdmin admin = adminService.getById(2738L);
  183. accessToken = admin.getApiKey();
  184. } else {
  185. TAdmin admin = adminService.getById(2739L);
  186. accessToken = admin.getApiKey();
  187. }
  188. } catch (Exception e) {
  189. e.printStackTrace();
  190. }
  191. if(StringUtils.isEmpty(accessToken)) {
  192. accessToken = getAccessToken(companyType);
  193. }
  194. // 推送消息
  195. RestTemplate restTemplate = new RestTemplate();
  196. Map<String, Object> sendBody = new HashMap<>();
  197. sendBody.put("touser", openId);
  198. sendBody.put("topcolor", "#FF0000");
  199. sendBody.put("data", sendMag);
  200. if(StringUtils.isEmpty(companyType) || companyType.equals("0")) {
  201. sendBody.put("template_id", ConfigConsts.SZ_TEMPLATE_ID);
  202. sendBody.put("url", "http://szwlh.sunzee.com.cn/shenze/");
  203. } else {
  204. sendBody.put("template_id", ConfigConsts.SC_TEMPLATE_ID);
  205. sendBody.put("url", "http://sevencloud.com.cn/sc/");
  206. }
  207. String sendUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
  208. ResponseEntity<String> forEntity = restTemplate.postForEntity(sendUrl, sendBody, String.class);
  209. JSONObject jsonObject = JSONObject.parseObject(forEntity.getBody());
  210. String messageCode = jsonObject.getString("errcode");
  211. String msgId = jsonObject.getString("msgid");
  212. System.out.println("messageCode : " + messageCode + ", msgId: " +msgId);
  213. log.info("微信推送结果:{}","messageCode : " + messageCode + ", msgId: " +msgId);
  214. }
  215. }