Files
usdt/ruoyi-system/src/test/java/com/ruoyi/system/rental/RentalTopupTest.java
T
lu7213 b6b9120b85 创建充值单后立即调用 /api/v1/order/create-transaction。
成功后自动跳转 public/usdtCheckout?tradeId=...。
收银台按交易号展示网络、金额、二维码、地址及支付状态。
失败时显示处理阶段,支持使用原单重试,避免重复创建。
2026-10-29 03:46:59 -04:00

265 lines
17 KiB
Java

package com.ruoyi.system.rental;
import static com.ruoyi.system.rental.RentalValues.*;
import static org.junit.Assert.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.security.*;
import org.h2.jdbcx.JdbcDataSource;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.transaction.support.TransactionTemplate;
/** 隔离MySQL兼容DDL与真实事务测试;支付和链上适配器可控,不访问真实账户或广播。 */
public class RentalTopupTest {
@Test public void diagnosticSummaryIncludesCauseAndLocationWithoutSensitiveMessages() {
Exception failure = new Exception("secret-top-level", new java.sql.SQLException("secret-sql-parameters", "42S22", 1054));
String diagnostic = RentalDiagnostics.describe(failure);
assertTrue(diagnostic.contains("java.sql.SQLException"));
assertTrue(diagnostic.contains("sqlState=42S22"));
assertTrue(diagnostic.contains("vendorCode=1054"));
assertTrue(diagnostic.contains("RentalTopupTest"));
assertFalse(diagnostic.contains("secret-top-level"));
assertFalse(diagnostic.contains("secret-sql-parameters"));
}
private static final String ADDRESS = "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf";
private static final String HASH = String.join("", Collections.nCopies(64, "a"));
private RentalStore store;
private RentalFunds funds;
private RentalTopups service;
private RentalPaymentProperties config;
private RentalPaymentClient client;
private TransactionTemplate tx;
private long account;
private String paymentNetwork = "NILE";
private String paymentAmount = "10.000000";
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;
private final ObjectMapper json = new ObjectMapper();
@Before
public void setup() throws Exception {
JdbcDataSource source = new JdbcDataSource();
source.setURL("jdbc:h2:mem:" + UUID.randomUUID() + ";MODE=MySQL;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=10000");
JdbcTemplate jdbc = new JdbcTemplate(source);
store = new RentalStore(jdbc);
for (String file : Arrays.asList("rent_init.sql", "rent_topup_init.sql")) {
String ddl = new String(Files.readAllBytes(Paths.get("../sql/" + file)), StandardCharsets.UTF_8)
.replaceAll("(?m)^--.*$", "").replace("CHARACTER SET ascii COLLATE ascii_bin", "")
.replaceAll("(?i)\\bJSON\\b", "LONGTEXT")
.replace("ENGINE=InnoDB ROW_FORMAT=DYNAMIC DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin", "");
for (String sql : ddl.split(";")) if (!sql.trim().isEmpty()) jdbc.execute(sql);
}
DataSourceTransactionManager manager = new DataSourceTransactionManager(source);
tx = new TransactionTemplate(manager);
funds = new RentalFunds(store);
account = number(funds.account(10, "NILE"), "id");
config = new RentalPaymentProperties(); config.setEnabled(true);
RentalPaymentProperties.Channel channel = config.getNile();
channel.setEnabled(true); channel.setBaseUrl("https://pay.example.com");
channel.setApiKey("payment-key"); channel.setApiSecret("test-secret");
channel.setNotifyUrl("https://rent.example.com/api/rental/payment/notify/NILE");
client = new RentalPaymentClient(json, config, new DefaultResourceLoader()) {
@Override public String publicKey(RentalPaymentProperties.Channel value) { return "public-key-fixture"; }
@Override public boolean verify(Map<String, Object> order, Map<String, Object> payload, String key, String signature) {
return "payment-key".equals(key) && "valid".equals(signature);
}
@Override public Map<String, Object> call(Map<String, Object> order, String operation) {
String no = text(order, "topup_no");
if ("create-transaction".equals(operation)) {
createCalls++; created.add(no);
if (failCreate) throw new IllegalStateException("controlled lost response");
return map("order_id", no, "trade_id", "P" + no, "payment_address", ADDRESS,
"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);
}
};
RentalChain chain = new RentalChain(json) {
@Override public Map<String, Object> paymentTransfer(String network, String hash, String address,
java.math.BigDecimal amount, long createdAt, long expiresAt) {
chainCalls++;
assertEquals("NILE", network); assertEquals(HASH, hash); assertEquals(ADDRESS, address);
assertEquals(money("10"), amount);
if (failChain) throw new IllegalStateException("controlled unconfirmed transfer");
return map("reference", "NILE:" + HASH + ":0", "log_index", 0);
}
};
service = new RentalTopups(store, funds, chain, config, client, manager);
}
private Map<String, Object> create(String request) throws Exception {
return service.create(10, map("network", "NILE", "amount", "10.00", "client_request_no", request));
}
private long id(Map<String, Object> view) { return number(store.one("SELECT id FROM rent_topup_order WHERE topup_no=?", view.get("topup_no")), "id"); }
private void due(long id) { store.update("topup_order", id, map("next_query_at", now().minusSeconds(1))); }
private Map<String, Object> payload(Map<String, Object> row) { return map("order_id", row.get("topup_no"), "trade_id", "P" + row.get("topup_no"), "status", 2, "transaction_id", HASH); }
@Test public void duplicateCreateNotificationAndPollingCreditOnce() throws Exception {
Map<String, Object> first = create("click-1");
assertEquals("WAITING_PAYMENT", first.get("status"));
assertEquals(first.get("topup_no"), create("click-1").get("topup_no"));
service.notify("NILE", payload(first), "payment-key", "valid");
service.notify("NILE", payload(first), "payment-key", "valid");
assertEquals(1, number(store.one("SELECT COUNT(*) AS n FROM rent_topup_notify"), "n"));
assertEquals(ZERO, amount(store.get("account", account, false), "available_amount"));
paymentStatus = 2; due(id(first)); service.reconcile(id(first)); service.reconcile(id(first));
assertEquals("CREDITED", service.detail(10, text(first, "topup_no")).get("status"));
assertEquals(money("10"), amount(store.get("account", account, false), "available_amount"));
assertEquals(1, number(store.one("SELECT COUNT(*) AS n FROM rent_ledger"), "n"));
assertEquals("DONE", store.one("SELECT * FROM rent_topup_notify").get("status"));
assertFalse(first.containsKey("payment_api_key")); assertFalse(first.containsKey("payment_public_key"));
assertEquals(1, createCalls);
}
@Test public void lostCreateResponseRetriesOriginalPaymentOrder() throws Exception {
failCreate = true;
Map<String, Object> first = create("lost");
assertEquals("CREATE_UNKNOWN", first.get("status"));
failCreate = false; due(id(first)); service.reconcile(id(first));
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");
assertEquals("MANUAL_REVIEW", wrongNetwork.get("status"));
paymentNetwork = "NILE"; paymentAmount = "11";
assertEquals("MANUAL_REVIEW", create("amount").get("status"));
assertEquals(0, chainCalls);
assertEquals(ZERO, amount(store.get("account", account, false), "available_amount"));
}
@Test public void chainFailureWaitsAndFrozenAccountGoesToReview() throws Exception {
paymentStatus = 2; failChain = true;
Map<String, Object> first = create("chain");
assertEquals("VERIFYING", first.get("status"));
failChain = false; store.update("account", account, map("status", "FROZEN"));
due(id(first)); service.reconcile(id(first));
assertEquals("MANUAL_REVIEW", service.detail(10, text(first, "topup_no")).get("status"));
assertEquals(ZERO, amount(store.get("account", account, false), "available_amount"));
}
@Test public void invalidSignatureAndOwnershipAreRejected() throws Exception {
Map<String, Object> first = create("auth");
assertThrows(IllegalArgumentException.class, () -> service.detail(20, text(first, "topup_no")));
assertThrows(IllegalArgumentException.class, () -> service.notify("NILE", payload(first), "payment-key", "forged"));
assertThrows(IllegalArgumentException.class, () -> service.notify("MAINNET", payload(first), "payment-key", "valid"));
assertThrows(IllegalArgumentException.class, () -> service.create(10, map("network", "NILE", "amount", "11", "client_request_no", "auth")));
}
@Test public void manualAndAutomaticTopupShareTransferIdempotency() throws Exception {
Map<String, Object> first = create("manual");
tx.execute(status -> { funds.post(account, "TOPUP:NILE:" + HASH + ":0", "TOPUP", money("10"), ZERO, ZERO, ZERO, null, null, null, 99, HASH, "manual"); return null; });
paymentStatus = 2; due(id(first)); service.reconcile(id(first));
assertEquals("MANUAL_REVIEW", service.detail(10, text(first, "topup_no")).get("status"));
assertEquals(money("10"), amount(store.get("account", account, false), "available_amount"));
}
@Test public void realRsaVerificationRejectsTamperingAndWrongKey() 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-----";
Map<String, Object> order = map("payment_api_key", "payment-key", "payment_public_key", pem);
Map<String, Object> payload = map("order_id", "demo", "status", 2);
String signature = com.ruoyi.system.service.PaymentSignatureService.signRsa(payload, pair.getPrivate());
RentalPaymentClient real = new RentalPaymentClient(json, config, new DefaultResourceLoader());
assertTrue(real.verify(order, payload, "payment-key", signature));
assertFalse(real.verify(order, payload, "other-key", signature));
payload.put("status", 1); assertFalse(real.verify(order, payload, "payment-key", signature));
}
@Test public void concurrentReconciliationCreditsOnlyOnceWithoutNotification() throws Exception {
Map<String, Object> first = create("parallel");
long orderId = id(first);
paymentStatus = 2; due(orderId);
ExecutorService workers = Executors.newFixedThreadPool(2);
try {
Future<?> left = workers.submit(() -> service.reconcile(orderId));
Future<?> right = workers.submit(() -> service.reconcile(orderId));
left.get(20, TimeUnit.SECONDS); right.get(20, TimeUnit.SECONDS);
} finally { workers.shutdownNow(); }
assertEquals("CREDITED", service.detail(10, text(first, "topup_no")).get("status"));
assertEquals(money("10"), amount(store.get("account", account, false), "available_amount"));
assertEquals(1, number(store.one("SELECT COUNT(*) AS n FROM rent_ledger"), "n"));
}
@Test public void expiredWorkerCannotOverwriteNewLeaseOrTerminalState() throws Exception {
Map<String, Object> first = create("lease"); long orderId = id(first);
store.update("topup_order", orderId, map("lease_token", "new-owner"));
java.lang.reflect.Method method = RentalTopups.class.getDeclaredMethod("updateOwned", long.class, String.class, Map.class);
method.setAccessible(true);
method.invoke(service, orderId, "expired-owner", map("status", "EXPIRED"));
assertEquals("WAITING_PAYMENT", service.detail(10, text(first, "topup_no")).get("status"));
store.update("topup_order", orderId, map("status", "CREDITED"));
method.invoke(service, orderId, "new-owner", map("status", "WAITING_PAYMENT"));
assertEquals("CREDITED", service.detail(10, text(first, "topup_no")).get("status"));
}
}