diff --git a/ruoyi-admin/src/main/java/com/ruoyi/task/TronPaymentTask.java b/ruoyi-admin/src/main/java/com/ruoyi/task/TronPaymentTask.java index cae290f..f87ad43 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/task/TronPaymentTask.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/task/TronPaymentTask.java @@ -7,8 +7,8 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.ruoyi.system.domain.UsdtOrdersPlus; import com.ruoyi.system.service.ITronService; import com.ruoyi.system.service.IUsdtOrdersService; -import com.ruoyi.system.service.WalletLedgerPostingService; import com.ruoyi.system.service.TronServiceProvider; +import com.ruoyi.system.service.WalletLedgerPostingService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -18,6 +18,7 @@ import org.springframework.web.client.RestTemplate; import java.math.BigDecimal; import java.math.RoundingMode; +import java.util.Date; /** * 轮询已确认 TRC20 转账,按地址、六位金额和唯一交易哈希入账。 @@ -25,6 +26,9 @@ import java.math.RoundingMode; @Component public class TronPaymentTask { private static final Logger log = LoggerFactory.getLogger(TronPaymentTask.class); + private static final long ORDER_TTL_MILLIS = 10L * 60L * 1000L; + /** 仅放宽订单开始时间,兼容应用服务器与 TRON 节点之间的轻微时钟偏差。 */ + private static final long CLOCK_SKEW_MILLIS = 5L * 1000L; @Autowired private IUsdtOrdersService orders; @@ -34,7 +38,7 @@ public class TronPaymentTask { private WalletLedgerPostingService ledgerPostingService; private final RestTemplate http = new RestTemplate(); - @Scheduled(fixedDelay = 30000L) + @Scheduled(fixedDelay = 10000L) public void scan() { ITronService tron; try { @@ -53,6 +57,8 @@ public class TronPaymentTask { for (int i = 0; i < data.size(); i++) { JSONObject tx = data.getJSONObject(i); if (!order.getToken().equals(tx.getString("to"))) continue; + long transactionTime = tx.getLongValue("block_timestamp"); + if (!isTransactionInPaymentWindow(order.getCreatedAt(), transactionTime)) continue; BigDecimal value = new BigDecimal(tx.getString("value")).movePointLeft(6).setScale(6, RoundingMode.DOWN); if (value.compareTo(order.getActualAmount().setScale(6, RoundingMode.DOWN)) != 0) continue; String hash = tx.getString("transaction_id"); @@ -63,9 +69,24 @@ public class TronPaymentTask { } } catch (Exception e) { // 单笔订单查询失败不能中断其他订单,日志中禁止输出凭证和钱包私钥。 + log.error(e.getMessage(), e); log.warn("查询 TRON 支付交易失败,订单ID={},网络={}", order.getId(), tron.type()); } } } + /** + * 链上交易必须发生在订单有效期内,防止同地址、同金额的历史转账命中新订单。 + * 截止时间不增加容差,避免订单过期后的付款被自动确认。 + */ + static boolean isTransactionInPaymentWindow(Date orderCreatedAt, long transactionTime) { + if (orderCreatedAt == null || transactionTime <= 0L) { + return false; + } + long createdAt = orderCreatedAt.getTime(); + long validFrom = createdAt - CLOCK_SKEW_MILLIS; + long validUntil = createdAt + ORDER_TTL_MILLIS; + return transactionTime >= validFrom && transactionTime <= validUntil; + } + } diff --git a/ruoyi-admin/src/test/java/com/ruoyi/task/TronPaymentTaskTest.java b/ruoyi-admin/src/test/java/com/ruoyi/task/TronPaymentTaskTest.java new file mode 100644 index 0000000..df954a2 --- /dev/null +++ b/ruoyi-admin/src/test/java/com/ruoyi/task/TronPaymentTaskTest.java @@ -0,0 +1,40 @@ +package com.ruoyi.task; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.Date; + +/** 支付扫描链上交易时间窗口边界测试。 */ +public class TronPaymentTaskTest { + private static final long CREATED_AT = 1_700_000_000_000L; + + @Test + public void shouldAcceptTransactionInsidePaymentWindow() { + Assert.assertTrue(TronPaymentTask.isTransactionInPaymentWindow( + new Date(CREATED_AT), CREATED_AT + 60_000L)); + } + + @Test + public void shouldAllowFiveSecondsClockSkewBeforeCreation() { + Assert.assertTrue(TronPaymentTask.isTransactionInPaymentWindow( + new Date(CREATED_AT), CREATED_AT - 5_000L)); + Assert.assertFalse(TronPaymentTask.isTransactionInPaymentWindow( + new Date(CREATED_AT), CREATED_AT - 5_001L)); + } + + @Test + public void shouldRejectTransactionAfterExpiration() { + Assert.assertTrue(TronPaymentTask.isTransactionInPaymentWindow( + new Date(CREATED_AT), CREATED_AT + 10L * 60L * 1000L)); + Assert.assertFalse(TronPaymentTask.isTransactionInPaymentWindow( + new Date(CREATED_AT), CREATED_AT + 10L * 60L * 1000L + 1L)); + } + + @Test + public void shouldRejectMissingTime() { + Assert.assertFalse(TronPaymentTask.isTransactionInPaymentWindow(null, CREATED_AT)); + Assert.assertFalse(TronPaymentTask.isTransactionInPaymentWindow( + new Date(CREATED_AT), 0L)); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/PaymentOrderOpenApiService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/PaymentOrderOpenApiService.java index 495527f..7ec2f80 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/PaymentOrderOpenApiService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/PaymentOrderOpenApiService.java @@ -39,7 +39,7 @@ import java.util.regex.Pattern; /** 商户开放 API 创建支付订单业务。 */ @Service public class PaymentOrderOpenApiService { - private static final long ORDER_TTL_MILLIS = 30L * 60L * 1000L; + private static final long ORDER_TTL_MILLIS = 10L * 60L * 1000L; private static final Pattern PARAMETER_PATTERN = Pattern.compile( "(?:^|&)(amount|notify_url|order_id|redirect_url|walletUserName)="); private static final List REQUIRED_PARAMETERS = Arrays.asList( @@ -93,8 +93,7 @@ public class PaymentOrderOpenApiService { String slotKey = slotKey(request.getAppId(), wallet.getToken(), actualAmount); UsdtOrdersPlus previousOrder = expirePreviousSlotOrder( request.getAppId(), wallet.getToken(), actualAmount, slotKey, now); - if (!Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent( - slotKey, tradeId, ORDER_TTL_MILLIS, TimeUnit.MILLISECONDS))) { + if (!acquireSlot(slotKey, tradeId, request.getAppId(), wallet.getToken(), actualAmount)) { throw new CustomException("该收款地址和金额已有待支付订单,请稍后重试"); } restoreSlotAfterRollback(slotKey, tradeId, previousOrder); @@ -168,6 +167,50 @@ public class PaymentOrderOpenApiService { redisTemplate.execute(RELEASE_SCRIPT, Collections.singletonList(slotKey), tradeId); } + /** + * 获取金额槽位。若 Redis 中的 owner 已经不是待支付订单,则说明支付成功、过期处理或 + * 异常退出时遗留了旧键,可按 owner 原子删除后重试一次;仍有待支付订单时禁止抢占。 + */ + private boolean acquireSlot(String slotKey, String tradeId, Long appId, + String token, BigDecimal amount) { + if (Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent( + slotKey, tradeId, ORDER_TTL_MILLIS, TimeUnit.MILLISECONDS))) { + return true; + } + String ownerTradeId = redisTemplate.opsForValue().get(slotKey); + if (ownerTradeId == null) { + return Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent( + slotKey, tradeId, ORDER_TTL_MILLIS, TimeUnit.MILLISECONDS)); + } + if (hasPendingSlotOwner(ownerTradeId, appId, token, amount)) { + return false; + } + releaseSlot(slotKey, ownerTradeId); + return Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent( + slotKey, tradeId, ORDER_TTL_MILLIS, TimeUnit.MILLISECONDS)); + } + + private boolean hasPendingSlotOwner(String tradeId, Long appId, + String token, BigDecimal amount) { + return ordersMapper.selectCount(new LambdaQueryWrapper() + .eq(UsdtOrdersPlus::getTradeId, tradeId) + .eq(UsdtOrdersPlus::getAppId, appId) + .eq(UsdtOrdersPlus::getToken, token) + .eq(UsdtOrdersPlus::getActualAmount, amount) + .eq(UsdtOrdersPlus::getStatus, 1L) + .isNull(UsdtOrdersPlus::getDeletedAt)) > 0; + } + + /** 支付事务提交成功后释放对应金额槽位,owner 不匹配时不会删除其他订单的锁。 */ + public void releasePaidOrderSlot(UsdtOrdersPlus order) { + if (order == null || order.getAppId() == null || order.getToken() == null + || order.getActualAmount() == null || order.getTradeId() == null) { + return; + } + releaseSlot(slotKey(order.getAppId(), order.getToken(), order.getActualAmount()), + order.getTradeId()); + } + private String slotKey(Long appId, String token, BigDecimal amount) { return "payment:slot:" + appId + ":" + token + ":" + amount.toPlainString(); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/WalletLedgerPostingService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/WalletLedgerPostingService.java index 2605eca..fa3bdb1 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/WalletLedgerPostingService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/WalletLedgerPostingService.java @@ -16,6 +16,8 @@ import com.ruoyi.system.mapper.UsdtConfigMapper; import com.ruoyi.system.mapper.WalletAddressLedgerMapper; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; import java.util.Date; import java.math.BigDecimal; @@ -36,6 +38,7 @@ public class WalletLedgerPostingService { private final AppsMapper appsMapper; private final AppsBalanceLedgerMapper appsLedgerMapper; private final UsdtConfigMapper configMapper; + private final PaymentOrderOpenApiService paymentOrderOpenApiService; public WalletLedgerPostingService(UsdtOrdersMapper ordersMapper, WalletAddressLedgerMapper ledgerMapper, @@ -43,7 +46,8 @@ public class WalletLedgerPostingService { IUsdtAggregationTaskItemService aggregationItemService, AppsMapper appsMapper, AppsBalanceLedgerMapper appsLedgerMapper, - UsdtConfigMapper configMapper) { + UsdtConfigMapper configMapper, + PaymentOrderOpenApiService paymentOrderOpenApiService) { this.ordersMapper = ordersMapper; this.ledgerMapper = ledgerMapper; this.walletService = walletService; @@ -51,6 +55,7 @@ public class WalletLedgerPostingService { this.appsMapper = appsMapper; this.appsLedgerMapper = appsLedgerMapper; this.configMapper = configMapper; + this.paymentOrderOpenApiService = paymentOrderOpenApiService; } /** 将待支付订单结算为成功,同一订单重复扫描不会重复产生流水。 */ @@ -92,7 +97,25 @@ public class WalletLedgerPostingService { ledgerMapper.insertSystemLedgerIgnoreDuplicate(ledger); postOrderToAppBalance(order, transactionId, now); - return ordersMapper.markOrderPaid(order.getId(), transactionId, now) == 1; + if (ordersMapper.markOrderPaid(order.getId(), transactionId, now) != 1) { + return false; + } + releasePaymentSlotAfterCommit(order); + return true; + } + + /** 数据库确认支付事务提交后再释放 Redis 槽位,避免回滚时提前开放相同地址和金额。 */ + private void releasePaymentSlotAfterCommit(final UsdtOrdersPlus order) { + if (!TransactionSynchronizationManager.isSynchronizationActive()) { + paymentOrderOpenApiService.releasePaidOrderSlot(order); + return; + } + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCommit() { + paymentOrderOpenApiService.releasePaidOrderSlot(order); + } + }); } /**