From 76f9e622530b84dbd90560861266eba76be16126 Mon Sep 17 00:00:00 2001 From: luqingjie <544309509@qq.com> Date: Thu, 29 Oct 2026 02:45:36 -0400 Subject: [PATCH] =?UTF-8?q?=E8=AF=B7=E6=B7=BB=E5=8A=A0=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E8=BE=93=E5=87=BA=E5=AE=9A=E4=BD=8D=E6=8E=92=E6=9F=A5=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/rental/topup-payment.md | 14 +++++++++ .../system/rental/RentalDiagnostics.java | 31 +++++++++++++++++++ .../com/ruoyi/system/rental/RentalErrors.java | 3 ++ .../system/rental/RentalPaymentClient.java | 12 +++++++ .../com/ruoyi/system/rental/RentalTopups.java | 31 +++++++++++++++++++ .../ruoyi/system/rental/RentalTopupTest.java | 10 ++++++ 6 files changed, 101 insertions(+) create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalDiagnostics.java diff --git a/docs/rental/topup-payment.md b/docs/rental/topup-payment.md index 89ae777..8619b88 100644 --- a/docs/rental/topup-payment.md +++ b/docs/rental/topup-payment.md @@ -72,4 +72,18 @@ RENT_PAYMENT_MAINNET_MAX_AMOUNT=10000.00 ## 验证范围 +### 充值失败日志定位 + +默认 INFO 级别即可看到充值阶段日志,不需要打开全局 DEBUG。搜索 `充值创建失败` 或 `充值核对失败`,按 `diagnosticId`、`topupNo` 或 `orderId` 关联同一次处理。 + +- `CHANNEL_CONFIG`:检查该网络启用状态及凭证是否配置,日志只记录布尔值。 +- `PUBLIC_KEY_LOAD`:公钥文件读取或 RSA 解析失败;`fileResource=false` 时检查是否遗漏 `file:` 前缀。 +- `LOCAL_ORDER_TRANSACTION`:账户检查、本地充值表查询或插入失败。 +- `PAYMENT_RECONCILE`:补偿租约申请等失败,包括旧表缺少 `lease_token` 字段。 +- `PAYMENT_CREATE` / `PAYMENT_QUERY`:支付连接、TLS、认证、解析失败;结合支付 HTTP 状态和 businessCode 检查。 +- `PAYMENT_CREATE_RESPONSE_VALIDATE`:支付返回单号、金额、地址、有效期或收银台地址不符合要求。 +- `CHAIN_VERIFY` / `LEDGER_CREDIT`:链上核验或账务事务失败。 + +异常摘要保留异常因果类型、前五个堆栈位置及 SQLState/数据库错误码,不记录异常原文,避免 SQL 参数、支付响应、Secret、公钥正文和签名进入日志。日志定位到阶段后,再检查对应服务器文件或配置;不要向日志追加完整配置对象。 + 隔离测试使用 H2 事务和可控支付/链上适配器,覆盖通知验签、重复请求、超时补偿、双网络金额核对、冻结账户、共享幂等键、并发补偿及租约接管。测试不会访问真实支付账户、修改线上数据库或广播交易。上线前仍需在 NILE 配置真实支付通道完成端到端验收。 diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalDiagnostics.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalDiagnostics.java new file mode 100644 index 0000000..a8f9438 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalDiagnostics.java @@ -0,0 +1,31 @@ +package com.ruoyi.system.rental; + +/** + * 安全异常定位摘要。只输出异常类型、SQL状态与代码位置,不输出异常原文。 + * SQL异常和HTTP异常原文可能包含凭证、SQL参数或响应体,禁止直接把Throwable传给日志。 + */ +final class RentalDiagnostics { + private RentalDiagnostics() { } + + static String describe(Throwable error) { + StringBuilder result = new StringBuilder(); + // 限制因果链和堆栈长度,兼容循环cause并避免异常日志无限膨胀。 + java.util.Set visited = java.util.Collections.newSetFromMap( + new java.util.IdentityHashMap()); + for (int depth = 0; error != null && depth < 8 && visited.add(error); depth++, error = error.getCause()) { + if (depth > 0) { result.append(" <- "); } + result.append(error.getClass().getName()); + if (error instanceof java.sql.SQLException) { + java.sql.SQLException sql = (java.sql.SQLException) error; + String state = sql.getSQLState(); + result.append("[sqlState=").append(state != null && state.matches("[A-Za-z0-9]{1,8}") ? state : "unknown") + .append(",vendorCode=").append(sql.getErrorCode()).append(']'); + } + StackTraceElement[] frames = error.getStackTrace(); + for (int index = 0; index < Math.min(frames.length, 5); index++) { + result.append(" at ").append(frames[index]); + } + } + return result.toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalErrors.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalErrors.java index e8b0d39..f99b895 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalErrors.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalErrors.java @@ -10,6 +10,7 @@ import org.springframework.web.bind.annotation.RestControllerAdvice; @RestControllerAdvice(basePackageClasses = RentalController.class) @org.springframework.core.annotation.Order(org.springframework.core.Ordered.HIGHEST_PRECEDENCE) public class RentalErrors { + private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(RentalErrors.class); @ExceptionHandler(IllegalArgumentException.class) public AjaxResult invalid(IllegalArgumentException exception) { return AjaxResult.error(400, exception.getMessage()); @@ -22,6 +23,7 @@ public class RentalErrors { @ExceptionHandler(DataAccessException.class) public AjaxResult database(DataAccessException exception) { + LOG.error("租赁数据库异常 diagnostic={}", RentalDiagnostics.describe(exception)); return AjaxResult.error(409, "租赁记录冲突或数据库结构未就绪,请核对状态后重试"); } @@ -32,6 +34,7 @@ public class RentalErrors { @ExceptionHandler(Exception.class) public AjaxResult unexpected(Exception exception) { + LOG.error("租赁未处理异常 diagnostic={}", RentalDiagnostics.describe(exception)); return AjaxResult.error(500, "租赁操作暂未完成,请保留业务编号并检查配置或运行状态"); } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalPaymentClient.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalPaymentClient.java index 5d51c88..032f30a 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalPaymentClient.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalPaymentClient.java @@ -19,6 +19,7 @@ import com.ruoyi.system.service.PaymentSignatureService; /** 支付HTTP适配器:复用项目混合加密SDK;不允许重定向携带支付认证材料。 */ @Component public class RentalPaymentClient { + private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(RentalPaymentClient.class); private final ObjectMapper json; private final RentalPaymentProperties properties; private final ResourceLoader resources; @@ -28,6 +29,11 @@ public class RentalPaymentClient { this.resources = resources; } public String publicKey(RentalPaymentProperties.Channel channel) throws Exception { + // 不打印资源路径;配置误填密钥正文或含口令URL时同样不会泄露。 + String location = channel.getRsaPublicKeyLocation(); + LOG.info("支付公钥资源检查 configured={} fileResource={} classpathResource={}", + location != null && !location.isEmpty(), location != null && location.startsWith("file:"), + location != null && location.startsWith("classpath:")); try (InputStream input = resources.getResource(channel.getRsaPublicKeyLocation()).getInputStream()) { java.io.ByteArrayOutputStream output = new java.io.ByteArrayOutputStream(); byte[] buffer = new byte[1024]; @@ -61,8 +67,14 @@ public class RentalPaymentClient { .retryOnConnectionFailure(false).build(); Request request = new Request.Builder().url(text(order, "payment_base_url") + "/api/v1/order/" + operation) .post(RequestBody.create(MediaType.parse("application/json"), json.writeValueAsString(encrypted))).build(); + long started = System.nanoTime(); + LOG.info("充值支付请求开始 topupNo={} network={} operation={}", text(order, "topup_no"), text(order, "network"), operation); try (Response response = client.newCall(request).execute()) { + LOG.info("充值支付HTTP响应 topupNo={} operation={} httpStatus={} elapsedMs={}", + text(order, "topup_no"), operation, response.code(), TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)); Map result = json.readValue(RentalHttp.body(response), new TypeReference>() { }); + LOG.info("充值支付业务响应 topupNo={} operation={} businessCode={} dataObject={}", + text(order, "topup_no"), operation, number(result, "code"), result.get("data") instanceof Map); require(number(result, "code") == 200 && result.get("data") instanceof Map, "支付请求未成功,请稍后核对"); return (Map) result.get("data"); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalTopups.java b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalTopups.java index f9ec8bc..489199c 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalTopups.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalTopups.java @@ -17,6 +17,7 @@ import static com.ruoyi.system.rental.RentalValues.*; */ @Service public class RentalTopups { + private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(RentalTopups.class); private final RentalStore store; private final RentalFunds funds; private final RentalChain chain; @@ -35,11 +36,21 @@ public class RentalTopups { } public Map create(long user, Map request) throws Exception { + String diagnosticId = UUID.randomUUID().toString().replace("-", ""); + String stage = "REQUEST_VALIDATION"; + LOG.info("充值创建开始 diagnosticId={} userId={}", diagnosticId, user); + try { String network = network(input(request, "network", 16)); String clientNo = input(request, "client_request_no", 64); BigDecimal value = money(request.get("amount")); require(value.signum() > 0 && value.stripTrailingZeros().scale() <= 2, "充值金额必须为正数且最多两位小数"); RentalPaymentProperties.Channel channel = config.channel(network); + stage = "CHANNEL_CONFIG"; + LOG.info("充值通道检查 diagnosticId={} network={} enabled={} channelEnabled={} apiKeyConfigured={} apiSecretConfigured={} publicKeyConfigured={}", + diagnosticId, network, config.isEnabled(), channel.isEnabled(), + channel.getApiKey() != null && !channel.getApiKey().isEmpty(), + channel.getApiSecret() != null && !channel.getApiSecret().isEmpty(), + channel.getRsaPublicKeyLocation() != null && !channel.getRsaPublicKeyLocation().isEmpty()); require(config.isEnabled() && channel.isEnabled(), "该网络暂未启用在线充值"); require(value.compareTo(channel.getMinAmount()) >= 0 && value.compareTo(channel.getMaxAmount()) <= 0, "充值金额超出通道允许范围"); @@ -52,7 +63,11 @@ public class RentalTopups { && notify.getUserInfo() == null && notify.getQuery() == null && notify.getFragment() == null && channel.getNotifyUrl().length() <= 128, "支付回调地址配置无效"); require(!channel.getApiKey().isEmpty() && !channel.getApiSecret().isEmpty(), "支付通道缺少应用凭证"); + stage = "PUBLIC_KEY_LOAD"; + LOG.info("充值公钥加载开始 diagnosticId={}", diagnosticId); String pem = payment.publicKey(channel); + LOG.info("充值公钥加载通过 diagnosticId={}", diagnosticId); + stage = "LOCAL_ORDER_TRANSACTION"; Map saved = tx.execute(status -> { Map account = store.one("SELECT * FROM rent_account WHERE user_id=? AND network=? FOR UPDATE", user, network); require(account != null && "ACTIVE".equals(text(account, "status")), "请先开通正常的网络资金账户"); @@ -69,8 +84,16 @@ public class RentalTopups { "notify_url", channel.getNotifyUrl(), "status", "CREATING", "next_query_at", now())); return store.get("topup_order", id, false); }); + LOG.info("充值本地单已就绪 diagnosticId={} topupNo={} network={}", diagnosticId, text(saved, "topup_no"), network); + stage = "PAYMENT_RECONCILE"; reconcile(number(saved, "id")); + stage = "DETAIL_RESPONSE"; return detail(user, text(saved, "topup_no")); + } catch (Exception exception) { + LOG.error("充值创建失败 diagnosticId={} userId={} stage={} diagnostic={}", + diagnosticId, user, stage, RentalDiagnostics.describe(exception)); + throw exception; + } } public Map detail(long user, String no) { @@ -132,6 +155,7 @@ public class RentalTopups { } public void reconcile(long id) { + String stage = "ORDER_LOAD"; // 一个HTTP请求最多30秒,租约180秒覆盖创建/查询及有界链上核验。 String lease = UUID.randomUUID().toString().replace("-", ""); if (store.execute("UPDATE rent_topup_order SET lease_token=?,next_query_at=?,query_attempts=query_attempts+1 WHERE id=? AND next_query_at<=? AND status IN ('CREATING','CREATE_UNKNOWN','WAITING_PAYMENT','VERIFYING')", @@ -139,7 +163,9 @@ public class RentalTopups { try { Map order = store.get("topup_order", id, false); if (text(order, "payment_trade_id").isEmpty()) { + stage = "PAYMENT_CREATE"; Map created = payment.call(order, "create-transaction"); + stage = "PAYMENT_CREATE_RESPONSE_VALIDATE"; require(text(order, "topup_no").equals(text(created, "order_id")), "支付订单号不符"); require(amount(created, "payment_amount").compareTo(amount(order, "requested_amount")) == 0, "支付实际金额不符"); RentalOrders.address(input(created, "payment_address", 64)); @@ -159,6 +185,7 @@ public class RentalTopups { }); order = store.get("topup_order", id, false); } + stage = "PAYMENT_QUERY"; Map result = payment.call(order, "query"); if (!text(order, "topup_no").equals(text(result, "order_id")) || !text(order, "payment_trade_id").equals(text(result, "trade_id")) @@ -178,9 +205,11 @@ public class RentalTopups { } updateOwned(id, lease, map("status", "VERIFYING")); String txId = input(result, "transaction_id", 64); + stage = "CHAIN_VERIFY"; Map proof = chain.paymentTransfer(text(order, "network"), txId, text(order, "payment_address"), amount(order, "payment_amount"), time(order.get("created_at")).toEpochMilli(), time(order.get("expires_at")).toEpochMilli()); + stage = "LEDGER_CREDIT"; tx.execute(status -> { Map current = store.get("topup_order", id, true); require(lease.equals(text(current, "lease_token")), "充值核对租约已被接管"); @@ -188,6 +217,7 @@ public class RentalTopups { return null; }); } catch (Exception exception) { + LOG.warn("充值核对失败 orderId={} stage={} diagnostic={}", id, stage, RentalDiagnostics.describe(exception)); // 不输出支付响应、配置、签名或异常原文;保留原单号用于后台补偿。 Map row = store.get("topup_order", id, false); if (!Arrays.asList("CREDITED", "MANUAL_REVIEW", "EXPIRED").contains(text(row, "status"))) { @@ -238,6 +268,7 @@ public class RentalTopups { store.update("topup_order", id, map("status", "CREDITED", "credited_amount", value, "credited_at", now(), "transaction_id", txId.toLowerCase(Locale.ROOT), "log_index", number(proof, "log_index"), "last_error", null)); store.execute("UPDATE rent_topup_notify SET status='DONE',updated_at=? WHERE topup_no=?", now(), text(row, "topup_no")); + LOG.info("充值入账完成 topupNo={} accountId={} network={}", text(row, "topup_no"), row.get("account_id"), text(row, "network")); return null; }); } diff --git a/ruoyi-system/src/test/java/com/ruoyi/system/rental/RentalTopupTest.java b/ruoyi-system/src/test/java/com/ruoyi/system/rental/RentalTopupTest.java index f2c9a3a..1589045 100644 --- a/ruoyi-system/src/test/java/com/ruoyi/system/rental/RentalTopupTest.java +++ b/ruoyi-system/src/test/java/com/ruoyi/system/rental/RentalTopupTest.java @@ -18,6 +18,16 @@ import org.springframework.transaction.support.TransactionTemplate; /** 隔离MySQL兼容DDL与真实事务测试;支付和链上适配器可控,不访问真实账户或广播。 */ public class RentalTopupTest { + @Test public void diagnosticSummaryIncludesCauseAndLocationWithoutSensitiveMessages() { + Exception failure = new Exception("secret-top-level", new java.sql.SQLException("secret-sql-parameters", "42S22", 1054)); + String diagnostic = RentalDiagnostics.describe(failure); + assertTrue(diagnostic.contains("java.sql.SQLException")); + assertTrue(diagnostic.contains("sqlState=42S22")); + assertTrue(diagnostic.contains("vendorCode=1054")); + assertTrue(diagnostic.contains("RentalTopupTest")); + assertFalse(diagnostic.contains("secret-top-level")); + assertFalse(diagnostic.contains("secret-sql-parameters")); + } private static final String ADDRESS = "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf"; private static final String HASH = String.join("", Collections.nCopies(64, "a")); private RentalStore store;