新增接口
This commit is contained in:
1 parent
a2be79377b
commit
8ebf5f383d
6 files changed
+487
-40
No files matched your search
@@ -1,63 +1,66 @@
|
||||
package com.ruoyi.system.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.ruoyi.common.annotation.Log;
|
||||
import com.ruoyi.common.core.domain.AjaxResult;
|
||||
import com.ruoyi.common.enums.BusinessType;
|
||||
import com.ruoyi.system.domain.AppApiKeysPlus;
|
||||
import com.ruoyi.system.domain.UsdtOrdersPlus;
|
||||
import com.ruoyi.system.service.IAppApiKeysService;
|
||||
import com.ruoyi.system.service.IUsdtOrdersService;
|
||||
import com.ruoyi.system.service.PaymentSignatureService;
|
||||
import com.ruoyi.system.service.AppPrivateKeyCipher;
|
||||
import com.ruoyi.system.domain.dto.EncryptedRequest;
|
||||
import com.ruoyi.system.domain.vo.DecryptResult;
|
||||
import com.ruoyi.system.service.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.math.BigDecimal;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.net.URI;
|
||||
import java.util.Date;
|
||||
|
||||
/** 对外支付 API,统一使用 JSON 和签名校验。 */
|
||||
/**
|
||||
* 对外支付 API,统一使用 JSON 和签名校验。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/order")
|
||||
public class PaymentApiController {
|
||||
@Autowired private IAppApiKeysService keys;
|
||||
@Autowired private IUsdtOrdersService orders;
|
||||
@Autowired private StringRedisTemplate redis;
|
||||
@Autowired private AppPrivateKeyCipher privateKeyCipher;
|
||||
@Autowired
|
||||
private IAppApiKeysService keys;
|
||||
@Autowired
|
||||
private IUsdtOrdersService orders;
|
||||
@Autowired
|
||||
private AppPrivateKeyCipher privateKeyCipher;
|
||||
@Autowired
|
||||
private ApiSecurityService apiSecurityService;
|
||||
@Autowired
|
||||
private PaymentOrderOpenApiService paymentOrderOpenApiService;
|
||||
|
||||
@Log(title = "开放 API 创建支付订单", businessType = BusinessType.INSERT,
|
||||
isSaveRequestData = false, isSaveResponseData = false)
|
||||
@PostMapping("/create-transaction")
|
||||
public AjaxResult create(@RequestBody Map<String, Object> body) {
|
||||
String signature = String.valueOf(body.get("signature"));
|
||||
Long appId = parseLong(body.get("app_id"));
|
||||
AppApiKeysPlus key = activeKey(appId, body.get("api_key"));
|
||||
if (key == null || !PaymentSignatureService.verify(body, privateKeyCipher.decryptCredentialSecret(key.getApiSecret()), signature)) return AjaxResult.error("签名无效");
|
||||
String orderId = String.valueOf(body.get("order_id"));
|
||||
if (orderId.length() == 0 || orderId.length() > 32 || body.get("amount") == null || body.get("wallet_user_name") == null) return AjaxResult.error("缺少必要参数");
|
||||
if (!validUrl(body.get("notify_url")) || (body.get("redirect_url") != null && !validUrl(body.get("redirect_url")))) return AjaxResult.error("回调地址无效");
|
||||
UsdtOrdersPlus order = new UsdtOrdersPlus();
|
||||
order.setTradeId(UUID.randomUUID().toString().replace("-", "")); order.setOrderId(orderId);
|
||||
order.setToken(String.valueOf(body.get("payment_address")));
|
||||
order.setAmount(new BigDecimal(String.valueOf(body.get("amount")))); order.setActualAmount(order.getAmount());
|
||||
String lockKey = "payment:slot:" + appId + ":" + order.getToken() + ":" + order.getActualAmount().toPlainString();
|
||||
if (!Boolean.TRUE.equals(redis.opsForValue().setIfAbsent(lockKey, order.getTradeId(), 30, TimeUnit.MINUTES))) return AjaxResult.error("该金额已有待支付订单");
|
||||
order.setStatus(1L); order.setCallbackConfirm(2L); order.setAppId(appId); order.setUserId(key.getUserId());
|
||||
order.setNotifyUrl(String.valueOf(body.get("notify_url"))); order.setRedirectUrl(body.get("redirect_url") == null ? null : String.valueOf(body.get("redirect_url")));
|
||||
orders.save(order);
|
||||
Map<String, Object> result = new HashMap<String, Object>(); result.put("order_id", orderId); result.put("trade_id", order.getTradeId()); result.put("payment_amount", order.getActualAmount()); result.put("payment_address", order.getToken());
|
||||
return AjaxResult.success(result);
|
||||
public AjaxResult create(@RequestBody EncryptedRequest request) {
|
||||
DecryptResult decrypted = apiSecurityService.decryptAndVerify(request);
|
||||
return AjaxResult.success(paymentOrderOpenApiService.createOrder(decrypted));
|
||||
}
|
||||
|
||||
@PostMapping("/query")
|
||||
public AjaxResult query(@RequestBody Map<String, Object> body) {
|
||||
Long appId = parseLong(body.get("app_id")); AppApiKeysPlus key = activeKey(appId, body.get("api_key")); String signature = String.valueOf(body.get("signature"));
|
||||
if (key == null || !PaymentSignatureService.verify(body, privateKeyCipher.decryptCredentialSecret(key.getApiSecret()), signature)) return AjaxResult.error("签名无效");
|
||||
Long appId = parseLong(body.get("app_id"));
|
||||
AppApiKeysPlus key = activeKey(appId, body.get("api_key"));
|
||||
String signature = String.valueOf(body.get("signature"));
|
||||
if (key == null || !PaymentSignatureService.verify(body, privateKeyCipher.decryptCredentialSecret(key.getApiSecret()), signature))
|
||||
return AjaxResult.error("签名无效");
|
||||
UsdtOrdersPlus order = orders.getOne(new LambdaQueryWrapper<UsdtOrdersPlus>().eq(UsdtOrdersPlus::getAppId, appId).eq(UsdtOrdersPlus::getOrderId, String.valueOf(body.get("order_id"))));
|
||||
if (order == null) return AjaxResult.error("订单不存在");
|
||||
Map<String, Object> result = new HashMap<String, Object>(); result.put("order_id", order.getOrderId()); result.put("trade_id", order.getTradeId()); result.put("status", order.getStatus()); result.put("transaction_id", order.getBlockTransactionId()); return AjaxResult.success(result);
|
||||
Map<String, Object> result = new HashMap<String, Object>();
|
||||
result.put("order_id", order.getOrderId());
|
||||
result.put("trade_id", order.getTradeId());
|
||||
result.put("status", order.getStatus());
|
||||
result.put("transaction_id", order.getBlockTransactionId());
|
||||
return AjaxResult.success(result);
|
||||
}
|
||||
|
||||
private AppApiKeysPlus activeKey(Long appId, Object apiKey) {
|
||||
if (appId == null || apiKey == null || String.valueOf(apiKey).trim().isEmpty()) return null;
|
||||
return keys.getOne(new LambdaQueryWrapper<AppApiKeysPlus>().eq(AppApiKeysPlus::getAppId, appId)
|
||||
@@ -65,6 +68,12 @@ public class PaymentApiController {
|
||||
.isNull(AppApiKeysPlus::getDeletedAt)
|
||||
.and(wrapper -> wrapper.isNull(AppApiKeysPlus::getExpiredAt).or().gt(AppApiKeysPlus::getExpiredAt, new Date())));
|
||||
}
|
||||
private Long parseLong(Object value) { try { return value == null ? null : Long.valueOf(String.valueOf(value)); } catch (Exception ex) { return null; } }
|
||||
private boolean validUrl(Object value) { try { if (value == null) return false; URI uri = new URI(String.valueOf(value)); return ("https".equalsIgnoreCase(uri.getScheme()) || "http".equalsIgnoreCase(uri.getScheme())) && uri.getHost() != null; } catch (Exception ex) { return false; } }
|
||||
|
||||
private Long parseLong(Object value) {
|
||||
try {
|
||||
return value == null ? null : Long.valueOf(String.valueOf(value));
|
||||
} catch (Exception ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.ruoyi.system.domain.vo;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
|
||||
/** 开放 API 创建支付订单响应。 */
|
||||
public class PaymentOrderCreateResult {
|
||||
@JsonProperty("order_id")
|
||||
private String orderId;
|
||||
@JsonProperty("trade_id")
|
||||
private String tradeId;
|
||||
@JsonProperty("payment_address")
|
||||
private String paymentAddress;
|
||||
@JsonProperty("payment_amount")
|
||||
private BigDecimal paymentAmount;
|
||||
@JsonProperty("expiration_time")
|
||||
private Date expirationTime;
|
||||
|
||||
public PaymentOrderCreateResult(String orderId, String tradeId, String paymentAddress,
|
||||
BigDecimal paymentAmount, Date expirationTime) {
|
||||
this.orderId = orderId;
|
||||
this.tradeId = tradeId;
|
||||
this.paymentAddress = paymentAddress;
|
||||
this.paymentAmount = paymentAmount;
|
||||
this.expirationTime = expirationTime;
|
||||
}
|
||||
|
||||
public String getOrderId() { return orderId; }
|
||||
public String getTradeId() { return tradeId; }
|
||||
public String getPaymentAddress() { return paymentAddress; }
|
||||
public BigDecimal getPaymentAmount() { return paymentAmount; }
|
||||
public Date getExpirationTime() { return expirationTime; }
|
||||
}
|
||||
@@ -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