啊鑫
2025-08-20 a92e3aeb50efc6ef252d0fbaa2d45b4b7a3f5c61
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
package com.gs.xiaomi.service;
 
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gs.xiaomi.config.DataAcquisitionConfiguration;
import com.gs.xiaomi.dto.BCS101Request;
import com.gs.xiaomi.util.X5StringUtils;
import okhttp3.*;
import org.springframework.stereotype.Service;
 
import java.io.IOException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;
 
@Service
public class BCS101ApiService {
 
    private final OkHttpClient client;
    private final ObjectMapper objectMapper;
 
    public BCS101ApiService() {
        this.client = new OkHttpClient.Builder()
                .connectTimeout(3000, TimeUnit.SECONDS)
                .readTimeout(90, TimeUnit.SECONDS)
                .build();
        this.objectMapper = new ObjectMapper();
    }
 
    /**
     * 获取BCS101数据
     *
     * @param request BCS101请求参数
     * @return API响应
     * @throws IOException 网络异常
     *                     <p>
     *                     HTTP访问需要Baisc Auth(该账户为条码集成专用账户,密码切勿输入错误!):
     *                     账户: RFCBCSXIAOBU
     *                     密码: L5X8!pdL
     *                     如何使用:
     *                     使用http 调用时需要根据账户密码增加http headers参数Authorization
     *                     对应的值为Basic bas64(账户:密码)
     *                     <p>
     *                     X5协议中使用的(国密算法)
     *                     对应appid和对应appkey请使用小米条码平台分配的对应的测试机信息:
     *                     APP ID:bcs_fty_177301
     *                     APP Key:IJBVGMJXG4ZTAMLSMFXGI33NONQWY5DG
     *                     <p>
     *                     HTTP HEADER参数:
     *                     Authorization  Basic XXXXX
     *                     同时请添加HTTP HEADER参数:
     *                     Content-Type  application/x-www-form-urlencoded
     *                     body选择raw,
     *                     数据格式为data=url编码(base64编码)的数据
     *                     </p>
     */
    public String getBCS101Data(BCS101Request request) throws IOException {
        // 直接将请求对象转换为JSON字符串
        String jsonData = objectMapper.writeValueAsString(request);
 
        // Base64编码
        String base64Data = X5StringUtils.encodeBase64(jsonData);
 
        // URL编码
        String urlEncodedData = URLEncoder.encode(base64Data, "UTF-8");
 
        // 构建form表单数据 - 按照注释要求:data=url编码(base64编码)的数据
        String formData = "data=" + urlEncodedData;
 
        // 构建Basic Auth - 使用专用条码集成账户
        String credentials = DataAcquisitionConfiguration.BCS_USER_NAME + ":" + DataAcquisitionConfiguration.BCS_PWD;
        String auth = X5StringUtils.encodeBase64(credentials);
 
        // 构建请求体 - Content-Type: application/x-www-form-urlencoded
        RequestBody body = RequestBody.create(formData, MediaType.parse("application/x-www-form-urlencoded"));
 
        // 构建请求 - 严格按照注释要求
        Request httpRequest = new Request.Builder()
                .url(DataAcquisitionConfiguration.BCS_101_URL)
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Authorization", "Basic " + auth)
                .build();
 
        // 执行请求
        try (Response response = client.newCall(httpRequest).execute()) {
            if (response.body() != null) {
                String responseBody = response.body().string();
                // 记录响应信息用于调试
                System.out.println("BCS101 API响应状态: " + response.code());
                System.out.println("BCS101 API响应内容: " + responseBody);
                return responseBody;
            }
            throw new IOException("Empty response body");
        }
    }
 
