新增接口
This commit is contained in:
1 parent
a2be79377b
commit
8ebf5f383d
6 files changed
+487
-40
No files matched your search
@@ -0,0 +1,245 @@
|
||||
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.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.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 = 30L * 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;
|
||||
|
||||
@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"));
|
||||
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(), amount);
|
||||
UsdtOrdersPlus previousOrder = expirePreviousSlotOrder(
|
||||
request.getAppId(), wallet.getToken(), amount, slotKey, now);
|
||||
if (!Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(
|
||||
slotKey, tradeId, ORDER_TTL_MILLIS, TimeUnit.MILLISECONDS))) {
|
||||
throw new CustomException("该收款地址和金额已有待支付订单,请稍后重试");
|
||||
}
|
||||
restoreSlotAfterRollback(slotKey, tradeId, previousOrder);
|
||||
|
||||
UsdtOrdersPlus order = new UsdtOrdersPlus();
|
||||
order.setTradeId(tradeId);
|
||||
order.setOrderId(orderId);
|
||||
order.setAmount(amount);
|
||||
order.setActualAmount(amount);
|
||||
order.setToken(wallet.getToken());
|
||||
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)
|
||||
.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);
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
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 格式错误");
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user