1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- package com.huimv.env.common.config;
- import cn.hutool.http.HttpUtil;
- import cn.hutool.json.JSONObject;
- import cn.hutool.json.JSONUtil;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.stereotype.Component;
- import java.util.Date;
- import java.util.HashMap;
- @Component
- public class WeChatMessage {
- // wx:
- // appId: "wx707fcfd7d09e02eb" #小程序appId
- // secret: "w95K45G9-2xGocleqrtGoHwEGF6ocqSu8EbDBxCQSR0" #小程序密钥
- // templateId: "f932c54f1cbd427b10218a0d1cfb88bf" #订阅消息模板
- //
- // @Value("${wx.appId}")
- // private String appId;
- //
- // @Value("${wx.secret}")
- // private String secret;
- //
- // @Value("${wx.templateId}")
- // private String templateId;
- private static final String appId= "wx707fcfd7d09e02eb";
- private static final String secret= "w95K45G9-2xGocleqrtGoHwEGF6ocqSu8EbDBxCQSR0";
- private static final String templateId= "f932c54f1cbd427b10218a0d1cfb88bf";
- public void sendMsg(String deviceCode,String warningContent, Date uploadDate,String location,String openId){
- //1:获取token(接口调用凭证)
- String token = queryToken();
- //2:发送订阅消息
- send(token,warningContent,deviceCode,uploadDate,location,openId);
- }
- // 1: 获取 access_token (2h过期)
- public String queryToken(){
- String tokenUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
- tokenUrl = tokenUrl + "&appid=" + appId + "&secret=" + secret;
- String result = HttpUtil.get(tokenUrl);
- JSONObject jsonObject = JSONUtil.parseObj(result);
- String token = jsonObject.get("access_token").toString();
- return token;
- }
- public void send(String token,String warningContent,String deviceCode, Date uploadDate,String location,String openId){
- String msgUrl="https://api.weixin.qq.com/cgi-bin/message/subscribe/send";
- msgUrl = msgUrl + "?access_token=" + token;
- // 设置模板参数
- HashMap<String, Object> paramMap = new HashMap<>();
- paramMap.put("touser", openId); // 接收方
- paramMap.put("template_id", templateId); // 模板id
- paramMap.put("page","pages/self/self"); // 消息中要跳转的页面
- // 设置data 模板内容
- HashMap<String, Object> data = new HashMap<>();
- //报警设备
- data.put("thing1", formatParam(deviceCode));
- //报警类型
- data.put("thing2", formatParam(warningContent));
- //报警时间
- data.put("thing3", formatParam(uploadDate.toString()));
- //报警地点
- data.put("thing5", formatParam(location));
- paramMap.put("data", data);
- // 转json字符串
- String jsonObject = JSONUtil.toJsonStr(paramMap);
- String result= HttpUtil.post(msgUrl, jsonObject);
- System.out.println(result);
- }
- public HashMap<String, Object> formatParam(String value){
- HashMap<String, Object> data = new HashMap<>();
- data.put("value", value);
- return data;
- }
- }
|