324 lines
15 KiB
Java
324 lines
15 KiB
Java
package com.ruoyi.system.service;
|
|
|
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
|
import com.ruoyi.common.exception.CustomException;
|
|
import com.ruoyi.common.utils.DateUtils;
|
|
import com.ruoyi.system.domain.Apps;
|
|
import com.ruoyi.system.domain.UsdtOrdersPlus;
|
|
import com.ruoyi.system.domain.WalletAddress;
|
|
import com.ruoyi.system.domain.vo.DecryptResult;
|
|
import com.ruoyi.system.domain.vo.PaymentOrderCreateResult;
|
|
import com.ruoyi.system.mapper.AppsMapper;
|
|
import com.ruoyi.system.mapper.UsdtOrdersMapper;
|
|
import com.ruoyi.system.mapper.WalletAddressMapper;
|
|
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.script.DefaultRedisScript;
|
|
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.math.BigDecimal;
|
|
import java.math.RoundingMode;
|
|
import java.net.URI;
|
|
import java.util.ArrayList;
|
|
import java.util.Arrays;
|
|
import java.util.Collections;
|
|
import java.util.Date;
|
|
import java.util.LinkedHashMap;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
import java.util.Objects;
|
|
import java.util.UUID;
|
|
import java.util.concurrent.TimeUnit;
|
|
import java.util.regex.Matcher;
|
|
import java.util.regex.Pattern;
|
|
|
|
/** 商户开放 API 创建支付订单业务。 */
|
|
@Service
|
|
public class PaymentOrderOpenApiService {
|
|
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<String> REQUIRED_PARAMETERS = Arrays.asList(
|
|
"amount", "notify_url", "order_id", "walletUserName");
|
|
private static final DefaultRedisScript<Long> RELEASE_SCRIPT = new DefaultRedisScript<Long>(
|
|
"if redis.call('get', KEYS[1]) == ARGV[1] then "
|
|
+ "return redis.call('del', KEYS[1]) else return 0 end", Long.class);
|
|
|
|
@Autowired private AppsMapper appsMapper;
|
|
@Autowired private WalletAddressMapper walletAddressMapper;
|
|
@Autowired private UsdtOrdersMapper ordersMapper;
|
|
@Autowired private StringRedisTemplate redisTemplate;
|
|
/** 1 USDT 对应的业务货币金额,例如 7.20 表示 1 USDT = 7.20 业务货币。 */
|
|
@Value("${payment.usdt-exchange-rate:1}")
|
|
private BigDecimal usdtExchangeRate;
|
|
/** 对外创建订单成功后返回的公共收银台入口。 */
|
|
@Value("${payment.checkout-url:http://192.168.3.103/public/usdtCheckout}")
|
|
private String checkoutUrl;
|
|
|
|
@Transactional(rollbackFor = Exception.class)
|
|
public PaymentOrderCreateResult createOrder(DecryptResult request) {
|
|
Map<String, String> parameters = parseParameters(request.getPlainData());
|
|
String orderId = required(parameters, "order_id");
|
|
String walletUserName = required(parameters, "walletUserName");
|
|
String notifyUrl = required(parameters, "notify_url");
|
|
String redirectUrl = trimToNull(parameters.get("redirect_url"));
|
|
BigDecimal amount = parseAmount(required(parameters, "amount"));
|
|
BigDecimal actualAmount = convertToUsdt(amount);
|
|
validate(orderId, walletUserName, notifyUrl, redirectUrl);
|
|
|
|
// 锁定应用,使同一应用下的钱包领取和商户订单幂等检查串行执行。
|
|
Apps app = appsMapper.selectAppsByIdForUpdate(request.getAppId());
|
|
if (app == null || !Integer.valueOf(1).equals(app.getStatus())
|
|
|| !Objects.equals(app.getUserId(), request.getUserId())) {
|
|
throw new CustomException("商户应用不可用");
|
|
}
|
|
UsdtOrdersPlus existingOrder = ordersMapper.selectOne(new LambdaQueryWrapper<UsdtOrdersPlus>()
|
|
.eq(UsdtOrdersPlus::getOrderId, orderId).last("limit 1"));
|
|
if (existingOrder != null) {
|
|
if (!Objects.equals(existingOrder.getAppId(), request.getAppId())) {
|
|
throw new CustomException("商户订单号已存在");
|
|
}
|
|
return result(existingOrder);
|
|
}
|
|
|
|
WalletAddress wallet = walletAddressMapper.selectByAppAndWalletUserName(
|
|
request.getAppId(), walletUserName);
|
|
if (wallet == null) {
|
|
wallet = allocateWallet(request, walletUserName);
|
|
}
|
|
|
|
Date now = DateUtils.getNowDate();
|
|
String tradeId = UUID.randomUUID().toString().replace("-", "");
|
|
String slotKey = slotKey(request.getAppId(), wallet.getToken(), actualAmount);
|
|
UsdtOrdersPlus previousOrder = expirePreviousSlotOrder(
|
|
request.getAppId(), wallet.getToken(), actualAmount, slotKey, now);
|
|
if (!acquireSlot(slotKey, tradeId, request.getAppId(), wallet.getToken(), actualAmount)) {
|
|
throw new CustomException("该收款地址和金额已有待支付订单,请稍后重试");
|
|
}
|
|
restoreSlotAfterRollback(slotKey, tradeId, previousOrder);
|
|
|
|
UsdtOrdersPlus order = new UsdtOrdersPlus();
|
|
order.setTradeId(tradeId);
|
|
order.setOrderId(orderId);
|
|
order.setAmount(amount);
|
|
order.setActualAmount(actualAmount);
|
|
order.setToken(wallet.getToken());
|
|
order.setWalletUserName(walletUserName);
|
|
order.setStatus(1L);
|
|
order.setNotifyUrl(notifyUrl);
|
|
order.setRedirectUrl(redirectUrl);
|
|
order.setCallbackNum(0L);
|
|
order.setCallbackConfirm(2L);
|
|
order.setCreatedAt(now);
|
|
order.setUpdatedAt(now);
|
|
order.setAppId(request.getAppId());
|
|
order.setUserId(request.getUserId());
|
|
order.setSettlementStatus(0);
|
|
order.setOrderType(0);
|
|
if (ordersMapper.insert(order) != 1) throw new CustomException("订单创建失败,请重试");
|
|
return result(order);
|
|
}
|
|
|
|
private WalletAddress allocateWallet(DecryptResult request, String walletUserName) {
|
|
WalletAddress available = walletAddressMapper.selectFirstAvailableForUpdate();
|
|
if (available == null) throw new CustomException("暂无可用钱包地址,请联系平台管理员补充子账号");
|
|
if (walletAddressMapper.bindAvailableWallet(available.getId(), request.getAppId(),
|
|
request.getUserId(), walletUserName, DateUtils.getNowDate()) != 1) {
|
|
throw new CustomException("钱包分配失败,请重试");
|
|
}
|
|
return available;
|
|
}
|
|
|
|
private UsdtOrdersPlus expirePreviousSlotOrder(Long appId, String token, BigDecimal amount,
|
|
String slotKey, Date now) {
|
|
UsdtOrdersPlus previous = ordersMapper.selectOne(new LambdaQueryWrapper<UsdtOrdersPlus>()
|
|
.eq(UsdtOrdersPlus::getAppId, appId).eq(UsdtOrdersPlus::getToken, token)
|
|
.eq(UsdtOrdersPlus::getActualAmount, amount).eq(UsdtOrdersPlus::getStatus, 1L)
|
|
.and(wrapper -> wrapper.isNull(UsdtOrdersPlus::getBlockTransactionId)
|
|
.or().eq(UsdtOrdersPlus::getBlockTransactionId, ""))
|
|
.isNull(UsdtOrdersPlus::getDeletedAt).orderByDesc(UsdtOrdersPlus::getId).last("limit 1"));
|
|
if (previous == null) return null;
|
|
previous.setStatus(3L);
|
|
previous.setUpdatedAt(now);
|
|
ordersMapper.updateById(previous);
|
|
releaseSlot(slotKey, previous.getTradeId());
|
|
return previous;
|
|
}
|
|
|
|
private void restoreSlotAfterRollback(final String slotKey, final String tradeId,
|
|
final UsdtOrdersPlus previousOrder) {
|
|
if (!TransactionSynchronizationManager.isSynchronizationActive()) return;
|
|
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
|
@Override
|
|
public void afterCompletion(int status) {
|
|
if (status == TransactionSynchronization.STATUS_COMMITTED) return;
|
|
releaseSlot(slotKey, tradeId);
|
|
if (previousOrder != null && previousOrder.getCreatedAt() != null) {
|
|
long expiresAt = previousOrder.getCreatedAt().getTime() + ORDER_TTL_MILLIS;
|
|
long remaining = expiresAt - System.currentTimeMillis();
|
|
if (remaining > 0) {
|
|
redisTemplate.opsForValue().setIfAbsent(
|
|
slotKey, previousOrder.getTradeId(), remaining, TimeUnit.MILLISECONDS);
|
|
}
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
private void releaseSlot(String slotKey, String tradeId) {
|
|
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<UsdtOrdersPlus>()
|
|
.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();
|
|
}
|
|
|
|
private PaymentOrderCreateResult result(UsdtOrdersPlus order) {
|
|
return new PaymentOrderCreateResult(order.getOrderId(), order.getTradeId(), order.getToken(),
|
|
order.getActualAmount(), new Date(order.getCreatedAt().getTime() + ORDER_TTL_MILLIS),
|
|
checkoutUrl+"?tradeId="+order.getTradeId());
|
|
}
|
|
|
|
private Map<String, String> parseParameters(String plainData) {
|
|
if (plainData == null || plainData.isEmpty() || !plainData.endsWith("&")) {
|
|
throw new CustomException("业务参数格式错误");
|
|
}
|
|
Matcher matcher = PARAMETER_PATTERN.matcher(plainData);
|
|
List<String> names = new ArrayList<String>();
|
|
List<Integer> valueStarts = new ArrayList<Integer>();
|
|
List<Integer> entryStarts = new ArrayList<Integer>();
|
|
while (matcher.find()) {
|
|
names.add(matcher.group(1));
|
|
valueStarts.add(matcher.end());
|
|
entryStarts.add(matcher.start());
|
|
}
|
|
if (names.isEmpty() || entryStarts.get(0) != 0) throw new CustomException("业务参数格式错误");
|
|
Map<String, String> values = new LinkedHashMap<String, String>();
|
|
for (int i = 0; i < names.size(); i++) {
|
|
int end = i + 1 < names.size() ? entryStarts.get(i + 1) : plainData.length() - 1;
|
|
if (values.put(names.get(i), plainData.substring(valueStarts.get(i), end)) != null) {
|
|
throw new CustomException("业务参数不能重复");
|
|
}
|
|
}
|
|
if (!values.keySet().containsAll(REQUIRED_PARAMETERS) || values.size() > 5) {
|
|
throw new CustomException("业务参数不完整或包含不支持的参数");
|
|
}
|
|
return values;
|
|
}
|
|
|
|
private void validate(String orderId, String walletUserName, String notifyUrl, String redirectUrl) {
|
|
if (orderId.length() > 32) throw new CustomException("order_id 长度不能超过 32");
|
|
if (walletUserName.length() > 256 || !walletUserName.matches("[A-Za-z0-9_.@:-]+")) {
|
|
throw new CustomException("walletUserName 格式错误");
|
|
}
|
|
validateUrl(notifyUrl, "notify_url");
|
|
if (redirectUrl != null) validateUrl(redirectUrl, "redirect_url");
|
|
}
|
|
|
|
private void validateUrl(String value, String name) {
|
|
if (value.length() > 128) throw new CustomException(name + " 长度不能超过 128");
|
|
try {
|
|
URI uri = new URI(value);
|
|
if (!("http".equalsIgnoreCase(uri.getScheme()) || "https".equalsIgnoreCase(uri.getScheme()))
|
|
|| uri.getHost() == null) throw new CustomException(name + " 格式错误");
|
|
} catch (CustomException e) {
|
|
throw e;
|
|
} catch (Exception e) {
|
|
throw new CustomException(name + " 格式错误");
|
|
}
|
|
}
|
|
|
|
private BigDecimal parseAmount(String value) {
|
|
try {
|
|
BigDecimal amount = new BigDecimal(value);
|
|
if (amount.signum() <= 0 || amount.scale() > 4 || amount.precision() > 19) {
|
|
throw new CustomException("amount 必须为正数且最多保留 4 位小数");
|
|
}
|
|
return amount;
|
|
} catch (NumberFormatException e) {
|
|
throw new CustomException("amount 格式错误");
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 将商户业务金额转换为应支付 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) {
|
|
String value = trimToNull(values.get(name));
|
|
if (value == null) throw new CustomException(name + " 不能为空");
|
|
return value;
|
|
}
|
|
|
|
private String trimToNull(String value) {
|
|
if (value == null || value.trim().isEmpty()) return null;
|
|
return value.trim();
|
|
}
|
|
}
|