BAOLH
2026-09-18 1d9899d1ff04c17d7c566ea0e7b20d7ebea660ec
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
package me.zhengjie.modules.temp.service.impl;
 
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.temp.service.WechatRobotService;
import me.zhengjie.utils.StringUtils;
import me.zhengjie.utils.weixin.AesException;
import me.zhengjie.utils.weixin.WXBizJsonMsgCrypt;
import org.springframework.stereotype.Service;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
 
@Service
@RequiredArgsConstructor
public class WechatRobotServiceImpl implements WechatRobotService {
 
    private final String CORP_ID = "";
    private final String TOKEN = "WTAgLRQif";
    private final String ENCODING_AES_KEY = "w2FEuoDg2D7DxnmJn4DL6YiD47OSHwB34WXVwa2eriY";
    private final String APPROVAL_AGENT_ID = "1000005";
    private final String ROBOT_ID = "aiboW1Wpr5Mg_9WNlzyBtIjtf-ETL6pTEFd";
 
    private final String TEXT_MSG_TEMPLATE = "{\"msgtype\": \"text\",\"text\": {\"content\": \"%s\"}}";
 
    private final String STREAM_MSG_TEMPLATE = "{\"msgtype\": \"stream\",\"stream\": {\"id\": \"%s\", \"finish\": \"%s\", \"content\": \"%s\"}}";
 
    @Override
    public void robotBack(String msgSignature, String timestamp, String nonce, String echostr, HttpServletResponse response) {
        try {
            WXBizJsonMsgCrypt wxcpt = new WXBizJsonMsgCrypt(TOKEN, ENCODING_AES_KEY, CORP_ID);
            // 设置响应内容类型为纯文本
            response.setContentType("text/plain; charset=UTF-8");
            // 获取PrintWriter对象
            PrintWriter out = response.getWriter();
            // 直接返回
            String message = wxcpt.VerifyURL(msgSignature, timestamp, nonce, echostr);
            out.print(message);
            // 刷新并关闭PrintWriter
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    @Override
    public Object handleRobotCallback(String msgSignature, String timestamp, String nonce, HttpServletRequest request, HttpServletResponse response) {
        WXBizJsonMsgCrypt wxcpt = null;
        try {
            wxcpt = new WXBizJsonMsgCrypt(TOKEN, ENCODING_AES_KEY, CORP_ID);
            // 读取回调数据
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
 
            String callbackData = sb.toString();
 
            JSONObject jsonObject = JSONObject.parseObject(callbackData);
            String decryptedMessage = wxcpt.DecryptRobotMsg(msgSignature, timestamp, nonce, jsonObject.toString());
            System.out.println("接收到机器人发送的加密消息:" + jsonObject.toJSONString());
            System.out.println("接收到机器人发送的解密后消息:" + decryptedMessage);
            JSONObject decryptedMessageJson =  JSONObject.parseObject(decryptedMessage);
            if (decryptedMessageJson.containsKey("response_url") && StringUtils.isNotBlank(decryptedMessageJson.getString("response_url"))) {
                String responseUrl = decryptedMessageJson.getString("response_url");
                if (decryptedMessageJson.getString("msgtype").equals("text")) {
                    String textContent = decryptedMessageJson.getJSONObject("text").getString("content");
                    if (textContent.contains("流式消息")) {
                        // 流式消息
                        StringBuilder streamContentBuilder = new StringBuilder();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
                        String streamId = decryptedMessageJson.getString("msgid") + "_" + sdf.format(new Date());
                        for (int i = 0; i < 10; i++) {
                            streamContentBuilder.append(i);
                            String replyPlainText = String.format(STREAM_MSG_TEMPLATE, streamId, i + 1 >= 10, streamContentBuilder.toString());
                            String responseStr = HttpUtil.post(responseUrl, replyPlainText);
                            System.out.println("接收到回复消息的响应:" + responseStr);
                        }
                    } else {
                        // 普通消息
                        String replyPlainText = String.format(TEXT_MSG_TEMPLATE, "消息已收到");
                        String responseStr = HttpUtil.post(responseUrl, replyPlainText);
                        System.out.println("接收到回复消息的响应:" + responseStr);
                    }
                } else {
                    // 不支持的消息
                    String replyPlainText = String.format(TEXT_MSG_TEMPLATE, "不支持的消息类型:抱歉当前仅支持文字信息");
                    String responseStr = HttpUtil.post(responseUrl, replyPlainText);
                    System.out.println("接收到回复消息的响应:" + responseStr);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                if (wxcpt != null) {
                    return wxcpt.EncryptRobotMsg("消息接收出现异常,请联系管理员处理 o(╥﹏╥o...)", "", nonce);
                }
            } catch (AesException aesException) {
                aesException.printStackTrace();
            }
        }
 
        return null;
    }
}