wlzboy
5 天以前 fe33646ee6e2d1e57f2b51812e94983a0e9efb04
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
package com.ruoyi.system.service.impl;
 
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.QyWechatArticle;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.IQyWechatAccessTokenService;
import com.ruoyi.system.service.IQyWechatService;
import com.ruoyi.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * 企业微信服务实现类
 * 
 * @author ruoyi
 * @date 2025-12-11
 */
@Service
public class QyWechatServiceImpl implements IQyWechatService {
 
    private static final Logger log = LoggerFactory.getLogger(QyWechatServiceImpl.class);
 
    @Autowired
    private IQyWechatAccessTokenService qyWechatAccessTokenService;
 
    @Autowired
    private ISysConfigService configService;
 
    @Autowired
    private SysUserMapper userMapper;
 
    /**
     * 发送企业微信消息
     */
    @Override
    public boolean sendNotifyMessage(Long userId, String title, String content,String notifyUrl) {
        try {
            // 检查服务是否启用
            if (!isEnabled()) {
                log.info("企业微信服务未启用,跳过消息发送");
                return false;
            }
 
            // 获取用户的企业微信ID
            String qyUserId = getQyUserIdByUserId(userId);
            if (StringUtils.isEmpty(qyUserId)) {
                log.warn("用户{}未绑定企业微信ID,无法发送消息", userId);
                return false;
            }
 
            // 发送文本消息
            return sendTextMessage(qyUserId, title, content, notifyUrl);
        } catch (Exception e) {
            log.error("企业微信消息发送异常,userId={}", userId, e);
            return false;
        }
    }
 
    /**
     * 发送企业微信文本消息
     */
    @Override
    public boolean sendTextMessage(String qyUserId, String title, String content, String notifyUrl) {
        try {
            // 检查服务是否启用
            if (!isEnabled()) {
                log.info("企业微信服务未启用,跳过消息发送");
                return false;
            }
 
            // 获取企业微信配置
            String corpId = configService.selectConfigByKey("qy_wechat.corp_id");
            String corpSecret = configService.selectConfigByKey("qy_wechat.corp_secret");
 
            if (StringUtils.isEmpty(corpId) || StringUtils.isEmpty(corpSecret)) {
                log.error("企业微信配置不完整,缺少corpId或corpSecret");
                return false;
            }
 
            // 获取AccessToken
            String accessToken = qyWechatAccessTokenService.getAppAccessToken(corpId, corpSecret);
            if (StringUtils.isEmpty(accessToken)) {
                log.error("获取企业微信AccessToken失败");
                return false;
            }
 
            // 构造请求URL
            String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;
 
            // 构造文章对象
            QyWechatArticle article = new QyWechatArticle();
            article.setTitle(title);
            article.setDescription(content);
            article.setUrl(notifyUrl);
            // 设置默认图片URL,您可以根据需要修改
            
 
            // 构造请求参数
            Map<String, Object> params = new HashMap<>();
            params.put("touser", qyUserId);
            params.put("msgtype", "news");
            params.put("agentid", Integer.parseInt(configService.selectConfigByKey("qy_wechat.agent_id")));
            
            // 构造文章列表
            List<QyWechatArticle> articles = new ArrayList<>();
            articles.add(article);
            params.put("news", Collections.singletonMap("articles", articles));
 
            // 发送HTTP POST请求
            String response = sendHttpPostRequest(url, params);
 
            if (StringUtils.isEmpty(response)) {
                log.error("发送企业微信消息失败,响应为空");
                return false;
            }
 
            // 解析响应结果
            QyWechatResponse result = parseResponse(response);
 
            if (result != null && result.getErrcode() == 0) {
                log.info("企业微信消息发送成功,用户ID: {}", qyUserId);
                return true;
            } else {
                log.error("企业微信消息发送失败,错误码: {}, 错误信息: {}",
                        result != null ? result.getErrcode() : "unknown",
                        result != null ? result.getErrmsg() : response);
                return false;
            }
        } catch (Exception e) {
            log.error("企业微信文本消息发送异常,qyUserId={}", qyUserId, e);
            return false;
        }
    }
 
    /**
     * 获取用户的企业微信ID
     */
    @Override
    public String getQyUserIdByUserId(Long userId) {
        try {
            if (userId == null) {
                log.warn("用户ID不能为空");
                return null;
            }
 
            // 查询用户信息
            SysUser user = userMapper.selectUserById(userId);
            if (user == null) {
                log.warn("未找到用户,userId={}", userId);
                return null;
            }
 
            // 返回企业微信用户ID
            return user.getQyWechatUserId();
        } catch (Exception e) {
            log.error("获取用户企业微信ID异常,userId={}", userId, e);
            return null;
        }
    }
 
    /**
     * 检查企业微信服务是否启用
     */
    @Override
    public boolean isEnabled() {
        try {
            String enabled = configService.selectConfigByKey("qy_wechat.enable");
            return "true".equals(enabled);
        } catch (Exception e) {
            log.warn("获取企业微信服务启用状态失败,使用默认值(false)", e);
            return false;
        }
    }
 
