添加比率

This commit is contained in:
lu7213 committed 2026-10-10 11:36:20 -04:00
1 parent 5be292c009
commit c0868f9d8f
4 files changed
+62 -4

No files matched your search

@@ -135,6 +135,8 @@ token:
# 商户 RSA 私钥加密主密钥。生产环境必须通过环境变量注入,长度至少 32 位。 # 商户 RSA 私钥加密主密钥。生产环境必须通过环境变量注入,长度至少 32 位。
payment: payment:
apps-private-key-encryption-key: ${APP_PRIVATE_KEY_ENCRYPTION_KEY:} apps-private-key-encryption-key: ${APP_PRIVATE_KEY_ENCRYPTION_KEY:}
# 1 USDT 对应的业务货币金额;订单实际支付 USDT = amount / 此汇率,向下保留 2 位。
usdt-exchange-rate: ${USDT_EXCHANGE_RATE:1}
# MyBatis配置 # MyBatis配置
mybatis: mybatis:
@@ -12,6 +12,7 @@ import com.ruoyi.system.mapper.AppsMapper;
import com.ruoyi.system.mapper.UsdtOrdersMapper; import com.ruoyi.system.mapper.UsdtOrdersMapper;
import com.ruoyi.system.mapper.WalletAddressMapper; import com.ruoyi.system.mapper.WalletAddressMapper;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,6 +21,7 @@ import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionSynchronizationManager;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URI; import java.net.URI;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@@ -50,6 +52,9 @@ public class PaymentOrderOpenApiService {
@Autowired private WalletAddressMapper walletAddressMapper; @Autowired private WalletAddressMapper walletAddressMapper;
@Autowired private UsdtOrdersMapper ordersMapper; @Autowired private UsdtOrdersMapper ordersMapper;
@Autowired private StringRedisTemplate redisTemplate; @Autowired private StringRedisTemplate redisTemplate;
/** 1 USDT 对应的业务货币金额,例如 7.20 表示 1 USDT = 7.20 业务货币。 */
@Value("${payment.usdt-exchange-rate:1}")
private BigDecimal usdtExchangeRate;
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public PaymentOrderCreateResult createOrder(DecryptResult request) { public PaymentOrderCreateResult createOrder(DecryptResult request) {
@@ -59,6 +64,7 @@ public class PaymentOrderOpenApiService {
String notifyUrl = required(parameters, "notify_url"); String notifyUrl = required(parameters, "notify_url");
String redirectUrl = trimToNull(parameters.get("redirect_url")); String redirectUrl = trimToNull(parameters.get("redirect_url"));
BigDecimal amount = parseAmount(required(parameters, "amount")); BigDecimal amount = parseAmount(required(parameters, "amount"));
BigDecimal actualAmount = convertToUsdt(amount);
validate(orderId, walletUserName, notifyUrl, redirectUrl); validate(orderId, walletUserName, notifyUrl, redirectUrl);
// 锁定应用,使同一应用下的钱包领取和商户订单幂等检查串行执行。 // 锁定应用,使同一应用下的钱包领取和商户订单幂等检查串行执行。
@@ -84,9 +90,9 @@ public class PaymentOrderOpenApiService {
Date now = DateUtils.getNowDate(); Date now = DateUtils.getNowDate();
String tradeId = UUID.randomUUID().toString().replace("-", ""); String tradeId = UUID.randomUUID().toString().replace("-", "");
String slotKey = slotKey(request.getAppId(), wallet.getToken(), amount); String slotKey = slotKey(request.getAppId(), wallet.getToken(), actualAmount);
UsdtOrdersPlus previousOrder = expirePreviousSlotOrder( UsdtOrdersPlus previousOrder = expirePreviousSlotOrder(
request.getAppId(), wallet.getToken(), amount, slotKey, now); request.getAppId(), wallet.getToken(), actualAmount, slotKey, now);
if (!Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent( if (!Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(
slotKey, tradeId, ORDER_TTL_MILLIS, TimeUnit.MILLISECONDS))) { slotKey, tradeId, ORDER_TTL_MILLIS, TimeUnit.MILLISECONDS))) {
throw new CustomException("该收款地址和金额已有待支付订单,请稍后重试"); throw new CustomException("该收款地址和金额已有待支付订单,请稍后重试");
@@ -97,7 +103,7 @@ public class PaymentOrderOpenApiService {
order.setTradeId(tradeId); order.setTradeId(tradeId);
order.setOrderId(orderId); order.setOrderId(orderId);
order.setAmount(amount); order.setAmount(amount);
order.setActualAmount(amount); order.setActualAmount(actualAmount);
order.setToken(wallet.getToken()); order.setToken(wallet.getToken());
order.setStatus(1L); order.setStatus(1L);
order.setNotifyUrl(notifyUrl); order.setNotifyUrl(notifyUrl);
@@ -232,6 +238,28 @@ public class PaymentOrderOpenApiService {
} }
} }
/**
* 将商户业务金额转换为应支付 USDT。
* 按支付契约向下保留两位,避免四舍五入导致用户多支付。
*/
private BigDecimal convertToUsdt(BigDecimal amount) {
return calculateActualAmount(amount, usdtExchangeRate);
}
static BigDecimal calculateActualAmount(BigDecimal amount, BigDecimal exchangeRate) {
if (exchangeRate == null || exchangeRate.signum() <= 0) {
throw new CustomException("USDT 兑换汇率配置无效");
}
BigDecimal actualAmount = amount.divide(exchangeRate, 2, RoundingMode.DOWN);
if (actualAmount.signum() <= 0) {
throw new CustomException("amount 按当前汇率换算后不足 0.01 USDT");
}
if (actualAmount.precision() > 19) {
throw new CustomException("amount 按当前汇率换算后超出金额范围");
}
return actualAmount;
}
private String required(Map<String, String> values, String name) { private String required(Map<String, String> values, String name) {
String value = trimToNull(values.get(name)); String value = trimToNull(values.get(name));
if (value == null) throw new CustomException(name + " 不能为空"); if (value == null) throw new CustomException(name + " 不能为空");
@@ -34,7 +34,7 @@ public class HybridCryptoTest {
// String apiUrl = requiredEnv("PAYMENT_API_URL"); // String apiUrl = requiredEnv("PAYMENT_API_URL");
// String apiKey = requiredEnv("PAYMENT_API_KEY"); // String apiKey = requiredEnv("PAYMENT_API_KEY");
// String apiSecret = requiredEnv("PAYMENT_API_SECRET"); // String apiSecret = requiredEnv("PAYMENT_API_SECRET");
String apiUrl = "http://192.168.3.103:2020/api/v1/wallet/create"; String apiUrl = "http://192.168.3.103:2020/api/v1/order/create-transaction";
String apiKey = "ak_YhWdZaB7NsMy_lKkjQgn0WtB_FML1zyr"; String apiKey = "ak_YhWdZaB7NsMy_lKkjQgn0WtB_FML1zyr";
String apiSecret = "7u3mhxNmqJVIr1cUiwLP_THiCjeBQZfaEG8FABCTgu4"; String apiSecret = "7u3mhxNmqJVIr1cUiwLP_THiCjeBQZfaEG8FABCTgu4";
String publicKey = "-----BEGIN PUBLIC KEY-----\n" + String publicKey = "-----BEGIN PUBLIC KEY-----\n" +
@@ -0,0 +1,28 @@
package com.ruoyi.system.service;
import com.ruoyi.common.exception.CustomException;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
/** 支付订单业务金额与 USDT 实付金额换算测试。 */
public class PaymentOrderOpenApiServiceTest {
@Test
public void shouldDivideByExchangeRateAndRoundDown() {
BigDecimal result = PaymentOrderOpenApiService.calculateActualAmount(
new BigDecimal("100"), new BigDecimal("7.2"));
Assert.assertEquals(new BigDecimal("13.88"), result);
}
@Test(expected = CustomException.class)
public void shouldRejectAmountBelowMinimumAfterConversion() {
PaymentOrderOpenApiService.calculateActualAmount(
new BigDecimal("0.01"), new BigDecimal("7.2"));
}
@Test(expected = CustomException.class)
public void shouldRejectInvalidExchangeRate() {
PaymentOrderOpenApiService.calculateActualAmount(BigDecimal.ONE, BigDecimal.ZERO);
}
}