当前位置:   article > 正文

Java SpringBoot集成微信告警推送服务_springboot+定时任务+微信告警

springboot+定时任务+微信告警

一.申请微信告警模板

登录微信公众号平台,在服务里面找到模板消息

 我们点击从模板库中添加一个模板消息

 可以通过关键字搜索告警模板,点击详情可以查看该模板的详情与示例,判断该模板是否试用与我们。

 最后找到合适的模板点击添加即可完成模板消息的创建。

二.封装微信推送方法

微信推送中用到了两个微信方法

其一:获取access_token,请求方式未get,接口地址:

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=你的appid&secret=你的secret

其二:推送模板消息接口,请求方式未post,接口地址:

https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=接口1得到的token值
  1. /**
  2. * 微信推送方法封装
  3. * @author HyoJung
  4. * @date 20210714
  5. */
  6. @Slf4j
  7. public class WeChatUtil {
  8. static HttpClient httpClient=new HttpClient();
  9. static String accessToken="";
  10. /**
  11. * 获取Token
  12. * @return
  13. * @throws Exception
  14. */
  15. public static WeChatToken getWeChatToken() throws Exception {
  16. String strUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"
  17. , WeChatConstants.WECHAT_SUBSCRIPTION_APP_ID, WeChatConstants.WECHAT_SUBSCRIPTION_APP_SECRET);
  18. String strToken=httpClient.doGet(strUrl);
  19. WeChatToken token = JSON.parseObject(strToken,WeChatToken.class);
  20. accessToken =token.getAccess_token();
  21. return token;
  22. }
  23. /**
  24. * 推送微信消息封装
  25. * @param para 推送参数
  26. * @return
  27. * @throws Exception
  28. */
  29. public static WeChatResult sendWeChatMessage(WeChatSendParam para) throws Exception {
  30. if(accessToken.length()==0){
  31. getWeChatToken();
  32. }
  33. String strUrl = String.format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s", accessToken);
  34. Map<String,Object> map=new HashMap<>();
  35. map.put("touser", para.getTouser());
  36. map.put("template_id", para.getTemplate_id());
  37. map.put("url", para.getUrl());
  38. map.put("topcolor", para.getTopcolor());
  39. map.put("data", para.getData());
  40. String result=httpClient.doPost(strUrl,JSON.toJSONString(map));
  41. if(result!=null&&result.length()>0){
  42. WeChatResult weChatResult=JSON.parseObject(result,WeChatResult.class);
  43. return weChatResult;
  44. }else {
  45. return null;
  46. }
  47. }
  48. /**
  49. * 模板报警消息推送
  50. * @param touser 被推送人关注公众号后的标识
  51. * @param alarm 报警内容实体
  52. * @return
  53. */
  54. public static WeChatResult sendWeChatAlarmMessage(String touser, MessageAlarm alarm) {
  55. try {
  56. //报警标题
  57. WeChatParaData first = new WeChatParaData();
  58. first.setValue(String.format("%s[%s]", alarm.getAlarmType(), alarm.getVehicleName()));
  59. first.setColor("#FF0000");
  60. //告警内容
  61. WeChatParaData content = new WeChatParaData();
  62. content.setValue(alarm.getAlarmContent());
  63. content.setColor("#173177");
  64. //告警时间
  65. WeChatParaData occurtime = new WeChatParaData();
  66. occurtime.setValue(alarm.getDateTime());
  67. occurtime.setColor("#173177");
  68. //备注
  69. WeChatParaData remark = new WeChatParaData();
  70. remark.setValue(alarm.getRemark());
  71. remark.setColor("#173177");
  72. Map<String, WeChatParaData> data = new HashMap<>();
  73. data.put("first", first);
  74. data.put("content", content);
  75. data.put("occurtime", occurtime);
  76. data.put("remark", remark);
  77. WeChatSendParam model = new WeChatSendParam();
  78. model.setTouser(touser);
  79. model.setTemplate_id(WeChatConstants.WECHAT_SUBSCRIPTION_ALARM_TEMPLATE_ID);
  80. model.setUrl("");
  81. model.setTopcolor("#FF0000");
  82. model.setData(data);
  83. WeChatResult weChatResult = WeChatUtil.sendWeChatMessage(model);
  84. if (weChatResult.getErrcode() == WeChatResultCode.access_token_expire.getValue() || weChatResult.getErrcode() == WeChatResultCode.access_token_overtime.getValue()) {
  85. WeChatUtil.getWeChatToken();
  86. weChatResult = WeChatUtil.sendWeChatMessage(model);
  87. }
  88. return weChatResult;
  89. }catch (Exception e) {
  90. log.error(e.getMessage());
  91. return null;
  92. }
  93. }
  94. }

