创建充值单后立即调用 /api/v1/order/create-transaction。

成功后自动跳转 public/usdtCheckout?tradeId=...。
收银台按交易号展示网络、金额、二维码、地址及支付状态。
失败时显示处理阶段,支持使用原单重试,避免重复创建。
This commit is contained in:
lu7213 committed 2026-10-29 03:46:59 -04:00
1 parent 76f9e62253
commit b6b9120b85
8 files changed
+203 -6

No files matched your search

@@ -0,0 +1,41 @@
package com.ruoyi.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.domain.UsdtOrdersPlus;
import com.ruoyi.system.service.IUsdtOrdersService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 收银台只读入口:随机32位交易号为访问凭据,只返回付款必需字段。
* 不接受商户订单号查询,不公开用户、应用、回调地址或任何签名凭证。
*/
@RestController
public class PaymentCheckoutController {
private final IUsdtOrdersService orders;
public PaymentCheckoutController(IUsdtOrdersService orders) { this.orders = orders; }
@GetMapping("/api/v1/order/checkout/{tradeId}")
public AjaxResult detail(@PathVariable String tradeId) {
if (!tradeId.matches("[0-9a-f]{32}")) { throw new CustomException("支付信息不存在"); }
UsdtOrdersPlus order = orders.getOne(new LambdaQueryWrapper<UsdtOrdersPlus>()
.eq(UsdtOrdersPlus::getTradeId, tradeId).isNull(UsdtOrdersPlus::getDeletedAt)
.eq(UsdtOrdersPlus::getOrderType, 0).last("limit 1"));
if (order == null || order.getCreatedAt() == null) { throw new CustomException("支付信息不存在"); }
long expires = order.getCreatedAt().getTime() + 600000L;
Map<String, Object> result = new LinkedHashMap<>();
result.put("trade_id", order.getTradeId());
result.put("network", order.getPaymentNetwork());
result.put("payment_address", order.getToken());
result.put("payment_amount", order.getActualAmount());
result.put("expiration_time", expires);
result.put("status", Long.valueOf(1).equals(order.getStatus()) && expires <= System.currentTimeMillis() ? 3 : order.getStatus());
return AjaxResult.success(result);
}
}
@@ -42,6 +42,12 @@ public class RentalTopupController {
return AjaxResult.success(topups.detail(SecurityUtils.getUserId(), no));
}
@PostMapping("/rental/topup/{no}/retry")
@PreAuthorize("@ss.hasPermi('rent:portal:view')")
public AjaxResult retry(@PathVariable String no) {
return AjaxResult.success(topups.retry(SecurityUtils.getUserId(), no));
}
@PostMapping(value = "/api/rental/payment/notify/{channel}", consumes = "application/json", produces = "text/plain")
public ResponseEntity<String> notify(@PathVariable String channel, HttpServletRequest request) {
try {
@@ -81,7 +81,8 @@ public class RentalTopups {
"user_id", user, "account_id", account.get("id"), "network", network, "client_request_no", clientNo,
"requested_amount", value, "payment_channel", network, "payment_api_key", channel.getApiKey(),
"payment_public_key", pem, "payment_base_url", channel.getBaseUrl().replaceAll("/+$", ""),
"notify_url", channel.getNotifyUrl(), "status", "CREATING", "next_query_at", now()));
// DATETIME(3)可能向上舍入;首次任务设为过去,确保提交后立即可领取。
"notify_url", channel.getNotifyUrl(), "status", "CREATING", "next_query_at", now().minusSeconds(1)));
return store.get("topup_order", id, false);
});
LOG.info("充值本地单已就绪 diagnosticId={} topupNo={} network={}", diagnosticId, text(saved, "topup_no"), network);
@@ -102,6 +103,14 @@ public class RentalTopups {
return view(row);
}
/** 手动重试只核对本人原单,不新建订单,不绕过后台退避或正在执行的租约。 */
public Map<String, Object> retry(long user, String no) {
Map<String, Object> row = store.one("SELECT * FROM rent_topup_order WHERE user_id=? AND topup_no=?", user, no);
require(row != null, "充值订单不存在");
reconcile(number(row, "id"));
return detail(user, no);
}
public List<Map<String, Object>> list(long user, String network, int page) {
network(network);
require(page >= 1 && page <= 10000, "分页参数无效");
@@ -121,6 +130,9 @@ public class RentalTopups {
for (String key : Arrays.asList("expires_at", "created_at", "credited_at")) {
result.put(key, row.get(key) == null ? null : time(row.get(key)).toEpochMilli());
}
// 只返回本服务生成的阶段提示,绝不把异常原文或支付响应暴露给浏览器。
String hint = text(row, "last_error");
result.put("payment_hint", hint.startsWith("充值处理未完成:") ? hint : null);
return result;
}
@@ -159,7 +171,11 @@ public class RentalTopups {
// 一个HTTP请求最多30秒,租约180秒覆盖创建/查询及有界链上核验。
String lease = UUID.randomUUID().toString().replace("-", "");
if (store.execute("UPDATE rent_topup_order SET lease_token=?,next_query_at=?,query_attempts=query_attempts+1 WHERE id=? AND next_query_at<=? AND status IN ('CREATING','CREATE_UNKNOWN','WAITING_PAYMENT','VERIFYING')",
lease, after(180), id, now()) != 1) return;
lease, after(180), id, now()) != 1) {
LOG.debug("充值核对跳过:未到重试时间、任务已领取或订单已结束 orderId={}", id);
return;
}
LOG.info("充值核对已领取 orderId={}", id);
try {
Map<String, Object> order = store.get("topup_order", id, false);
if (text(order, "payment_trade_id").isEmpty()) {
@@ -221,8 +237,12 @@ public class RentalTopups {
// 不输出支付响应、配置、签名或异常原文;保留原单号用于后台补偿。
Map<String, Object> row = store.get("topup_order", id, false);
if (!Arrays.asList("CREDITED", "MANUAL_REVIEW", "EXPIRED").contains(text(row, "status"))) {
updateOwned(id, lease, map("status", text(row, "payment_trade_id").isEmpty() ? "CREATE_UNKNOWN" : "VERIFYING",
"next_query_at", after(60), "last_error", "支付或链上核验暂未完成,后台将使用原单号继续核对"));
// 创建已成功但查单暂时失败,仍允许用户进入已生成的收银台,不误标为已付款核验中。
String retryStatus = text(row, "payment_trade_id").isEmpty() ? "CREATE_UNKNOWN"
: "PAYMENT_QUERY".equals(stage) ? text(row, "status") : "VERIFYING";
updateOwned(id, lease, map("status", retryStatus,
"next_query_at", after(60), "last_error", "充值处理未完成:" + stage
+ ",请联系管理员检查对应阶段日志;系统将在稍后使用原单重试"));
}
}
}
@@ -56,7 +56,7 @@ public class PaymentOrderOpenApiService {
@Value("${payment.usdt-exchange-rate:1}")
private BigDecimal usdtExchangeRate;
/** 对外创建订单成功后返回的公共收银台入口。 */
@Value("${payment.checkout-url:http://192.168.3.103/public/usdtCheckout}")
@Value("${payment.checkout-url:http://192.168.3.103/public/usdtPay}")
private String checkoutUrl;
@Autowired private TronServiceProvider tronServiceProvider;
@@ -235,9 +235,16 @@ public class PaymentOrderOpenApiService {
}
private PaymentOrderCreateResult result(UsdtOrdersPlus order) {
// 兼容已配置的旧收银台路径;支付订单应直接进入付款页,保留域名及代理前缀。
org.springframework.web.util.UriComponentsBuilder paymentPage =
org.springframework.web.util.UriComponentsBuilder.fromUriString(checkoutUrl);
String path = URI.create(checkoutUrl).getPath();
if (path != null && path.endsWith("/public/usdtCheckout")) {
paymentPage.replacePath(path.substring(0, path.length() - "usdtCheckout".length()) + "usdtPay");
}
return new PaymentOrderCreateResult(order.getOrderId(), order.getTradeId(), order.getToken(),
order.getActualAmount(), new Date(order.getCreatedAt().getTime() + ORDER_TTL_MILLIS),
checkoutUrl+"?tradeId="+order.getTradeId());
paymentPage.replaceQueryParam("tradeId", order.getTradeId()).build().toUriString());
}
private Map<String, String> parseParameters(String plainData) {
@@ -42,6 +42,7 @@ public class RentalTopupTest {
private int paymentStatus = 1;
private boolean failCreate;
private boolean failChain;
private boolean failQuery;
private Set<String> created = new HashSet<>();
private int createCalls;
private int chainCalls;
@@ -83,6 +84,7 @@ public class RentalTopupTest {
"payment_amount", money("10"), "expiration_time", System.currentTimeMillis() + 600000,
"url", "https://pay.example.com/checkout?trade=" + no);
}
if (failQuery) throw new IllegalStateException("controlled query timeout");
return map("order_id", no, "trade_id", "P" + no, "status", paymentStatus,
"transaction_id", HASH, "network", paymentNetwork,
"payment_amount", money(paymentAmount), "payment_address", ADDRESS);
@@ -131,6 +133,63 @@ public class RentalTopupTest {
assertEquals(1, created.size());
assertEquals("WAITING_PAYMENT", service.detail(10, text(first, "topup_no")).get("status"));
}
@Test public void manualRetryRecoversOriginalOrderAndChecksOwnershipAndLease() throws Exception {
failCreate = true;
Map<String, Object> first = create("retry-original");
String no = text(first, "topup_no");
assertTrue(text(first, "payment_hint").contains("PAYMENT_CREATE"));
assertThrows(IllegalArgumentException.class, () -> service.retry(20, no));
failCreate = false;
service.retry(10, no);
assertEquals(1, createCalls); // 退避期不会重复调用支付服务。
due(id(first));
Map<String, Object> recovered = service.retry(10, no);
assertEquals("WAITING_PAYMENT", recovered.get("status"));
assertEquals("https://pay.example.com/checkout?trade=" + no, recovered.get("checkout_url"));
assertEquals(1, created.size());
assertNull(recovered.get("payment_hint"));
}
@Test public void successfulCreateRemainsPayableWhenQueryTimesOut() throws Exception {
failQuery = true;
Map<String, Object> first = create("query-timeout");
assertEquals(1, createCalls);
assertEquals("WAITING_PAYMENT", first.get("status"));
assertNotNull(first.get("checkout_url"));
assertTrue(text(first, "payment_hint").contains("PAYMENT_QUERY"));
}
@Test public void paymentAdapterPostsEncryptedCreateRequestToPaymentApi() throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048);
KeyPair pair = generator.generateKeyPair();
String pem = "-----BEGIN PUBLIC KEY-----\n" + Base64.getEncoder().encodeToString(pair.getPublic().getEncoded()) + "\n-----END PUBLIC KEY-----";
com.sun.net.httpserver.HttpServer server = com.sun.net.httpserver.HttpServer.create(new java.net.InetSocketAddress("127.0.0.1", 0), 0);
java.util.concurrent.atomic.AtomicReference<String> plain = new java.util.concurrent.atomic.AtomicReference<>();
server.createContext("/api/v1/order/create-transaction", exchange -> {
try {
Map<String, Object> envelope = json.readValue(exchange.getRequestBody(), Map.class);
byte[] aes = com.ruoyi.system.security.RsaCipherUtil.rsaOaepDecrypt(text(envelope, "encryptedKey"), pair.getPrivate());
plain.set(com.ruoyi.system.security.AesGcmUtil.decrypt(text(envelope, "data"), aes, Base64.getDecoder().decode(text(envelope, "iv"))));
byte[] response = json.writeValueAsBytes(map("code", 200, "data", map("order_id", "adapter-test", "url", "https://pay.example.com/public/usdtCheckout?tradeId=test", "payment_amount", money("10.12"))));
exchange.sendResponseHeaders(200, response.length); exchange.getResponseBody().write(response);
} catch (Exception failure) { exchange.sendResponseHeaders(500, -1); }
finally { exchange.close(); }
});
server.start();
try {
RentalPaymentClient real = new RentalPaymentClient(json, config, new DefaultResourceLoader());
Map<String, Object> response = real.call(map("network", "NILE", "topup_no", "adapter-test", "requested_amount", money("10.12"),
"payment_api_key", "payment-key", "payment_public_key", pem,
"payment_base_url", "http://127.0.0.1:" + server.getAddress().getPort(), "notify_url", config.getNile().getNotifyUrl()), "create-transaction");
assertTrue(plain.get().contains("network=NILE&"));
assertTrue(plain.get().contains("amount_currency=USDT&"));
assertTrue(plain.get().contains("amount=10.12&"));
assertTrue(plain.get().contains("order_id=adapter-test&"));
assertTrue(text(response, "url").contains("/public/usdtCheckout?tradeId="));
assertEquals(money("10.12"), amount(response, "payment_amount"));
} finally { server.stop(0); }
}
@Test public void networkAndAmountMismatchNeverCredit() throws Exception {
paymentStatus = 2; paymentNetwork = "MAINNET";
Map<String, Object> wrongNetwork = create("network");
@@ -0,0 +1,45 @@
package com.ruoyi.system.service;
import com.ruoyi.system.controller.PaymentCheckoutController;
import com.ruoyi.system.domain.UsdtOrdersPlus;
import com.ruoyi.common.exception.CustomException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import org.junit.Test;
import static org.junit.Assert.*;
/** 公共支付详情仅暴露白名单,不返回资金账户、商户身份或回调凭证。 */
public class PaymentCheckoutControllerTest {
private PaymentCheckoutController controller(UsdtOrdersPlus order) {
IUsdtOrdersService service = (IUsdtOrdersService) java.lang.reflect.Proxy.newProxyInstance(
IUsdtOrdersService.class.getClassLoader(), new Class<?>[]{IUsdtOrdersService.class},
(proxy, method, arguments) -> {
if ("getOne".equals(method.getName())) return order;
throw new UnsupportedOperationException();
});
return new PaymentCheckoutController(service);
}
@Test public void checkoutUsesStoredNetworkExpiryAndResponseWhitelist() {
UsdtOrdersPlus order = new UsdtOrdersPlus();
order.setTradeId("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
order.setPaymentNetwork("NILE"); order.setToken("TAddress");
order.setStatus(1L); order.setCreatedAt(new Date(System.currentTimeMillis() - 700000));
order.setActualAmount(new BigDecimal("10.00"));
order.setNotifyUrl("https://private.example.com"); order.setUserId(123L);
Map<String, Object> data = (Map<String, Object>) controller(order).detail(order.getTradeId()).get("data");
assertEquals("NILE", data.get("network"));
assertEquals(3L, ((Number) data.get("status")).longValue());
assertEquals(6, data.size());
assertFalse(data.containsKey("notify_url")); assertFalse(data.containsKey("user_id"));
order.setStatus(2L);
data = (Map<String, Object>) controller(order).detail(order.getTradeId()).get("data");
assertEquals(2L, ((Number) data.get("status")).longValue());
}
@Test public void rejectsMerchantNumbersAndMissingTrades() {
assertThrows(CustomException.class, () -> controller(null).detail("merchant-order-001"));
assertThrows(CustomException.class, () -> controller(null).detail("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
}
}
@@ -10,6 +10,19 @@ import java.util.Date;
/** 支付订单业务金额与 USDT 实付金额换算测试。 */
public class PaymentOrderOpenApiServiceTest {
@Test
public void paymentLinksUsePayPageAndPreserveExistingQuery() throws Exception {
PaymentOrderOpenApiService service = new PaymentOrderOpenApiService();
java.lang.reflect.Field field = PaymentOrderOpenApiService.class.getDeclaredField("checkoutUrl");
field.setAccessible(true);
field.set(service, "https://pay.example.com/prefix/public/usdtCheckout?lang=zh&tradeId=old");
com.ruoyi.system.domain.UsdtOrdersPlus order = new com.ruoyi.system.domain.UsdtOrdersPlus();
order.setTradeId("new-trade"); order.setCreatedAt(new Date());
java.lang.reflect.Method method = PaymentOrderOpenApiService.class.getDeclaredMethod("result", com.ruoyi.system.domain.UsdtOrdersPlus.class);
method.setAccessible(true);
PaymentOrderCreateResult result = (PaymentOrderCreateResult) method.invoke(service, order);
Assert.assertEquals("https://pay.example.com/prefix/public/usdtPay?lang=zh&tradeId=new-trade", result.getUrl());
}
@Test
public void shouldDivideByExchangeRateAndRoundDown() {
BigDecimal result = PaymentOrderOpenApiService.calculateActualAmount(