    /**
     * 发送HTTP POST请求
     *
     * @param url    请求URL
     * @param params 请求参数
     * @return 响应内容
     */
    private String sendHttpPostRequest(String url, Map<String, Object> params) {
        try {
            // 将参数转换为JSON字符串
            String jsonParams = toJsonString(params);
 
            java.net.HttpURLConnection conn = (java.net.HttpURLConnection) new java.net.URL(url).openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setDoOutput(true);
 
            // 发送请求数据
            java.io.OutputStream os = conn.getOutputStream();
            os.write(jsonParams.getBytes("UTF-8"));
            os.flush();
            os.close();
 
            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                java.io.BufferedReader reader = new java.io.BufferedReader(
                        new java.io.InputStreamReader(conn.getInputStream(), "UTF-8"));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                return response.toString();
            } else {
                log.error("HTTP请求失败,响应码: {}", responseCode);
                return null;
            }
        } catch (Exception e) {
            log.error("发送HTTP POST请求失败", e);
            return null;
        }
    }
 
    /**
     * 简单的JSON序列化方法
     *
     * @param map 要序列化的Map
     * @return JSON字符串
     */
    private String toJsonString(Map<String, Object> map) {
        StringBuilder json = new StringBuilder("{");
        boolean first = true;
 
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (!first) {
                json.append(",");
            }
 
            json.append("\"").append(entry.getKey()).append("\":");
 
            Object value = entry.getValue();
            if (value instanceof String) {
                json.append("\"").append(value).append("\"");
            } else if (value instanceof Map) {
                // 处理嵌套Map
                json.append(toJsonString((Map<String, Object>) value));
            } else if (value instanceof List) {
                // 处理列表
                json.append(toJsonList((List<Object>) value));
            } else {
                json.append(value);
            }
 
            first = false;
        }
 
        json.append("}");
        return json.toString();
    }
 
    /**
     * 序列化列表为JSON
     *
     * @param list 列表
     * @return JSON字符串
     */
    private String toJsonList(List<Object> list) {
        StringBuilder json = new StringBuilder("[");
        boolean first = true;
 
        for (Object item : list) {
            if (!first) {
                json.append(",");
            }
 
            if (item instanceof String) {
                json.append("\"").append(item).append("\"");
            } else if (item instanceof Map) {
                json.append(toJsonString((Map<String, Object>) item));
            } else if (item instanceof QyWechatArticle) {
                json.append(toJsonArticle((QyWechatArticle) item));
            } else {
                json.append(item);
            }
 
            first = false;
        }
 
        json.append("]");
        return json.toString();
    }
 
    /**
     * 序列化文章对象为JSON
     *
     * @param article 文章对象
     * @return JSON字符串
     */
    private String toJsonArticle(QyWechatArticle article) {
        StringBuilder json = new StringBuilder("{");
        boolean first = true;
 
        // 添加非空字段
        if (article.getTitle() != null) {
            if (!first) json.append(",");
            json.append("\"title\":\"").append(escapeJsonString(article.getTitle())).append("\"");
            first = false;
        }
        if (article.getDescription() != null) {
            if (!first) json.append(",");
            json.append("\"description\":\"").append(escapeJsonString(article.getDescription())).append("\"");
            first = false;
        }
        if (article.getUrl() != null) {
            if (!first) json.append(",");
            json.append("\"url\":\"").append(escapeJsonString(article.getUrl())).append("\"");
            first = false;
        }
        if (article.getPicurl() != null) {
            if (!first) json.append(",");
            json.append("\"picurl\":\"").append(escapeJsonString(article.getPicurl())).append("\"");
            first = false;
        }
        if (article.getAppid() != null) {
            if (!first) json.append(",");
            json.append("\"appid\":\"").append(escapeJsonString(article.getAppid())).append("\"");
            first = false;
        }
        if (article.getPagepath() != null) {
            if (!first) json.append(",");
            json.append("\"pagepath\":\"").append(escapeJsonString(article.getPagepath())).append("\"");
            first = false;
        }
 
        json.append("}");
        return json.toString();
    }
 
    /**
     * 转义JSON字符串中的特殊字符
     *
     * @param str 原始字符串
     * @return 转义后的字符串
     */
    private String escapeJsonString(String str) {
        if (str == null) return "";
        return str.replace("\\", "\\\\")
                 .replace("\"", "\\\"")
                 .replace("\n", "\\n")
                 .replace("\r", "\\r")
                 .replace("\t", "\\t");
    }
 
    /**
     * 解析企业微信响应
     *
     * @param response 响应JSON
     * @return 响应对象
     */
    private QyWechatResponse parseResponse(String response) {
        try {
            // 使用简单JSON解析
            QyWechatResponse result = new QyWechatResponse();
            
            // 移除首尾花括号
            String content = response.trim();
            if (content.startsWith("{")) {
                content = content.substring(1);
            }
            if (content.endsWith("}")) {
                content = content.substring(0, content.length() - 1);
            }
            
            // 按逗号分割键值对
            String[] pairs = content.split(",");
            
            for (String pair : pairs) {
                String[] keyValue = pair.split(":", 2); // 只分割第一个冒号
                if (keyValue.length == 2) {
                    String key = keyValue[0].trim().replaceAll("\"", "");
                    String value = keyValue[1].trim().replaceAll("\"", "");
                    
                    switch (key) {
                        case "errcode":
                            result.setErrcode(Integer.parseInt(value));
                            break;
                        case "errmsg":
                            result.setErrmsg(value);
                            break;
                    }
                }
            }
            
            return result;
        } catch (Exception e) {
            log.error("解析企业微信响应失败: {}", response, e);
            return null;
        }
    }
 
    /**
     * 企业微信响应内部类
     */
    private static class QyWechatResponse {
        private int errcode;
        private String errmsg;
 
        // Getters and Setters
        public int getErrcode() {
            return errcode;
        }
 
        public void setErrcode(int errcode) {
            this.errcode = errcode;
        }
 
        public String getErrmsg() {
            return errmsg;
        }
 
        public void setErrmsg(String errmsg) {
            this.errmsg = errmsg;
        }
    }
}