请添加日志输出定位排查。
This commit is contained in:
1 parent
e73f099734
commit
76f9e62253
6 files changed
+101
No files matched your search
@@ -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<Throwable> visited = java.util.Collections.newSetFromMap(
|
||||
new java.util.IdentityHashMap<Throwable, Boolean>());
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -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, "租赁操作暂未完成,请保留业务编号并检查配置或运行状态");
|
||||
}
|
||||
}
|
||||
@@ -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<String, Object> result = json.readValue(RentalHttp.body(response), new TypeReference<Map<String, Object>>() { });
|
||||
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<String, Object>) result.get("data");
|
||||
}
|
||||
|
||||
@@ -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<String, Object> create(long user, Map<String, Object> 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<String, Object> saved = tx.execute(status -> {
|
||||
Map<String, Object> 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<String, Object> 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<String, Object> order = store.get("topup_order", id, false);
|
||||
if (text(order, "payment_trade_id").isEmpty()) {
|
||||
stage = "PAYMENT_CREATE";
|
||||
Map<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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;
|
||||
});
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user