    /**
     * 获取BCS101数据 - 带X5协议支持
     *
     * @param request  BCS101请求参数
     * @param enableX5 是否启用X5协议国密签名
     * @return API响应
     * @throws IOException 网络异常
     */
    public String getBCS101DataWithX5(BCS101Request request, boolean enableX5) throws IOException {
        // 直接将请求对象转换为JSON字符串
        String jsonData = objectMapper.writeValueAsString(request);
 
        // Base64编码
        String base64Data = X5StringUtils.encodeBase64(jsonData);
 
        // URL编码
        String urlEncodedData = URLEncoder.encode(base64Data, "UTF-8");
 
        // 构建form表单数据
        String formData = "data=" + urlEncodedData;
 
        // 构建Basic Auth
        String credentials = DataAcquisitionConfiguration.BCS_USER_NAME + ":" + DataAcquisitionConfiguration.BCS_PWD;
        String auth = X5StringUtils.encodeBase64(credentials);
 
        // 构建请求体
        RequestBody body = RequestBody.create(formData, MediaType.parse("application/x-www-form-urlencoded"));
 
        Request.Builder requestBuilder = new Request.Builder()
                .url(DataAcquisitionConfiguration.BCS_101_URL)
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Authorization", "Basic " + auth);
 
        // 如果启用X5协议,添加国密签名
        if (enableX5) {
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
            String signature = generateX5Signature(
                    DataAcquisitionConfiguration.BCS_APP_ID,
                    DataAcquisitionConfiguration.BCS_APP_Key,
                    timestamp,
                    formData
            );
            requestBuilder.addHeader("X-App-Id", DataAcquisitionConfiguration.BCS_APP_ID)
                    .addHeader("X-Timestamp", timestamp)
                    .addHeader("X-Signature", signature);
        }
 
        Request httpRequest = requestBuilder.build();
 
        // 执行请求
        try (Response response = client.newCall(httpRequest).execute()) {
            if (response.body() != null) {
                String responseBody = response.body().string();
                System.out.println("BCS101 API响应状态: " + response.code());
                System.out.println("BCS101 API响应内容: " + responseBody);
                return responseBody;
            }
            throw new IOException("Empty response body");
        }
    }
 
    /**
     * 生成X5协议签名 - 使用国密算法
     *
     * @param appId     APP ID
     * @param appKey    APP Key
     * @param timestamp 时间戳
     * @param data      请求数据
     * @return 签名字符串
     */
    private String generateX5Signature(String appId, String appKey, String timestamp, String data) {
        // X5协议国密算法签名: 尝试使用SM3,如果不支持则使用MD5
        String signString = appId + appKey + timestamp + data;
        try {
            // 尝试使用国密SM3算法
            return SmUtil.sm3(signString).toUpperCase();
        } catch (Exception e) {
            // 如果SM3不可用,fallback到MD5
            System.out.println("SM3算法不可用,使用MD5替代: " + e.getMessage());
            return DigestUtil.md5Hex(signString).toUpperCase();
        }
    }
 