里面有用到一些微信推送的常量,定义在了WeChatConstants

  1. /**
  2. * 微信服务接口常量
  3. * @author lenny
  4. */
  5. public class WeChatConstants {
  6. private WeChatConstants() {
  7. }
  8. /**
  9. * 微信推送AppID
  10. */
  11. public static final String WECHAT_SUBSCRIPTION_APP_ID = "xxxxxxxx";
  12. /**
  13. * 微信推送密钥
  14. */
  15. public static final String WECHAT_SUBSCRIPTION_APP_SECRET = "xxxxxxxxxxxxx";
  16. /**
  17. * 微信推送报警信息模板
  18. */
  19. public static final String WECHAT_SUBSCRIPTION_ALARM_TEMPLATE_ID = "xxxxxxxxxxxxx";
  20. /**
  21. * 微信推送报警备注(中文)
  22. */
  23. public static final String WECHAT_SUBSCRIPTION_ALARM_CN_REMARK="请尽快处理!";
  24. /**
  25. * 微信推送报警备注(英文)
  26. */
  27. public static final String WECHAT_SUBSCRIPTION_ALARM_EN_REMARK="please handle it ASAP!";
  28. }

微信推送结果实体类

  1. /**
  2. * 微信推送结果实体类
  3. * @author Mr.lee
  4. * @date 20210710
  5. */
  6. @Data
  7. public class WeChatResult {
  8. private int errcode;
  9. private String errmsg;
  10. }

微信Token实体类

  1. /**
  2. * 微信Token实体类
  3. * @author Mr.lee
  4. * @date 20210710
  5. */
  6. @Data
  7. public class WeChatToken {
  8. private String access_token;
  9. private String expires_in;
  10. }

微信推送参数实体类:

  1. /**
  2. * 微信推送参数实体
  3. * @author Mr.Lee
  4. * @date 20210710
  5. */
  6. @Data
  7. public class WeChatSendParam {
  8. private String touser;
  9. private String template_id;
  10. private String url;
  11. private String topcolor;
  12. private Map<String,WeChatParaData> data;
  13. }

微信推送内容参数:

  1. /**
  2. * 微信推送内容参数
  3. * @author Mr.Lee
  4. * @date 20210710
  5. */
  6. @Data
  7. public class WeChatParaData {
  8. private String value;
  9. private String color;
  10. }

入参报警实体类

  1. /**
  2. * 报警入参
  3. * @author Mr.Lee
  4. * @date 20230331
  5. */
  6. @Data
  7. public class MessageAlarm {
  8. private String vehicleName;
  9. private String assetID;
  10. private String dateTime;
  11. private String lon;
  12. private String lat;
  13. private String alarmType;
  14. private String alarmContent;
  15. private String remark;
  16. }

因为微信接口采用的是Api的方式进行调用的,所以这里贴出了我封装的HttpClient

  1. /**
  2. * http请求封装类
  3. * @author lenny
  4. * @date 20210710
  5. */
  6. public class HttpClient {
  7. public HttpClient(){
  8. }
  9. private CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  10. @Autowired
  11. private RequestConfig config;
  12. /**
  13. * 不带参数的get请求,如果状态码为200,则返回body,如果不为200,则返回null
  14. *
  15. * @param url
  16. * @return
  17. * @throws Exception
  18. */
  19. public String doGet(String url) {
  20. try {
  21. // 声明 http get 请求
  22. HttpGet httpGet = new HttpGet(url);
  23. // 装载配置信息
  24. httpGet.setConfig(config);
  25. // 发起请求
  26. CloseableHttpResponse response = this.httpClient.execute(httpGet);
  27. if(response!=null) {
  28. return EntityUtils.toString(response.getEntity(), "UTF-8");
  29. }else {
  30. return null;
  31. }
  32. }catch (Exception e) {
  33. return null;
  34. }
  35. }
  36. /**
  37. * 带参数的get请求,如果状态码为200,则返回body,如果不为200,则返回null
  38. *
  39. * @param url
  40. * @return
  41. * @throws Exception
  42. */
  43. public String doGet(String url, Map<String, Object> map) throws Exception {
  44. URIBuilder uriBuilder = new URIBuilder(url);
  45. if (map != null) {
  46. // 遍历map,拼接请求参数
  47. for (Map.Entry<String, Object> entry : map.entrySet()) {
  48. uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
  49. }
  50. }
  51. // 调用不带参数的get请求
  52. return this.doGet(uriBuilder.build().toString());
  53. }
  54. /**
  55. * 不带参数post请求
  56. *
  57. * @param url
  58. * @return
  59. * @throws Exception
  60. */
  61. public String doPost(String url) throws Exception {
  62. return this.doPost(url, "");
  63. }
  64. /**
  65. * 带Json参数的Post请求
  66. * @param url
  67. * @param jsonParam
  68. * @return
  69. * @throws Exception
  70. */
  71. public String doPost(String url, String jsonParam) throws Exception{
  72. String result = "";
  73. // 声明httpPost请求
  74. HttpPost httpPost = new HttpPost(url);
  75. // 加入配置信息
  76. httpPost.setConfig(config);
  77. httpPost.setHeader("Content-Type", "application/json");
  78. if(jsonParam.length()>0){
  79. httpPost.setEntity(new StringEntity(jsonParam, ContentType.create("application/json", "utf-8")));
  80. HttpResponse response = httpClient.execute(httpPost);
  81. if (response != null && response.getStatusLine().getStatusCode() == 200) {
  82. result = EntityUtils.toString(response.getEntity());
  83. }
  84. }
  85. return result;
  86. }
  87. }
