From ecc482ce133bb73683dad2e0025eafbd9de87db8 Mon Sep 17 00:00:00 2001 From: Iamasoldier <1272745473@qq.com> Date: Sun, 3 Aug 2025 12:12:58 +0800 Subject: [PATCH] =?UTF-8?q?fix(=E8=AE=A2=E5=8D=95=E4=B8=AD=E5=BF=83)?= =?UTF-8?q?=EF=BC=9A=E9=A6=96=E9=A1=B5=E7=BB=9F=E8=AE=A1=E4=B8=B4=E6=97=B6?= =?UTF-8?q?=E6=BC=94=E7=A4=BA=E4=BF=AE=E5=A4=8D=EF=BC=8C=E4=BA=8C=E7=BB=B4?= =?UTF-8?q?=E7=A0=81=E7=A7=9F=E6=88=B7Id=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/HotDataSyncController.java | 85 +++ .../file/service/HotDataSyncService.java | 187 +++++- .../src/main/resources/application.yml | 2 +- .../order/controller/CouponController.java | 621 +++++++++++++++++- .../central/order/mapper/DashboardMapper.java | 70 +- .../central/order/util/CtripDecryptUtil.java | 315 +++++++++ .../central/order/util/DataDecoderUtil.java | 84 --- .../src/main/resources/application.yml | 8 + .../controller/CouponControllerTest.java | 70 +- .../src/main/frontend/src/pages/Welcome.tsx | 20 +- .../orders/Qrcode/components/CreateForm.tsx | 20 + .../orders/Qrcode/components/UpdateForm.tsx | 20 + .../src/pages/orders/Qrcode/index.tsx | 52 +- .../orders/Tourism/components/UpdateForm.tsx | 16 +- .../src/pages/orders/Tourism/index.tsx | 51 +- .../main/frontend/src/services/orders/api.ts | 11 + 16 files changed, 1362 insertions(+), 270 deletions(-) create mode 100644 zlt-business/order-center/src/main/java/com/central/order/util/CtripDecryptUtil.java delete mode 100644 zlt-business/order-center/src/main/java/com/central/order/util/DataDecoderUtil.java diff --git a/zlt-business/file-center/src/main/java/com/central/file/controller/HotDataSyncController.java b/zlt-business/file-center/src/main/java/com/central/file/controller/HotDataSyncController.java index c1ade628..68a857bd 100644 --- a/zlt-business/file-center/src/main/java/com/central/file/controller/HotDataSyncController.java +++ b/zlt-business/file-center/src/main/java/com/central/file/controller/HotDataSyncController.java @@ -10,6 +10,7 @@ import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; import java.util.Map; +import com.central.common.model.Result; /** * 热数据同步控制器 @@ -194,4 +195,88 @@ public class HotDataSyncController { return result; } + + /** + * 诊断S3配置和URL生成 + */ + @Operation(summary = "诊断S3配置和URL生成") + @GetMapping("/diagnose") + public Result> diagnoseS3Config() { + Map result = new HashMap<>(); + + try { + // 检查S3配置 + result.put("s3Enabled", hotDataSyncService.isS3Enabled()); + result.put("enhancedS3ServiceAvailable", hotDataSyncService.isEnhancedS3ServiceAvailable()); + result.put("s3ServiceAvailable", hotDataSyncService.isS3ServiceAvailable()); + + // 检查S3配置信息 + result.put("s3Config", hotDataSyncService.getS3ConfigInfo()); + + // 测试URL生成 + result.put("urlTest", hotDataSyncService.testUrlGeneration()); + + // 检查热同步配置 + result.put("hotSyncConfig", hotDataSyncService.getHotSyncConfig()); + + return Result.succeed(result); + } catch (Exception e) { + log.error("诊断S3配置失败", e); + result.put("error", e.getMessage()); + return Result.failed("诊断失败:" + e.getMessage()); + } + } + + /** + * 测试URL访问 + */ + @Operation(summary = "测试URL访问") + @PostMapping("/test-url") + public Result> testUrlAccess(@RequestParam String url) { + Map result = new HashMap<>(); + + try { + log.info("测试URL访问: {}", url); + + // 创建HTTP连接 + java.net.URL testUrl = new java.net.URL(url); + java.net.HttpURLConnection connection = (java.net.HttpURLConnection) testUrl.openConnection(); + connection.setRequestMethod("GET"); + connection.setConnectTimeout(10000); // 10秒连接超时 + connection.setReadTimeout(30000); // 30秒读取超时 + + // 设置User-Agent + connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"); + + int responseCode = connection.getResponseCode(); + String responseMessage = connection.getResponseMessage(); + + result.put("url", url); + result.put("responseCode", responseCode); + result.put("responseMessage", responseMessage); + result.put("contentType", connection.getContentType()); + result.put("contentLength", connection.getContentLengthLong()); + result.put("accessible", responseCode == 200); + + // 获取响应头信息 + Map headers = new HashMap<>(); + connection.getHeaderFields().forEach((key, values) -> { + if (key != null && values != null && !values.isEmpty()) { + headers.put(key, String.join(", ", values)); + } + }); + result.put("headers", headers); + + log.info("URL访问测试结果: 状态码={}, 消息={}, 可访问={}", responseCode, responseMessage, responseCode == 200); + + return Result.succeed(result); + + } catch (Exception e) { + log.error("测试URL访问失败: {}", url, e); + result.put("url", url); + result.put("error", e.getMessage()); + result.put("accessible", false); + return Result.failed("URL访问测试失败:" + e.getMessage()); + } + } } diff --git a/zlt-business/file-center/src/main/java/com/central/file/service/HotDataSyncService.java b/zlt-business/file-center/src/main/java/com/central/file/service/HotDataSyncService.java index 54df64dc..922c7c0d 100644 --- a/zlt-business/file-center/src/main/java/com/central/file/service/HotDataSyncService.java +++ b/zlt-business/file-center/src/main/java/com/central/file/service/HotDataSyncService.java @@ -19,6 +19,8 @@ import java.util.Date; import java.util.List; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; +import java.util.Map; +import java.util.HashMap; /** * 热数据自动同步服务 @@ -203,10 +205,14 @@ public class HotDataSyncService { log.info("开始同步文件到S3,文件ID: {}, 文件名: {}, 重试次数: {}/{}", fileInfo.getId(), fileInfo.getName(), retryCount + 1, maxRetries); + // 获取原始OSS路径(不包含hot-sync前缀) + String originalPath = getOriginalPath(fileInfo); + log.debug("原始OSS路径: {}", originalPath); + // 从OSS获取文件URL - String ossUrl = ossService.getViewUrlByPath(fileInfo.getPath()); + String ossUrl = ossService.getViewUrlByPath(originalPath); if (ossUrl == null || ossUrl.isEmpty()) { - log.error("从OSS获取文件URL失败,文件ID: {}", fileInfo.getId()); + log.error("从OSS获取文件URL失败,文件ID: {}, 路径: {}", fileInfo.getId(), originalPath); return false; } @@ -230,16 +236,26 @@ public class HotDataSyncService { } if (uploadSuccess) { - // 更新文件存储信息 - updateFileStorageInfo(fileInfo, s3Path); - log.info("文件同步成功,文件ID: {}, 新路径: {}", fileInfo.getId(), s3Path); - return true; + // 验证文件是否真的上传成功 + if (verifyFileUpload(s3Path)) { + // 更新文件存储信息 + updateFileStorageInfo(fileInfo, s3Path); + log.info("文件同步成功,文件ID: {}, 新路径: {}", fileInfo.getId(), s3Path); + return true; + } else { + log.error("文件上传验证失败,文件ID: {}", fileInfo.getId()); + retryCount++; + if (retryCount < maxRetries) { + log.info("准备重试,等待2秒后重试..."); + Thread.sleep(2000); + } + } } else { log.error("文件上传到S3失败,文件ID: {}", fileInfo.getId()); retryCount++; if (retryCount < maxRetries) { log.info("准备重试,等待2秒后重试..."); - Thread.sleep(2000); // 等待2秒后重试 + Thread.sleep(2000); } } @@ -254,7 +270,7 @@ public class HotDataSyncService { if (retryCount < maxRetries) { try { log.info("准备重试,等待2秒后重试..."); - Thread.sleep(2000); // 等待2秒后重试 + Thread.sleep(2000); } catch (InterruptedException ie) { log.error("重试等待被中断", ie); Thread.currentThread().interrupt(); @@ -371,14 +387,55 @@ public class HotDataSyncService { return "hot-sync/" + fileInfo.getId() + "/" + fileInfo.getName(); } - // 如果原路径包含OSS信息,替换为S3路径 - if (originalPath.contains("oss://") || originalPath.contains("aliyun")) { - return originalPath.replace("oss://", "s3://") - .replace("aliyun", "minio"); + // 提取文件名,避免路径过长 + String fileName = fileInfo.getName(); + if (fileName == null || fileName.isEmpty()) { + // 从路径中提取文件名 + if (originalPath.contains("/")) { + fileName = originalPath.substring(originalPath.lastIndexOf("/") + 1); + } else { + fileName = originalPath; + } } - // 否则添加热同步前缀 - return "hot-sync/" + originalPath; + // 生成简洁的S3路径 + return "hot-sync/" + fileName; + } + + /** + * 获取原始OSS路径(去除hot-sync前缀) + */ + private String getOriginalPath(FileInfo fileInfo) { + String path = fileInfo.getPath(); + if (path == null || path.isEmpty()) { + return path; + } + + // 如果路径包含hot-sync前缀,去除它 + if (path.startsWith("hot-sync/")) { + return path.substring("hot-sync/".length()); + } + + return path; + } + + /** + * 验证文件是否上传成功 + */ + private boolean verifyFileUpload(String s3Path) { + try { + if (enhancedS3Service != null) { + return enhancedS3Service.fileExists(s3Path); + } else if (s3Service != null) { + // 基础S3服务验证 + String url = s3Service.getViewUrlByPath(s3Path); + return url != null && !url.isEmpty(); + } + return false; + } catch (Exception e) { + log.warn("验证文件上传失败: {}", s3Path, e); + return false; + } } /** @@ -482,7 +539,105 @@ public class HotDataSyncService { * 获取配置信息 */ public String getConfigInfo() { - return String.format("批次大小: %d, 同步间隔: %d分钟, 访问阈值: %d, 热数据天数: %d, 最大线程: %d", - batchSize, syncIntervalMinutes, accessThreshold, hotDataDays, maxThreads); + return String.format("热数据同步配置 - 启用: %s, 批次大小: %d, 同步间隔: %d分钟, 访问阈值: %d, 最大线程数: %d, 热数据天数: %d", + syncEnabled, batchSize, syncIntervalMinutes, accessThreshold, maxThreads, hotDataDays); + } + + /** + * 检查S3是否启用 + */ + public boolean isS3Enabled() { + return syncEnabled; + } + + /** + * 检查增强S3服务是否可用 + */ + public boolean isEnhancedS3ServiceAvailable() { + return enhancedS3Service != null; + } + + /** + * 检查基础S3服务是否可用 + */ + public boolean isS3ServiceAvailable() { + return s3Service != null; + } + + /** + * 获取S3配置信息 + */ + public Map getS3ConfigInfo() { + Map config = new HashMap<>(); + + if (enhancedS3Service != null) { + config.put("enhancedS3Service", "可用"); + // 尝试获取S3配置信息 + try { + // 这里可以添加更多S3配置信息的获取逻辑 + config.put("s3Template", enhancedS3Service != null ? "已配置" : "未配置"); + } catch (Exception e) { + config.put("s3Template", "配置错误: " + e.getMessage()); + } + } else { + config.put("enhancedS3Service", "不可用"); + } + + if (s3Service != null) { + config.put("s3Service", "可用"); + } else { + config.put("s3Service", "不可用"); + } + + return config; + } + + /** + * 测试URL生成 + */ + public Map testUrlGeneration() { + Map result = new HashMap<>(); + + try { + // 测试一个示例路径 + String testPath = "hot-sync/test-file.txt"; + + if (enhancedS3Service != null) { + String url = enhancedS3Service.getViewUrlByPath(testPath); + result.put("enhancedS3Url", url); + result.put("enhancedS3UrlValid", url != null && !url.isEmpty()); + } + + if (s3Service != null) { + String url = s3Service.getViewUrlByPath(testPath); + result.put("s3ServiceUrl", url); + result.put("s3ServiceUrlValid", url != null && !url.isEmpty()); + } + + result.put("testPath", testPath); + + } catch (Exception e) { + result.put("error", e.getMessage()); + } + + return result; + } + + /** + * 获取热同步配置 + */ + public Map getHotSyncConfig() { + Map config = new HashMap<>(); + config.put("syncEnabled", syncEnabled); + config.put("batchSize", batchSize); + config.put("syncIntervalMinutes", syncIntervalMinutes); + config.put("accessThreshold", accessThreshold); + config.put("maxThreads", maxThreads); + config.put("hotDataDays", hotDataDays); + config.put("running", running); + config.put("lastSyncTime", lastSyncTime); + config.put("totalSyncedFiles", totalSyncedFiles.get()); + config.put("totalFailedFiles", totalFailedFiles.get()); + return config; } } \ No newline at end of file diff --git a/zlt-business/file-center/src/main/resources/application.yml b/zlt-business/file-center/src/main/resources/application.yml index 58bebc14..2612dd7d 100644 --- a/zlt-business/file-center/src/main/resources/application.yml +++ b/zlt-business/file-center/src/main/resources/application.yml @@ -54,7 +54,7 @@ zlt: delete-source: false # 迁移后是否删除源文件 batch-size: 100 # 迁移批次大小 hot-sync: - enabled: true # 启用热数据同步 + enabled: true # 启用热数据同步 batch-size: 100 # 批次大小 interval-minutes: 30 # 同步间隔 access-threshold: 10 # 访问次数阈值 diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/CouponController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/CouponController.java index 8e668558..da5daad4 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/controller/CouponController.java +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/CouponController.java @@ -25,10 +25,12 @@ import com.central.order.model.CtripCreateOrderRequest.CtripOrderItem; import com.central.order.model.CtripCreateOrderRequest.CtripPassenger; import com.central.order.model.CtripCreateOrderRequest.CtripContact; import com.central.order.model.CtripCreateOrderRequest.CtripHeader; -import com.central.order.util.DataDecoderUtil; + import com.central.order.model.CtripCreateOrderResponse; import com.central.order.service.IOrderService; +import com.central.order.util.CtripDecryptUtil; import java.util.ArrayList; +import java.util.HashMap; /** * 优惠券管理控制器 @@ -42,6 +44,9 @@ public class CouponController { @Autowired private ICouponService couponService; + @Autowired + private CtripDecryptUtil ctripDecryptUtil; + /** * 列表 */ @@ -151,32 +156,77 @@ public class CouponController { log.info("收到加密的body数据,长度:{}", encryptedBody.length()); // 尝试解码body数据 - String decodedBody = DataDecoderUtil.tryDecode(encryptedBody); + String decodedBody = tryDecode(encryptedBody); if (!decodedBody.equals(encryptedBody)) { log.info("body数据解码成功,尝试解析解码后的数据"); - if (DataDecoderUtil.isValidJson(decodedBody)) { + log.debug("解码后的数据前100个字符:{}", decodedBody.length() > 100 ? decodedBody.substring(0, 100) + "..." : decodedBody); + + if (isValidJson(decodedBody)) { // 解析解码后的JSON数据 com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - body = objectMapper.readValue(decodedBody, CtripOrderBody.class); + try { + body = objectMapper.readValue(decodedBody, CtripOrderBody.class); + log.info("成功解析解码后的JSON数据"); + } catch (Exception e) { + log.error("解析解码后的JSON数据失败:{}", e.getMessage()); + } + } else { + log.warn("解码后的数据不是有效的JSON格式,尝试进一步处理"); + // 尝试其他解码方式或直接处理 + String processedData = processDecodedData(decodedBody); + if (processedData != null && isValidJson(processedData)) { + com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); + objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + try { + body = objectMapper.readValue(processedData, CtripOrderBody.class); + log.info("成功解析处理后的JSON数据"); + } catch (Exception e) { + log.error("解析处理后的JSON数据失败:{}", e.getMessage()); + } + } } } else { // 如果解码失败,尝试直接解析为JSON - if (DataDecoderUtil.isValidJson(encryptedBody)) { + if (isValidJson(encryptedBody)) { log.info("body数据是有效的JSON格式,直接解析"); com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - body = objectMapper.readValue(encryptedBody, CtripOrderBody.class); + try { + body = objectMapper.readValue(encryptedBody, CtripOrderBody.class); + log.info("成功解析原始JSON数据"); + } catch (Exception e) { + log.error("解析原始JSON数据失败:{}", e.getMessage()); + } + } + } + + // 如果仍然无法解析,尝试使用携程特定的解密方法 + if (body == null) { + log.warn("标准解码失败,尝试携程特定解密方法"); + try { + String decryptedBody = tryCtripDecrypt(encryptedBody, request.getHeader().getAccountId()); + if (decryptedBody != null && isValidJson(decryptedBody)) { + com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); + objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + body = objectMapper.readValue(decryptedBody, CtripOrderBody.class); + log.info("成功通过携程解密解析数据"); + } + } catch (Exception e) { + log.error("携程解密失败:{}", e.getMessage()); } } if (body == null) { - log.error("无法解析body数据,数据格式:{}", DataDecoderUtil.analyzeDataFormat(encryptedBody)); + log.error("无法解析body数据,数据格式:{}", analyzeDataFormat(encryptedBody)); + log.error("解码后的数据格式:{}", analyzeDataFormat(decodedBody)); + log.error("解码后的数据详情:{}", getDataDetails(decodedBody)); return buildErrorResponse(request, "0007", "无法解析body数据,请联系技术支持"); } } else if (request.getBody() instanceof CtripOrderBody) { // body已经是对象 body = (CtripOrderBody) request.getBody(); + log.info("body已经是对象格式"); } else { log.error("body字段格式不支持:{}", request.getBody().getClass().getName()); return buildErrorResponse(request, "0008", "body字段格式不支持"); @@ -394,20 +444,20 @@ public class CouponController { } // 分析数据格式 - String dataFormat = DataDecoderUtil.analyzeDataFormat(nonJsonData); + String dataFormat = analyzeDataFormat(nonJsonData); log.info("数据格式分析结果:{}", dataFormat); // 检查是否是JSON格式 - if (DataDecoderUtil.isValidJson(nonJsonData)) { + if (isValidJson(nonJsonData)) { log.info("数据是JSON格式,转发到标准接口"); return createCouponFromCtripRaw(nonJsonData); } // 尝试解码 - String decodedData = DataDecoderUtil.tryDecode(nonJsonData); + String decodedData = tryDecode(nonJsonData); if (!decodedData.equals(nonJsonData)) { log.info("数据解码成功,尝试解析解码后的数据"); - if (DataDecoderUtil.isValidJson(decodedData)) { + if (isValidJson(decodedData)) { return createCouponFromCtripRaw(decodedData); } } @@ -489,4 +539,553 @@ public class CouponController { } } } + + // 处理解码后的数据,尝试进一步解析 + private String processDecodedData(String decodedData) { + log.debug("尝试进一步处理解码后的数据,长度:{}", decodedData.length()); + + // 检查是否是JSON格式 + if (isValidJson(decodedData)) { + log.info("解码后的数据是有效的JSON格式"); + return decodedData; + } + + // 尝试移除可能的BOM或其他前缀 + String cleanedData = decodedData.trim(); + if (cleanedData.startsWith("\uFEFF")) { + cleanedData = cleanedData.substring(1); + log.info("移除了BOM前缀"); + } + + // 尝试查找JSON开始位置 + int jsonStart = cleanedData.indexOf("{"); + if (jsonStart >= 0) { + String jsonPart = cleanedData.substring(jsonStart); + if (isValidJson(jsonPart)) { + log.info("找到有效的JSON部分"); + return jsonPart; + } + } + + // 尝试查找JSON结束位置 + int jsonEnd = cleanedData.lastIndexOf("}"); + if (jsonEnd >= 0) { + String jsonPart = cleanedData.substring(0, jsonEnd + 1); + if (isValidJson(jsonPart)) { + log.info("找到有效的JSON部分(从开始到结束)"); + return jsonPart; + } + } + + // 尝试AES解密 + log.info("尝试对解码后的数据进行AES解密"); + try { + String decryptedData = tryAesDecrypt(decodedData); + if (decryptedData != null && isValidJson(decryptedData)) { + log.info("AES解密成功,得到有效的JSON数据"); + return decryptedData; + } + } catch (Exception e) { + log.debug("AES解密失败:{}", e.getMessage()); + } + + // 尝试将数据转换为十六进制字符串,然后查找JSON + try { + StringBuilder hexString = new StringBuilder(); + for (byte b : decodedData.getBytes()) { + hexString.append(String.format("%02x", b)); + } + String hexData = hexString.toString(); + log.debug("数据转换为十六进制,长度:{}", hexData.length()); + + // 在十六进制数据中查找可能的JSON字符串 + if (hexData.contains("7b") && hexData.contains("7d")) { // { 和 } 的十六进制 + log.info("在十六进制数据中发现了JSON字符"); + // 这里可以添加更复杂的十六进制解析逻辑 + } + } catch (Exception e) { + log.debug("十六进制转换失败:{}", e.getMessage()); + } + + log.warn("无法从解码后的数据中提取有效的JSON,数据前100个字符:{}", + cleanedData.length() > 100 ? cleanedData.substring(0, 100) + "..." : cleanedData); + return null; + } + + // 工具方法 + private String tryDecode(String encodedData) { + if (encodedData == null || encodedData.trim().isEmpty()) { + return encodedData; + } + try { + byte[] decodedBytes = java.util.Base64.getDecoder().decode(encodedData); + String decodedString = new String(decodedBytes, "UTF-8"); + log.debug("Base64解码成功,原长度:{},解码后长度:{}", + encodedData.length(), decodedString.length()); + return decodedString; + } catch (Exception e) { + log.debug("Base64解码失败,数据可能不是Base64编码:{}", e.getMessage()); + return encodedData; + } + } + + private boolean isValidJson(String data) { + if (data == null || data.trim().isEmpty()) { + return false; + } + String trimmed = data.trim(); + return trimmed.startsWith("{") && trimmed.endsWith("}"); + } + + private String analyzeDataFormat(String data) { + if (data == null) return "null"; + if (data.trim().isEmpty()) return "empty"; + if (isValidJson(data)) return "valid_json"; + + try { + java.util.Base64.getDecoder().decode(data); + return "base64_encoded"; + } catch (Exception e) { + // 不是Base64编码 + } + + if (data.matches("^[a-zA-Z0-9]+$")) return "alphanumeric_string"; + if (data.contains("{") || data.contains("}")) return "contains_json_chars"; + if (data.contains("<") || data.contains(">")) return "contains_xml_chars"; + if (data.length() > 100 && data.matches(".*[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F].*")) { + return "binary_data"; + } + + return "unknown_format"; + } + + private String getDataDetails(String data) { + if (data == null) return "null"; + + StringBuilder details = new StringBuilder(); + details.append("长度: ").append(data.length()); + details.append(", 格式: ").append(analyzeDataFormat(data)); + + if (data.length() > 0) { + details.append(", 前10个字符: ").append(data.substring(0, Math.min(10, data.length()))); + if (data.length() > 20) { + details.append(", 后10个字符: ").append(data.substring(data.length() - 10)); + } + } + + return details.toString(); + } + + private String tryCtripDecrypt(String encryptedData, String accountId) { + if (encryptedData == null || encryptedData.trim().isEmpty()) { + return null; + } + + try { + String[] possibleKeys = { + accountId, + accountId + "1234567890123456", + "ctrip" + accountId, + accountId.substring(0, Math.min(16, accountId.length())), + "ctrip123456789012", + "c50a8f2a4a59c9e7" + }; + + for (String key : possibleKeys) { + try { + String decrypted = decryptAES(encryptedData, key, "0000000000000000"); + if (decrypted != null && isValidJson(decrypted)) { + log.info("携程数据解密成功,使用密钥:{}", key); + return decrypted; + } + } catch (Exception e) { + log.debug("携程AES解密失败,密钥:{},错误:{}", key, e.getMessage()); + } + + try { + String decrypted = decryptAESWithMode(encryptedData, key, "AES/ECB/PKCS5Padding"); + if (decrypted != null && isValidJson(decrypted)) { + log.info("携程数据ECB解密成功,使用密钥:{}", key); + return decrypted; + } + } catch (Exception e) { + log.debug("携程ECB解密失败,密钥:{},错误:{}", key, e.getMessage()); + } + } + + log.warn("所有携程解密尝试都失败了"); + return null; + + } catch (Exception e) { + log.error("携程解密过程中发生异常:{}", e.getMessage()); + return null; + } + } + + private String tryAesDecrypt(String encryptedData) { + if (encryptedData == null || encryptedData.trim().isEmpty()) { + return null; + } + + try { + String[] possibleKeys = { + "1234567890123456", "12345678901234567890123456789012", + "c50a8f2a4a59c9e7", "ctrip123456789012", "gofly123456789012", + "ctriptest1234567", "ctrip12345678901234567890123456789012" + }; + + String[] possibleIVs = { + "1234567890123456", "0000000000000000", "c50a8f2a4a59c9e7", + "ctrip123456789012", "00000000000000000000000000000000" + }; + + // 尝试不同的密钥和IV组合 + for (String key : possibleKeys) { + for (String iv : possibleIVs) { + try { + String decrypted = decryptAES(encryptedData, key, iv); + if (decrypted != null && isValidJson(decrypted)) { + log.info("AES解密成功,使用密钥:{},IV:{}", key, iv); + return decrypted; + } + } catch (Exception e) { + log.debug("AES解密失败,密钥:{},IV:{},错误:{}", key, iv, e.getMessage()); + } + } + } + + // 尝试不同的加密模式 + String[] modes = {"AES/CBC/PKCS5Padding", "AES/ECB/PKCS5Padding", "AES/CBC/NoPadding"}; + for (String mode : modes) { + for (String key : possibleKeys) { + try { + String decrypted = decryptAESWithMode(encryptedData, key, mode); + if (decrypted != null && isValidJson(decrypted)) { + log.info("AES解密成功,使用模式:{},密钥:{}", mode, key); + return decrypted; + } + } catch (Exception e) { + log.debug("AES解密失败,模式:{},密钥:{},错误:{}", mode, key, e.getMessage()); + } + } + } + + log.warn("所有AES解密尝试都失败了"); + return null; + + } catch (Exception e) { + log.error("AES解密过程中发生异常:{}", e.getMessage()); + return null; + } + } + + private String decryptAES(String encryptedData, String key, String iv) throws Exception { + byte[] encryptedBytes; + try { + encryptedBytes = java.util.Base64.getDecoder().decode(encryptedData); + } catch (Exception e) { + encryptedBytes = encryptedData.getBytes(java.nio.charset.StandardCharsets.UTF_8); + } + + byte[] keyBytes = adjustKeyLength(key.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + byte[] ivBytes = adjustIVLength(iv.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + + javax.crypto.spec.SecretKeySpec secretKeySpec = new javax.crypto.spec.SecretKeySpec(keyBytes, "AES"); + javax.crypto.spec.IvParameterSpec ivParameterSpec = new javax.crypto.spec.IvParameterSpec(ivBytes); + + javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("AES/CBC/PKCS5Padding"); + cipher.init(javax.crypto.Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); + + byte[] decryptedBytes = cipher.doFinal(encryptedBytes); + return new String(decryptedBytes, java.nio.charset.StandardCharsets.UTF_8); + } + + private String decryptAESWithMode(String encryptedData, String key, String mode) throws Exception { + byte[] encryptedBytes; + try { + encryptedBytes = java.util.Base64.getDecoder().decode(encryptedData); + } catch (Exception e) { + encryptedBytes = encryptedData.getBytes(java.nio.charset.StandardCharsets.UTF_8); + } + + byte[] keyBytes = adjustKeyLength(key.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + javax.crypto.spec.SecretKeySpec secretKeySpec = new javax.crypto.spec.SecretKeySpec(keyBytes, "AES"); + + javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(mode); + + if (mode.contains("CBC")) { + byte[] ivBytes = new byte[16]; + javax.crypto.spec.IvParameterSpec ivParameterSpec = new javax.crypto.spec.IvParameterSpec(ivBytes); + cipher.init(javax.crypto.Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); + } else { + cipher.init(javax.crypto.Cipher.DECRYPT_MODE, secretKeySpec); + } + + byte[] decryptedBytes = cipher.doFinal(encryptedBytes); + return new String(decryptedBytes, java.nio.charset.StandardCharsets.UTF_8); + } + + private byte[] adjustKeyLength(byte[] keyBytes) { + if (keyBytes.length == 16 || keyBytes.length == 24 || keyBytes.length == 32) { + return keyBytes; + } + + int targetLength = keyBytes.length < 16 ? 16 : (keyBytes.length < 24 ? 24 : 32); + byte[] newKeyBytes = new byte[targetLength]; + System.arraycopy(keyBytes, 0, newKeyBytes, 0, Math.min(keyBytes.length, targetLength)); + return newKeyBytes; + } + + private byte[] adjustIVLength(byte[] ivBytes) { + if (ivBytes.length == 16) { + return ivBytes; + } + + byte[] newIvBytes = new byte[16]; + System.arraycopy(ivBytes, 0, newIvBytes, 0, Math.min(ivBytes.length, 16)); + return newIvBytes; + } + + /** + * 测试携程解密功能 + */ + @Operation(summary = "测试携程解密功能") + @PostMapping("/ctrip/test-decrypt") + public Result testCtripDecrypt(@RequestBody String encryptedData) { + log.info("测试携程解密功能,加密数据长度: {}", encryptedData.length()); + + try { + // 检查配置 + if (!ctripDecryptUtil.isConfigValid()) { + log.error("携程解密配置不完整: {}", ctripDecryptUtil.getConfigInfo()); + return Result.failed("携程解密配置不完整"); + } + + // 使用携程标准解密 + String decryptedData = ctripDecryptUtil.decryptCtripBody(encryptedData); + + if (decryptedData != null) { + log.info("解密成功,解密后数据长度: {}", decryptedData.length()); + log.info("解密后数据前200个字符: {}", + decryptedData.length() > 200 ? decryptedData.substring(0, 200) + "..." : decryptedData); + return Result.succeed(decryptedData); + } else { + log.error("解密失败"); + return Result.failed("解密失败"); + } + + } catch (Exception e) { + log.error("测试解密功能异常: {}", e.getMessage(), e); + return Result.failed("测试解密功能异常: " + e.getMessage()); + } + } + + /** + * 携程创建优惠券接口(新版本,使用正确的解密逻辑) + */ + @Operation(summary = "携程创建优惠券接口(新版本)") + @PostMapping("/ctrip/create/v2") + public CtripCreateOrderResponse createCouponFromCtripV2(@RequestBody CtripCreateOrderRequest request) { + log.info("携程创建优惠券请求(新版本):{}", request); + + try { + // 检查配置 + if (!ctripDecryptUtil.isConfigValid()) { + log.error("携程解密配置不完整: {}", ctripDecryptUtil.getConfigInfo()); + return buildErrorResponse(request, "CONFIG_ERROR", "携程解密配置不完整"); + } + + // 验证请求头 + if (request.getHeader() == null || request.getBody() == null) { + log.error("请求格式错误:header或body为空"); + return buildErrorResponse(request, "0001", "请求格式错误"); + } + + // 处理body字段 + CtripOrderBody body = null; + if (request.getBody() instanceof String) { + // body是加密字符串,需要解密 + String encryptedBody = (String) request.getBody(); + log.info("收到加密的body数据,长度:{}", encryptedBody.length()); + + // 使用携程标准解密 + String decryptedBody = ctripDecryptUtil.decryptCtripBody(encryptedBody); + + if (decryptedBody == null) { + log.error("携程标准解密失败"); + return buildErrorResponse(request, "DECRYPT_ERROR", "请求体解密失败"); + } + + log.info("body数据解密成功,解密后数据长度: {}", decryptedBody.length()); + log.debug("解密后数据前200个字符: {}", + decryptedBody.length() > 200 ? decryptedBody.substring(0, 200) + "..." : decryptedBody); + + // 解析解密后的JSON + try { + // 先验证JSON格式 + if (!isValidJson(decryptedBody)) { + log.error("解密后的数据不是有效的JSON格式"); + log.error("解密后数据前200个字符: {}", + decryptedBody.length() > 200 ? decryptedBody.substring(0, 200) + "..." : decryptedBody); + return buildErrorResponse(request, "INVALID_JSON", "解密后的数据不是有效的JSON格式"); + } + + com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); + objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + body = objectMapper.readValue(decryptedBody, CtripOrderBody.class); + log.info("成功解析解密后的JSON数据"); + } catch (Exception e) { + log.error("解析解密后的JSON数据失败:{}", e.getMessage()); + log.error("解密后数据前200个字符: {}", + decryptedBody.length() > 200 ? decryptedBody.substring(0, 200) + "..." : decryptedBody); + return buildErrorResponse(request, "JSON_PARSE_ERROR", "JSON解析失败"); + } + + } else if (request.getBody() instanceof CtripOrderBody) { + // body已经是对象 + body = (CtripOrderBody) request.getBody(); + log.info("body已经是对象格式"); + } else { + log.error("未知的body数据类型:{}", request.getBody().getClass().getSimpleName()); + return buildErrorResponse(request, "0002", "未知的body数据类型"); + } + + // 验证签名 + if (request.getHeader().getSign() != null) { + // 使用携程标准签名验证 + boolean signValid = ctripDecryptUtil.verifySign( + request.getHeader().getAccountId(), + request.getHeader().getServiceName(), + request.getHeader().getRequestTime(), + (String) request.getBody(), // 使用加密的body + request.getHeader().getVersion(), + request.getHeader().getSign() + ); + + if (!signValid) { + log.error("签名验证失败"); + return buildErrorResponse(request, "SIGN_ERROR", "签名验证失败"); + } + + log.info("签名验证成功"); + } + + // 验证必要字段 + if (body == null) { + log.error("订单信息为空"); + return buildErrorResponse(request, "0003", "订单信息为空"); + } + + // 打印解析后的订单信息用于调试 + log.info("解析后的订单信息: otaOrderId={}, sequenceId={}, items数量={}", + body.getOtaOrderId(), body.getSequenceId(), + body.getItems() != null ? body.getItems().size() : 0); + + if (body.getItems() == null || body.getItems().isEmpty()) { + log.error("订单项为空,完整订单信息: {}", body); + return buildErrorResponse(request, "0003", "订单项为空"); + } + + // 创建优惠券(这里需要根据实际的优惠券创建逻辑来调整) + String otaOrderId = "CTRIP_" + System.currentTimeMillis(); + // TODO: 实现具体的优惠券创建逻辑 + boolean success = true; // 临时设置为true,实际需要实现具体的创建逻辑 + + if (success) { + log.info("携程优惠券创建成功,OTA订单ID: {}", otaOrderId); + return buildSuccessResponse(request, otaOrderId, "优惠券创建成功"); + } else { + log.error("携程优惠券创建失败"); + return buildErrorResponse(request, "0004", "优惠券创建失败"); + } + + } catch (Exception e) { + log.error("处理携程请求异常:{}", e.getMessage(), e); + return buildErrorResponse(request, "0005", "系统处理异常"); + } + } + + /** + * 调试携程解密数据 + */ + @Operation(summary = "调试携程解密数据") + @PostMapping("/ctrip/debug-decrypt") + public Result> debugCtripDecrypt(@RequestBody String encryptedData) { + log.info("调试携程解密数据,加密数据长度: {}", encryptedData.length()); + + Map result = new HashMap<>(); + + try { + // 检查配置 + if (!ctripDecryptUtil.isConfigValid()) { + result.put("error", "携程解密配置不完整"); + result.put("configInfo", ctripDecryptUtil.getConfigInfo()); + return Result.succeed(result); + } + + // 使用携程标准解密 + String decryptedData = ctripDecryptUtil.decryptCtripBody(encryptedData); + + if (decryptedData != null) { + result.put("success", true); + result.put("decryptedLength", decryptedData.length()); + result.put("decryptedData", decryptedData); + result.put("decryptedDataFirst200", + decryptedData.length() > 200 ? decryptedData.substring(0, 200) + "..." : decryptedData); + + // 尝试解析JSON + try { + com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); + objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + CtripOrderBody body = objectMapper.readValue(decryptedData, CtripOrderBody.class); + + result.put("jsonParseSuccess", true); + result.put("otaOrderId", body.getOtaOrderId()); + result.put("sequenceId", body.getSequenceId()); + result.put("itemsCount", body.getItems() != null ? body.getItems().size() : 0); + result.put("contactsCount", body.getContacts() != null ? body.getContacts().size() : 0); + + // 如果有订单项,显示第一个订单项的详细信息 + if (body.getItems() != null && !body.getItems().isEmpty()) { + CtripOrderItem firstItem = body.getItems().get(0); + Map itemInfo = new HashMap<>(); + itemInfo.put("passengersCount", firstItem.getPassengers() != null ? firstItem.getPassengers().size() : 0); + itemInfo.put("cost", firstItem.getCost()); + itemInfo.put("salePrice", firstItem.getSalePrice()); + itemInfo.put("price", firstItem.getPrice()); + itemInfo.put("quantity", firstItem.getQuantity()); + itemInfo.put("useStartDate", firstItem.getUseStartDate()); + itemInfo.put("useEndDate", firstItem.getUseEndDate()); + + // 如果有乘客信息,显示第一个乘客的信息 + if (firstItem.getPassengers() != null && !firstItem.getPassengers().isEmpty()) { + CtripPassenger firstPassenger = firstItem.getPassengers().get(0); + Map passengerInfo = new HashMap<>(); + passengerInfo.put("name", firstPassenger.getName()); + passengerInfo.put("mobile", firstPassenger.getMobile()); + passengerInfo.put("gender", firstPassenger.getGender()); + passengerInfo.put("cardNo", firstPassenger.getCardNo()); + itemInfo.put("firstPassenger", passengerInfo); + } + + result.put("firstItem", itemInfo); + } + + } catch (Exception e) { + result.put("jsonParseSuccess", false); + result.put("jsonParseError", e.getMessage()); + } + + } else { + result.put("success", false); + result.put("error", "解密失败"); + } + + } catch (Exception e) { + result.put("success", false); + result.put("error", "调试解密功能异常: " + e.getMessage()); + } + + return Result.succeed(result); + } } \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/mapper/DashboardMapper.java b/zlt-business/order-center/src/main/java/com/central/order/mapper/DashboardMapper.java index 38be4129..b4668e76 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/mapper/DashboardMapper.java +++ b/zlt-business/order-center/src/main/java/com/central/order/mapper/DashboardMapper.java @@ -14,14 +14,7 @@ public interface DashboardMapper { // 基础订单统计(支持筛选) @Select({ "