租赁资金账户资金充值功能,对接项目的支付接口,application-rental.yml添加配置NILE和主网的对接配置

This commit is contained in:
lu7213 committed 2026-10-29 02:16:04 -04:00
1 parent 911a3634ee
commit e73f099734
20 files changed
+878 -9

No files matched your search

@@ -53,6 +53,10 @@ public class PaymentApiController {
result.put("trade_id", order.getTradeId());
result.put("status", order.getStatus());
result.put("transaction_id", order.getBlockTransactionId());
result.put("network", order.getPaymentNetwork());
result.put("payment_amount", order.getActualAmount());
result.put("payment_address", order.getToken());
result.put("expiration_time", order.getCreatedAt().getTime() + 600000L);
if (Long.valueOf(2L).equals(order.getStatus())) {
result.put("signed_redirect_url",
paymentRedirectService.buildSignedRedirectUrl(order, request.getApiKey()));
@@ -27,6 +27,10 @@ public class UsdtOrdersPlus implements Serializable
/** 主键 */
@TableId(type = IdType.INPUT)
private Long id;
/** 支付创建时锁定网络;历史NULL订单兼容全局网络。 */
private String paymentNetwork;
public String getPaymentNetwork() { return paymentNetwork; }
public void setPaymentNetwork(String paymentNetwork) { this.paymentNetwork = paymentNetwork; }
/** 订单号 */
@Excel(name = "订单号")
private String tradeId;
@@ -15,6 +15,7 @@ public class PaymentOrderCreateResult {
@JsonProperty("payment_amount")
private BigDecimal paymentAmount;
@JsonProperty("expiration_time")
@com.fasterxml.jackson.annotation.JsonFormat(shape = com.fasterxml.jackson.annotation.JsonFormat.Shape.NUMBER)
private Date expirationTime;
/** 商户可引导用户访问的公共收银台地址。 */
private String url;
@@ -298,6 +298,34 @@ public class RentalChain {
return ApiWrapper.toHex(ApiWrapper.parseAddress(address));
}
/** 自动充值定位唯一匹配日志;不信任支付平台传入的日志索引,兼用人工充值去重键。 */
public Map<String, Object> paymentTransfer(String network, String txId, String address,
BigDecimal expected, long createdAt, long expiresAt) {
require(txId.matches("[0-9a-fA-F]{64}"), "支付交易哈希无效");
JsonNode receipt = call(network, "/walletsolidity/gettransactioninfobyid", map("value", txId));
long timestamp = receipt.path("blockTimeStamp").asLong(-1);
require(timestamp >= createdAt - 5000 && timestamp <= expiresAt, "支付交易不在订单有效期内");
JsonNode logs = receipt.path("log");
require(logs.isArray() && logs.size() <= 512, "支付交易日志缺失或过多");
int selected = -1;
String contract = hexAddress(tronServices.getServiceForNetwork(network).contractAddress()).substring(2);
for (int index = 0; index < logs.size(); index++) {
JsonNode entry = logs.get(index);
if (contract.equalsIgnoreCase(entry.path("address").asText())
&& entry.path("topics").size() == 3
&& "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef".equalsIgnoreCase(entry.path("topics").get(0).asText())
&& entry.path("topics").get(2).asText().toLowerCase(Locale.ROOT).endsWith(hexAddress(address).substring(2).toLowerCase(Locale.ROOT))
&& new BigDecimal(new java.math.BigInteger(entry.path("data").asText(), 16)).movePointLeft(6).compareTo(expected) == 0) {
require(selected < 0, "同交易存在多笔匹配充值,需要人工核对");
selected = index;
}
}
require(selected >= 0, "未找到匹配的USDT充值日志");
Map<String, Object> result = transfer(network, txId, selected, address, expected);
result.put("log_index", selected);
return result;
}
/**
* 人工充值/付款依据必须由配置网络的USDT Transfer日志独立核对。
*/
@@ -0,0 +1,80 @@
package com.ruoyi.system.rental;
import static com.ruoyi.system.rental.RentalValues.*;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.system.security.RsaKeyUtil;
import com.ruoyi.system.security.SecureClient;
import okhttp3.*;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.Signature;
import java.util.Base64;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import com.ruoyi.system.service.PaymentSignatureService;
/** 支付HTTP适配器:复用项目混合加密SDK;不允许重定向携带支付认证材料。 */
@Component
public class RentalPaymentClient {
private final ObjectMapper json;
private final RentalPaymentProperties properties;
private final ResourceLoader resources;
public RentalPaymentClient(ObjectMapper json, RentalPaymentProperties properties, ResourceLoader resources) {
this.json = json.copy().enable(com.fasterxml.jackson.databind.DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
this.properties = properties;
this.resources = resources;
}
public String publicKey(RentalPaymentProperties.Channel channel) throws Exception {
try (InputStream input = resources.getResource(channel.getRsaPublicKeyLocation()).getInputStream()) {
java.io.ByteArrayOutputStream output = new java.io.ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int size;
while ((size = input.read(buffer)) != -1) {
require(output.size() + size <= 16384, "支付公钥文件过大");
output.write(buffer, 0, size);
}
String pem = new String(output.toByteArray(), StandardCharsets.UTF_8);
RsaKeyUtil.loadPublicKey(pem);
return pem;
}
}
public Map<String, Object> call(Map<String, Object> order, String operation) throws Exception {
RentalPaymentProperties.Channel channel = properties.channel(text(order, "network"));
require(properties.isEnabled() && channel.isEnabled(), "支付充值尚未启用");
require(channel.getApiKey().equals(text(order, "payment_api_key"))
&& !channel.getApiSecret().isEmpty(), "在途充值凭证已变化,请保留旧通道配置后核对");
Map<String, Object> parameters = map("order_id", text(order, "topup_no"));
if ("create-transaction".equals(operation)) {
parameters.putAll(map("amount", amount(order, "requested_amount").setScale(2).toPlainString(),
"amount_currency", "USDT", "network", text(order, "network"),
"walletUserName", "rent:" + text(order, "topup_no"), "notify_url", text(order, "notify_url")));
}
Object encrypted = SecureClient.encrypt(text(order, "payment_api_key"), channel.getApiSecret(),
RsaKeyUtil.loadPublicKey(text(order, "payment_public_key")), parameters);
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(properties.getConnectTimeoutMs(), TimeUnit.MILLISECONDS)
.readTimeout(properties.getReadTimeoutMs(), TimeUnit.MILLISECONDS)
.callTimeout(30, TimeUnit.SECONDS).followRedirects(false).followSslRedirects(false)
.retryOnConnectionFailure(false).build();
Request request = new Request.Builder().url(text(order, "payment_base_url") + "/api/v1/order/" + operation)
.post(RequestBody.create(MediaType.parse("application/json"), json.writeValueAsString(encrypted))).build();
try (Response response = client.newCall(request).execute()) {
Map<String, Object> result = json.readValue(RentalHttp.body(response), new TypeReference<Map<String, Object>>() { });
require(number(result, "code") == 200 && result.get("data") instanceof Map, "支付请求未成功,请稍后核对");
return (Map<String, Object>) result.get("data");
}
}
/** RSA验签使用项目既有参数规范化规则,不使用租赁HMAC或浏览器跳转结果。 */
public boolean verify(Map<String, Object> order, Map<String, Object> payload, String key, String signature) {
try {
if (!text(order, "payment_api_key").equals(key) || signature == null) return false;
Signature verifier = Signature.getInstance("SHA256withRSA");
verifier.initVerify(RsaKeyUtil.loadPublicKey(text(order, "payment_public_key")));
verifier.update(PaymentSignatureService.canonicalText(payload).getBytes(StandardCharsets.UTF_8));
return verifier.verify(Base64.getDecoder().decode(signature));
} catch (Exception exception) { return false; }
}
}
@@ -0,0 +1,58 @@
package com.ruoyi.system.rental;
import java.math.BigDecimal;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/** 支付通道配置只保存在服务器;禁止输出配置对象或向浏览器返回凭证。 */
@Component
@ConfigurationProperties(prefix = "rental.payment")
public class RentalPaymentProperties {
private boolean enabled;
private int connectTimeoutMs = 5000;
private int readTimeoutMs = 15000;
private Channel nile = new Channel();
private Channel mainnet = new Channel();
public boolean isEnabled() { return enabled; }
public void setEnabled(boolean value) { enabled = value; }
public int getConnectTimeoutMs() { return connectTimeoutMs; }
public void setConnectTimeoutMs(int value) { connectTimeoutMs = value; }
public int getReadTimeoutMs() { return readTimeoutMs; }
public void setReadTimeoutMs(int value) { readTimeoutMs = value; }
public Channel getNile() { return nile; }
public void setNile(Channel value) { nile = value; }
public Channel getMainnet() { return mainnet; }
public void setMainnet(Channel value) { mainnet = value; }
public Channel channel(String network) {
RentalValues.network(network);
return "NILE".equals(network) ? nile : mainnet;
}
/** 每个网络独立启用;支付应用公钥以Spring Resource路径从外部文件加载。 */
public static class Channel {
private boolean enabled;
private String baseUrl = "";
private String apiKey = "";
private String apiSecret = "";
private String rsaPublicKeyLocation = "";
private String notifyUrl = "";
private BigDecimal minAmount = new BigDecimal("1.00");
private BigDecimal maxAmount = new BigDecimal("10000.00");
public boolean isEnabled() { return enabled; }
public void setEnabled(boolean value) { enabled = value; }
public String getBaseUrl() { return baseUrl; }
public void setBaseUrl(String value) { baseUrl = value; }
public String getApiKey() { return apiKey; }
public void setApiKey(String value) { apiKey = value; }
public String getApiSecret() { return apiSecret; }
public void setApiSecret(String value) { apiSecret = value; }
public String getRsaPublicKeyLocation() { return rsaPublicKeyLocation; }
public void setRsaPublicKeyLocation(String value) { rsaPublicKeyLocation = value; }
public String getNotifyUrl() { return notifyUrl; }
public void setNotifyUrl(String value) { notifyUrl = value; }
public BigDecimal getMinAmount() { return minAmount; }
public void setMinAmount(BigDecimal value) { minAmount = value; }
public BigDecimal getMaxAmount() { return maxAmount; }
public void setMaxAmount(BigDecimal value) { maxAmount = value; }
}
}
@@ -89,6 +89,10 @@ public class RentalQueries {
args.toArray());
for (Map<String, Object> row : rows) {
row.remove("api_secret");
row.remove("payment_api_key");
row.remove("payment_public_key");
row.remove("payment_base_url");
row.remove("lease_token");
row.remove("ownership_signature");
row.remove("ownership_challenge");
row.remove("ownership_message");
@@ -25,6 +25,7 @@ public class RentalStore {
"package",
"user_package",
"account",
"topup_order",
"order",
"task",
"transaction",
@@ -0,0 +1,69 @@
package com.ruoyi.system.rental;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* 本人充值入口与支付通知入口分离;通知仅按支付应用RSA公钥认证。
*/
@RestController
public class RentalTopupController {
private final RentalTopups topups;
private final ObjectMapper json;
public RentalTopupController(RentalTopups topups, ObjectMapper json) {
this.topups = topups;
this.json = json;
}
@PostMapping("/rental/topup/create")
@PreAuthorize("@ss.hasPermi('rent:portal:view')")
public AjaxResult create(@RequestBody Map<String, Object> body) throws Exception {
return AjaxResult.success(topups.create(SecurityUtils.getUserId(), body));
}
@GetMapping("/rental/topup/list")
@PreAuthorize("@ss.hasPermi('rent:portal:view')")
public AjaxResult list(@RequestParam String network, @RequestParam(defaultValue = "1") int page) {
return AjaxResult.success(topups.list(SecurityUtils.getUserId(), network, page));
}
@GetMapping("/rental/topup/{no}")
@PreAuthorize("@ss.hasPermi('rent:portal:view')")
public AjaxResult detail(@PathVariable String no) {
return AjaxResult.success(topups.detail(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 {
// 只读取一次流,兼容RuoYi可重复读取包装器,512KiB原始字节上限。
java.io.InputStream input = request.getInputStream();
java.io.ByteArrayOutputStream output = new java.io.ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int count;
while ((count = input.read(buffer)) != -1) {
RentalValues.require(output.size() + count <= RentalJson.MAX_HTTP_BODY_BYTES, "支付通知过大");
output.write(buffer, 0, count);
}
String body = java.nio.charset.StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(java.nio.charset.CodingErrorAction.REPORT)
.decode(java.nio.ByteBuffer.wrap(output.toByteArray())).toString();
RentalJson.bounded(body, RentalJson.MAX_HTTP_BODY_BYTES);
Map<String, Object> payload = json.readValue(body, new TypeReference<Map<String, Object>>() {
});
topups.notify(channel, payload, request.getHeader("X-Payment-Api-Key"), request.getHeader("X-Payment-Rsa-Signature"));
return ResponseEntity.ok("ok");
} catch (Exception exception) {
return ResponseEntity.status(400).body("invalid notification");
}
}
}
@@ -0,0 +1,248 @@
package com.ruoyi.system.rental;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import java.math.BigDecimal;
import java.net.URI;
import java.util.*;
import static com.ruoyi.system.rental.RentalValues.*;
/**
* 充值编排:本地单先落库,外部HTTP/RPC均在事务外,账务与终态同事务。
* 数据库租约防止多实例同时执行;HTTP超时用原单号重试,绝不生成替代支付单。
*/
@Service
public class RentalTopups {
private final RentalStore store;
private final RentalFunds funds;
private final RentalChain chain;
private final RentalPaymentProperties config;
private final RentalPaymentClient payment;
private final TransactionTemplate tx;
public RentalTopups(RentalStore store, RentalFunds funds, RentalChain chain,
RentalPaymentProperties config, RentalPaymentClient payment, PlatformTransactionManager manager) {
this.store = store;
this.funds = funds;
this.chain = chain;
this.config = config;
this.payment = payment;
this.tx = new TransactionTemplate(manager);
}
public Map<String, Object> create(long user, Map<String, Object> request) throws Exception {
String network = network(input(request, "network", 16));
String clientNo = input(request, "client_request_no", 64);
BigDecimal value = money(request.get("amount"));
require(value.signum() > 0 && value.stripTrailingZeros().scale() <= 2, "充值金额必须为正数且最多两位小数");
RentalPaymentProperties.Channel channel = config.channel(network);
require(config.isEnabled() && channel.isEnabled(), "该网络暂未启用在线充值");
require(value.compareTo(channel.getMinAmount()) >= 0 && value.compareTo(channel.getMaxAmount()) <= 0,
"充值金额超出通道允许范围");
URI base = URI.create(channel.getBaseUrl());
URI notify = URI.create(channel.getNotifyUrl());
require("https".equalsIgnoreCase(base.getScheme()) && base.getHost() != null
&& base.getUserInfo() == null && base.getQuery() == null && base.getFragment() == null,
"支付服务必须配置合法HTTPS基地址");
require("https".equalsIgnoreCase(notify.getScheme()) && notify.getHost() != null
&& notify.getUserInfo() == null && notify.getQuery() == null && notify.getFragment() == null
&& channel.getNotifyUrl().length() <= 128, "支付回调地址配置无效");
require(!channel.getApiKey().isEmpty() && !channel.getApiSecret().isEmpty(), "支付通道缺少应用凭证");
String pem = payment.publicKey(channel);
Map<String, Object> saved = tx.execute(status -> {
Map<String, Object> account = store.one("SELECT * FROM rent_account WHERE user_id=? AND network=? FOR UPDATE", user, network);
require(account != null && "ACTIVE".equals(text(account, "status")), "请先开通正常的网络资金账户");
Map<String, Object> existing = store.one("SELECT * FROM rent_topup_order WHERE user_id=? AND client_request_no=?", user, clientNo);
if (existing != null) {
require(network.equals(text(existing, "network")) && amount(existing, "requested_amount").compareTo(value) == 0,
"相同充值请求号的网络或金额不一致");
return existing;
}
long id = store.insert("topup_order", map("topup_no", UUID.randomUUID().toString().replace("-", ""),
"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()));
return store.get("topup_order", id, false);
});
reconcile(number(saved, "id"));
return detail(user, text(saved, "topup_no"));
}
public Map<String, Object> detail(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, "充值订单不存在");
return view(row);
}
public List<Map<String, Object>> list(long user, String network, int page) {
network(network);
require(page >= 1 && page <= 10000, "分页参数无效");
List<Map<String, Object>> result = new ArrayList<>();
for (Map<String, Object> row : store.rows("SELECT * FROM rent_topup_order WHERE user_id=? AND network=? ORDER BY id DESC LIMIT 20 OFFSET ?",
user, network, (page - 1) * 20))
result.add(view(row));
return result;
}
private Map<String, Object> view(Map<String, Object> row) {
// 明确响应白名单,不把支付凭证、回调地址、公钥或内部错误发送给浏览器。
Map<String, Object> result = new LinkedHashMap<>();
for (String key : Arrays.asList("topup_no", "network", "requested_amount", "payment_amount", "credited_amount",
"payment_address", "checkout_url", "status", "transaction_id"))
result.put(key, row.get(key));
for (String key : Arrays.asList("expires_at", "created_at", "credited_at")) {
result.put(key, row.get(key) == null ? null : time(row.get(key)).toEpochMilli());
}
return result;
}
/**
* 只有验签后才持久化收件箱;支付通知不直接更改余额。
*/
public void notify(String channel, Map<String, Object> payload, String key, String signature) {
network(channel);
String no = input(payload, "order_id", 32);
tx.execute(status -> {
Map<String, Object> order = store.one("SELECT * FROM rent_topup_order WHERE topup_no=? FOR UPDATE", no);
require(order != null && channel.equals(text(order, "network")), "通知订单或通道不匹配");
require(payment.verify(order, payload, key, signature), "支付通知认证失败");
String trade = input(payload, "trade_id", 64);
require(text(order, "payment_trade_id").isEmpty() || trade.equals(text(order, "payment_trade_id")), "通知交易号不符");
require(number(payload, "status") == 2 && text(payload, "transaction_id").matches("[0-9a-fA-F]{64}"), "通知支付结果无效");
String hash = RentalCrypto.sha256(com.ruoyi.system.service.PaymentSignatureService.canonicalText(payload));
if (store.one("SELECT id FROM rent_topup_notify WHERE notification_hash=?", hash) == null) {
store.execute("INSERT INTO rent_topup_notify(notification_hash,topup_no,payment_trade_id,transaction_id,payment_status,status,created_at,updated_at) VALUES(?,?,?,?,2,'PENDING',?,?)",
hash, no, trade, text(payload, "transaction_id"), now(), now());
}
return null;
});
}
@Scheduled(fixedDelayString = "${rental.payment.reconcile-interval-ms:15000}")
public void tick() {
if (!config.isEnabled()) return;
for (Map<String, Object> row : store.rows("SELECT id FROM rent_topup_order WHERE status IN ('CREATING','CREATE_UNKNOWN','WAITING_PAYMENT','VERIFYING') AND next_query_at<=? ORDER BY next_query_at LIMIT 20", now())) {
reconcile(number(row, "id"));
}
}
public void reconcile(long id) {
// 一个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;
try {
Map<String, Object> order = store.get("topup_order", id, false);
if (text(order, "payment_trade_id").isEmpty()) {
Map<String, Object> created = payment.call(order, "create-transaction");
require(text(order, "topup_no").equals(text(created, "order_id")), "支付订单号不符");
require(amount(created, "payment_amount").compareTo(amount(order, "requested_amount")) == 0, "支付实际金额不符");
RentalOrders.address(input(created, "payment_address", 64));
Object expiration = created.get("expiration_time");
Date expires = new com.fasterxml.jackson.databind.ObjectMapper().convertValue(expiration, Date.class);
require(expires != null, "支付有效期缺失");
String checkout = input(created, "url", 1024);
URI checkoutUri = URI.create(checkout);
require("https".equalsIgnoreCase(checkoutUri.getScheme()) && checkoutUri.getHost() != null
&& checkoutUri.getUserInfo() == null, "支付收银台需使用HTTPS");
tx.execute(status -> {
updateOwned(id, lease, map("payment_trade_id", input(created, "trade_id", 64),
"payment_address", text(created, "payment_address"), "payment_amount", amount(created, "payment_amount"),
"checkout_url", checkout, "expires_at", java.time.LocalDateTime.ofInstant(expires.toInstant(), java.time.ZoneOffset.UTC),
"status", "WAITING_PAYMENT"));
return null;
});
order = store.get("topup_order", id, false);
}
Map<String, Object> result = payment.call(order, "query");
if (!text(order, "topup_no").equals(text(result, "order_id"))
|| !text(order, "payment_trade_id").equals(text(result, "trade_id"))
|| !text(order, "network").equals(text(result, "network"))
|| !text(order, "payment_address").equals(text(result, "payment_address"))
|| amount(order, "payment_amount").compareTo(amount(result, "payment_amount")) != 0) {
updateOwned(id, lease, map("status", "MANUAL_REVIEW", "last_error", "支付订单的网络、金额、地址或交易号不一致"));
return;
}
if (number(result, "status") == 3) {
updateOwned(id, lease, map("status", "EXPIRED", "last_error", null));
return;
}
if (number(result, "status") != 2) {
updateOwned(id, lease, map("status", "WAITING_PAYMENT", "next_query_at", after(15), "last_error", null));
return;
}
updateOwned(id, lease, map("status", "VERIFYING"));
String txId = input(result, "transaction_id", 64);
Map<String, Object> proof = chain.paymentTransfer(text(order, "network"), txId,
text(order, "payment_address"), amount(order, "payment_amount"), time(order.get("created_at")).toEpochMilli(),
time(order.get("expires_at")).toEpochMilli());
tx.execute(status -> {
Map<String, Object> current = store.get("topup_order", id, true);
require(lease.equals(text(current, "lease_token")), "充值核对租约已被接管");
credit(id, txId, proof);
return null;
});
} catch (Exception exception) {
// 不输出支付响应、配置、签名或异常原文;保留原单号用于后台补偿。
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", "支付或链上核验暂未完成,后台将使用原单号继续核对"));
}
}
}
/**
* 行锁内核对租约,防止多实例接管后,过期任务覆盖新状态或已入账终态。
*/
private void updateOwned(long id, String lease, Map<String, Object> values) {
tx.execute(status -> {
Map<String, Object> current = store.get("topup_order", id, true);
if (lease.equals(text(current, "lease_token"))
&& !Arrays.asList("CREDITED", "MANUAL_REVIEW", "EXPIRED").contains(text(current, "status"))) {
store.update("topup_order", id, values);
}
return null;
});
}
/**
* 终态、余额与不可变流水原子提交,复用人工充值的链上事件幂等键。
*/
public void credit(long id, String txId, Map<String, Object> proof) {
tx.execute(status -> {
Map<String, Object> row = store.get("topup_order", id, true);
if ("CREDITED".equals(text(row, "status"))) return null;
require("VERIFYING".equals(text(row, "status")), "充值单状态不可入账");
Map<String, Object> account = store.get("account", number(row, "account_id"), true);
if (!"ACTIVE".equals(text(account, "status"))) {
manual(id, "账户已冻结,请人工核对已付款充值");
return null;
}
require(number(account, "user_id") == number(row, "user_id") && text(account, "network").equals(text(row, "network")), "充值账户归属不符");
String reference = text(proof, "reference");
require(reference.equals(text(row, "network") + ":" + txId.toLowerCase(Locale.ROOT) + ":" + number(proof, "log_index")), "充值证明引用不符");
Map<String, Object> used = store.one("SELECT * FROM rent_ledger WHERE business_key=?", "TOPUP:" + reference);
if (used != null) {
manual(id, "该链上转账已入账,请人工核对原充值记录");
return null;
}
BigDecimal value = amount(row, "payment_amount");
funds.post(number(row, "account_id"), "TOPUP:" + reference, "TOPUP", value, ZERO, ZERO, ZERO,
null, null, null, 0, reference, "支付接口充值 " + text(row, "topup_no"));
store.update("topup_order", id, map("status", "CREDITED", "credited_amount", value, "credited_at", now(),
"transaction_id", txId.toLowerCase(Locale.ROOT), "log_index", number(proof, "log_index"), "last_error", null));
store.execute("UPDATE rent_topup_notify SET status='DONE',updated_at=? WHERE topup_no=?", now(), text(row, "topup_no"));
return null;
});
}
private void manual(long id, String reason) {
store.update("topup_order", id, map("status", "MANUAL_REVIEW", "last_error", reason));
}
}
@@ -41,7 +41,7 @@ import java.util.regex.Pattern;
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)=");
"(?:^|&)(amount|notify_url|order_id|redirect_url|walletUserName|network|amount_currency)=");
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>(
@@ -58,6 +58,7 @@ public class PaymentOrderOpenApiService {
/** 对外创建订单成功后返回的公共收银台入口。 */
@Value("${payment.checkout-url:http://192.168.3.103/public/usdtCheckout}")
private String checkoutUrl;
@Autowired private TronServiceProvider tronServiceProvider;
@Transactional(rollbackFor = Exception.class)
public PaymentOrderCreateResult createOrder(DecryptResult request) {
@@ -67,7 +68,12 @@ public class PaymentOrderOpenApiService {
String notifyUrl = required(parameters, "notify_url");
String redirectUrl = trimToNull(parameters.get("redirect_url"));
BigDecimal amount = parseAmount(required(parameters, "amount"));
BigDecimal actualAmount = convertToUsdt(amount);
boolean usdt = "USDT".equals(parameters.get("amount_currency"));
if (parameters.containsKey("amount_currency") && !usdt) throw new CustomException("不支持的金额币种");
BigDecimal actualAmount = usdt ? amount.setScale(2, RoundingMode.UNNECESSARY) : convertToUsdt(amount);
String network = parameters.get("network");
if (network == null) network = "nile".equals(tronServiceProvider.getCurrentService().type()) ? "NILE" : "MAINNET";
if (!("NILE".equals(network) || "MAINNET".equals(network))) throw new CustomException("支付网络无效");
validate(orderId, walletUserName, notifyUrl, redirectUrl);
// 锁定应用,使同一应用下的钱包领取和商户订单幂等检查串行执行。
@@ -82,6 +88,12 @@ public class PaymentOrderOpenApiService {
if (!Objects.equals(existingOrder.getAppId(), request.getAppId())) {
throw new CustomException("商户订单号已存在");
}
if (existingOrder.getActualAmount().compareTo(actualAmount) != 0
|| (existingOrder.getPaymentNetwork() != null && !Objects.equals(existingOrder.getPaymentNetwork(), network))
|| !Objects.equals(existingOrder.getWalletUserName(), walletUserName)
|| !Objects.equals(existingOrder.getNotifyUrl(), notifyUrl)) {
throw new CustomException("同一支付单号参数不一致");
}
return result(existingOrder);
}
@@ -103,6 +115,7 @@ public class PaymentOrderOpenApiService {
UsdtOrdersPlus order = new UsdtOrdersPlus();
order.setTradeId(tradeId);
order.setPaymentNetwork(network);
order.setOrderId(orderId);
order.setAmount(amount);
order.setActualAmount(actualAmount);
@@ -248,7 +261,7 @@ public class PaymentOrderOpenApiService {
throw new CustomException("业务参数不能重复");
}
}
if (!values.keySet().containsAll(REQUIRED_PARAMETERS) || values.size() > 5) {
if (!values.keySet().containsAll(REQUIRED_PARAMETERS) || values.size() > 7) {
throw new CustomException("业务参数不完整或包含不支持的参数");
}
return values;
@@ -77,7 +77,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<select id="selectByIdForUpdate" resultType="com.ruoyi.system.domain.UsdtOrdersPlus">
select id, trade_id, order_id, block_transaction_id, actual_amount, amount, token, wallet_user_name,
status, notify_url, redirect_url, callback_num, callback_confirm, created_at,
updated_at, deleted_at, app_id, settlement_status, user_id, order_type
updated_at, deleted_at, app_id, settlement_status, user_id, order_type, payment_network
from orders
where id = #{id}
for update
@@ -0,0 +1,195 @@
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 {
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 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);
}
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 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"));
}
}
@@ -36,4 +36,12 @@ public class PaymentOrderOpenApiServiceTest {
Assert.assertEquals(checkoutUrl, result.getUrl());
}
@Test
public void expirationIsEpochEvenWhenServerUsesCustomDateFormat() throws Exception {
com.fasterxml.jackson.databind.ObjectMapper json = new com.fasterxml.jackson.databind.ObjectMapper();
json.setDateFormat(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
PaymentOrderCreateResult result = new PaymentOrderCreateResult("o", "t", "TAddress", BigDecimal.ONE, new Date(1793232000000L), "https://pay.example.com");
Assert.assertEquals(1793232000000L, json.readTree(json.writeValueAsString(result)).path("expiration_time").asLong());
}
}