liujie
2025-04-29 40bfb646d1b962d33841c1ebbceb0dd7cb668bfb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.panzhihua.sangeshenbian.utils;
 
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
 
import java.util.Map;
 
@Component
@Slf4j
public class WechatMsgUtil {
 
    private String appId;
    
    private String appSecret;
 
    // 获取access_token
    private String getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret;
        String result = HttpUtil.get(url);
        return JSONObject.parseObject(result).getString("access_token");
    }
 
    // 发送模板消息
    public void sendTemplateMsg(String openId, String templateId, 
                               Map<String, String> content) {
        try {
            String accessToken = getAccessToken();
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessToken;
            
            JSONObject json = new JSONObject();
            json.put("touser", openId);
            json.put("template_id", templateId);
            
            JSONObject data = new JSONObject();
            content.forEach((key, value) -> {
                JSONObject item = new JSONObject();
                item.put("value", value);
                data.put(key, item);
            });
            json.put("data", data);
            
            String result = HttpUtil.post(url, json.toJSONString());
            log.info("微信消息发送结果:{}", result);
        } catch (Exception e) {
            log.error("微信消息发送失败", e);
        }
    }
}