微信返回结果码: WeChatResultCode
  1. /**
  2. * 微信返回状态值
  3. * @author Mr.Li
  4. * @date 2023-09-06
  5. */
  6. @Getter
  7. public enum WeChatResultCode {
  8. system_busy(-1,"系统繁忙"),
  9. succeed(0,"请求成功"),
  10. fail(40001,"验证失败"),
  11. illegal_voucher_type(40002,"不合法的凭证类型"),
  12. illegal_openid(40003,"不合法的OpenID"),
  13. illegal_media_file_type(40004,"不合法的媒体文件类型"),
  14. illegal_file_type(40005,"不合法的文件类型"),
  15. illegal_file_size(40006,"不合法的文件大小"),
  16. illegal_media_file_id(40007,"不合法的媒体文件id"),
  17. illegal_message_type(40008,"不合法的消息类型"),
  18. illegal_image_file_size(40009,"不合法的图片文件大小"),
  19. illegal_audio_file_size(40010,"不合法的音频文件大小"),
  20. illegal_video_file_size(40011,"不合法的视频文件大小"),
  21. illegal_thumbnail_file_size(40012,"不合法的缩略图文件大小"),
  22. illegal_app_id(40013,"不合法的APPID"),
  23. missing_access_token(41001,"缺少access_token参数"),
  24. missing_app_id(41002,"缺少appid参数"),
  25. missing_refresh_token(41003,"缺少refresh_token参数"),
  26. missing_secret(41004,"缺少secret参数"),
  27. missing_media_file(41005,"缺少多媒体文件数据"),
  28. access_token_overtime(41006,"access_token超时"),
  29. access_token_expire(42001,"access_token过期"),
  30. need_POST(43002,"需要POST请求"),
  31. need_HTTPS(43003,"需要HTTPS请求"),
  32. media_file_null(44001,"多媒体文件为空"),
  33. post_data_null(44002,"POST的数据包为空"),
  34. text_data_null(44003,"图文消息内容为空"),
  35. media_file_size_exceeds_limit(45001,"多媒体文件大小超过限制"),
  36. message_exceeds_limit(45002,"消息内容超过限制"),
  37. title_exceeds_limit(45003,"标题字段超过限制"),
  38. description_exceeds_limit(45004,"描述字段超过限制"),
  39. link_exceeds_limit(45005,"链接字段超过限制"),
  40. image_link_exceeds_limit(45006,"图片链接字段超过限制"),
  41. audio_playback_time_exceeds_limit(45007,"音频播放时间超过限制"),
  42. text_message_exceeds_limit(45008,"图文消息超过限制"),
  43. interface_call_exceeds_limit(45009,"接口调用超过限制"),
  44. media_data_not_existent(46001,"不存在媒体数据"),
  45. parsing_JSON_error(47001,"解析JSON内容错误"),
  46. unknow(-2, "未知异常");
  47. private final int value;
  48. private final String desc;
  49. WeChatResultCode(int value, String desc) {
  50. this.value = value;
  51. this.desc = desc;
  52. }
  53. public static WeChatResultCode fromValue(int result) {
  54. for (WeChatResultCode mediaEventEnum : values()) {
  55. if (result == mediaEventEnum.getValue()) {
  56. return mediaEventEnum;
  57. }
  58. }
  59. return unknow;
  60. }
  61. }

HttpClient需要以下pom

  1. <dependency>
  2. <groupId>org.apache.httpcomponents</groupId>
  3. <artifactId>httpclient</artifactId>
  4. <version>4.3.1</version>
  5. </dependency>
  6. <!-- httpClient文件上传需要 -->
  7. <dependency>
  8. <groupId>org.apache.httpcomponents</groupId>
  9. <artifactId>httpmime</artifactId>
  10. </dependency>

三.其他说明

模板推送一个简单的微信服务号,用户需要关注此服务号才能实现推送模板消息的目的,并且推送方法中touser参数可以在用户关注微信服务号的时候通过前端传给后台并保存在数据库中。

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

闽ICP备14008679号