    /**
     * 调试版本 - 详细输出请求信息来定位问题
     */
    public String getBCS101DataDebug(BCS101Request request) throws IOException {
        System.out.println("=== BCS101 API 调试信息 ===");
 
        // 直接将请求对象转换为JSON字符串
        String jsonData = objectMapper.writeValueAsString(request);
        System.out.println("1. 原始JSON数据: " + jsonData);
 
        // Base64编码
        String base64Data = X5StringUtils.encodeBase64(jsonData);
        System.out.println("2. Base64编码后: " + base64Data);
 
        // URL编码
        String urlEncodedData = URLEncoder.encode(base64Data, "UTF-8");
        System.out.println("3. URL编码后: " + urlEncodedData);
 
        // 构建form表单数据
        String formData = "data=" + urlEncodedData;
        System.out.println("4. Form数据: " + formData);
 
        // 构建Basic Auth
        String credentials = DataAcquisitionConfiguration.BCS_USER_NAME + ":" + DataAcquisitionConfiguration.BCS_PWD;
        String auth = X5StringUtils.encodeBase64(credentials);
        System.out.println("5. Auth编码: Basic " + auth);
        System.out.println("6. 请求URL: " + DataAcquisitionConfiguration.BCS_101_URL);
 
        // 尝试不同的Content-Type
        RequestBody body = RequestBody.create(formData, MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"));
 
        Request httpRequest = new Request.Builder()
                .url(DataAcquisitionConfiguration.BCS_101_URL)
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
                .addHeader("Authorization", "Basic " + auth)
                .addHeader("Accept", "application/xml, text/xml, */*")
                .addHeader("User-Agent", "BCS101-Client/1.0")
                .addHeader("Connection", "close")
                .build();
 
        System.out.println("7. 发送请求...");
 
        // 执行请求
        try (Response response = client.newCall(httpRequest).execute()) {
            System.out.println("8. 响应状态码: " + response.code());
            System.out.println("9. 响应头: " + response.headers().toString());
 
            if (response.body() != null) {
                String responseBody = response.body().string();
                System.out.println("10. 响应内容: " + responseBody);
                return responseBody;
            }
            throw new IOException("Empty response body");
        }
    }
 
    /**
     * 简化版本 - 尝试直接发送JSON数据
     */
    public String getBCS101DataSimple(BCS101Request request) throws IOException {
        System.out.println("=== BCS101 API 简化版本测试 ===");
 
        // 直接将请求对象转换为JSON字符串
        String jsonData = objectMapper.writeValueAsString(request);
        System.out.println("发送的JSON数据: " + jsonData);
 
        // 构建Basic Auth
        String credentials = DataAcquisitionConfiguration.BCS_USER_NAME + ":" + DataAcquisitionConfiguration.BCS_PWD;
        String auth = X5StringUtils.encodeBase64(credentials);
 
        // 尝试直接发送JSON数据(不经过Base64和URL编码)
        RequestBody body = RequestBody.create(jsonData, MediaType.parse("application/json; charset=utf-8"));
 
        Request httpRequest = new Request.Builder()
                .url(DataAcquisitionConfiguration.BCS_101_URL)
                .method("POST", body)
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .addHeader("Authorization", "Basic " + auth)
                .build();
 
        // 执行请求
        try (Response response = client.newCall(httpRequest).execute()) {
            System.out.println("简化版本响应状态: " + response.code());
            if (response.body() != null) {
                String responseBody = response.body().string();
                System.out.println("简化版本响应内容: " + responseBody);
                return responseBody;
            }
            throw new IOException("Empty response body");
        }
    }
 
    /**
     * X5协议标准实现版本
     * 基于注释要求:X5协议中使用的(国密算法)
     * APP ID:bcs_fty_177301, APP Key:IJBVGMJXG4ZTAMLSMFXGI33NONQWY5DG
     */
    public String getBCS101DataX5Standard(BCS101Request request) throws IOException {
        System.out.println("=== BCS101 API X5协议标准实现 ===");
 
        // 1. 构建JSON数据
        String jsonData = objectMapper.writeValueAsString(request);
        System.out.println("1. 原始JSON: " + jsonData);
 
        // 2. Base64编码
        String base64Data = X5StringUtils.encodeBase64(jsonData);
        System.out.println("2. Base64编码: " + base64Data);
 
        // 3. URL编码
        String urlEncodedData = URLEncoder.encode(base64Data, "UTF-8");
        System.out.println("3. URL编码: " + urlEncodedData);
 
        // 4. 构建form数据
        String formData = "data=" + urlEncodedData;
        System.out.println("4. Form数据: " + formData);
 
        // 5. X5协议参数
        String appId = DataAcquisitionConfiguration.BCS_APP_ID;
        String appKey = DataAcquisitionConfiguration.BCS_APP_Key;
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String nonce = String.valueOf(System.currentTimeMillis()); // 使用时间戳作为nonce
 
        // 6. X5协议签名 - 标准算法: hash(appId + timestamp + nonce + appKey + data)
        String signString = appId + timestamp + nonce + appKey + formData;
        String signature;
        try {
            signature = SmUtil.sm3(signString);
            System.out.println("5. 使用SM3签名");
        } catch (Exception e) {
            signature = DigestUtil.md5Hex(signString).toUpperCase();
            System.out.println("5. 使用MD5签名 (SM3不可用)");
        }
 
        System.out.println("6. 签名字符串: " + signString);
        System.out.println("7. 签名值: " + signature);
 
        // 7. Basic Auth
        String credentials = DataAcquisitionConfiguration.BCS_USER_NAME + ":" + DataAcquisitionConfiguration.BCS_PWD;
        String auth = X5StringUtils.encodeBase64(credentials);
 
        // 8. 构建请求体
        RequestBody body = RequestBody.create(formData, MediaType.parse("application/x-www-form-urlencoded"));
 
        // 9. 构建请求 - 添加X5协议标准头部
        Request httpRequest = new Request.Builder()
                .url(DataAcquisitionConfiguration.BCS_101_URL)
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Authorization", "Basic " + auth)
                .addHeader("X-App-Id", appId)
                .addHeader("X-Timestamp", timestamp)
                .addHeader("X-Nonce", nonce)
                .addHeader("X-Signature", signature)
                .build();
 
        System.out.println("8. 发送X5标准请求...");
 
        // 10. 执行请求
        try (Response response = client.newCall(httpRequest).execute()) {
            System.out.println("9. 响应状态: " + response.code());
            System.out.println("10. 响应头: " + response.headers());
 
            if (response.body() != null) {
                String responseBody = response.body().string();
                System.out.println("11. 响应内容: " + responseBody);
                return responseBody;
            }
            throw new IOException("Empty response body");
        }
    }
 
    /**
     * X5协议变体2 - 不同的签名算法
     * 签名算法: hash(appKey + data + timestamp + appId)
     */
    public String getBCS101DataX5Variant(BCS101Request request) throws IOException {
        System.out.println("=== BCS101 API X5协议变体2 ===");
 
        // 1. 构建数据
        String jsonData = objectMapper.writeValueAsString(request);
        String base64Data = X5StringUtils.encodeBase64(jsonData);
        String urlEncodedData = URLEncoder.encode(base64Data, "UTF-8");
        String formData = "data=" + urlEncodedData;
 
        // 2. X5协议参数
        String appId = DataAcquisitionConfiguration.BCS_APP_ID;
        String appKey = DataAcquisitionConfiguration.BCS_APP_Key;
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
 
        // 3. 变体签名算法: appKey + data + timestamp + appId
        String signString = appKey + formData + timestamp + appId;
        String signature;
        try {
            signature = SmUtil.sm3(signString);
            System.out.println("使用SM3签名变体");
        } catch (Exception e) {
            signature = DigestUtil.md5Hex(signString).toUpperCase();
            System.out.println("使用MD5签名变体");
        }
 
        System.out.println("签名字符串(变体): " + signString);
        System.out.println("签名值(变体): " + signature);
 
        // 4. Basic Auth
        String credentials = DataAcquisitionConfiguration.BCS_USER_NAME + ":" + DataAcquisitionConfiguration.BCS_PWD;
        String auth = X5StringUtils.encodeBase64(credentials);
 
        // 5. 构建请求 - 使用常见的X5头部名称
        RequestBody body = RequestBody.create(formData, MediaType.parse("application/x-www-form-urlencoded"));
        Request httpRequest = new Request.Builder()
                .url(DataAcquisitionConfiguration.BCS_101_URL)
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Authorization", "Basic " + auth)
                .addHeader("appId", appId)
                .addHeader("timestamp", timestamp)
                .addHeader("signature", signature)
                .build();
 
        System.out.println("发送X5变体请求...");
 
        try (Response response = client.newCall(httpRequest).execute()) {
            System.out.println("变体响应状态: " + response.code());
            if (response.body() != null) {
                String responseBody = response.body().string();
                System.out.println("变体响应内容: " + responseBody);
                return responseBody;
            }
            throw new IOException("Empty response body");
        }
    }
}