1.PROXY\_ACCOUNT 租赁账户,首页中的租赁套餐 ,立即租赁按钮不可操作,帮我完成这个功能,点击立即租赁,跳出输入地址,apiKey,apiSecret,时长,对接地址,回调地址等,然后显示预计费用,然后调用租赁api 2. 帮我实现回调地址同步和异步验证的demo的controller

This commit is contained in:
lu7213 committed 2026-10-25 22:14:04 -04:00
1 parent 127d575a1c
commit 8dcb313454
9 files changed
+408 -3

No files matched your search

@@ -35,7 +35,7 @@ public class RentalApiController {
public AjaxResult execute(@PathVariable String operation, HttpServletRequest request)
throws Exception {
require(
Arrays.asList("create", "query", "packages").contains(operation)
Arrays.asList("create", "query", "packages", "quote").contains(operation)
&& request.getQueryString() == null,
"接口或查询参数不支持");
ByteArrayOutputStream output = new ByteArrayOutputStream();
@@ -79,6 +79,22 @@ public class RentalApiController {
return AjaxResult.success(products);
}
Map<String, Object> order;
if ("quote".equals(operation)) {
RentalOrders.address(input(data, "receiver_address", 64));
if (!text(data, "notify_url").trim().isEmpty()) {
RentalHttp.checkUrl(text(data, "notify_url").trim());
}
Map<String, Object> product = store.one("SELECT p.* FROM rent_package p"
+ " JOIN rent_user_package b ON b.package_id=p.id WHERE b.user_id=?"
+ " AND b.status='ACTIVE' AND b.default_slot=1 AND p.status='ACTIVE' AND p.id=?",
number(app, "user_id"), number(data, "package_id"));
require(product != null, "套餐未绑定或已下架");
RentalOrders.validatePackage(product);
Map<String, Object> price = RentalPricing.price(product, data);
return AjaxResult.success(map("package_id", price.get("id"), "network", price.get("network"),
"duration_seconds", price.get("duration_seconds"), "amount", amount(price, "sale_amount").toPlainString(),
"resource_quantity", price.get("resource_quantity"), "currency", "USDT"));
}
if ("create".equals(operation)) {
order = orders.create(number(app, "id"), number(app, "user_id"), data);
} else {
@@ -109,6 +125,8 @@ public class RentalApiController {
order.get("reclaim_status"),
"amount",
order.get("sale_amount"),
"duration_seconds",
order.get("duration_seconds"),
"refunded_amount",
order.get("refunded_amount")));
}
@@ -0,0 +1,135 @@
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 org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* 商户接收端示例,默认不注册。同步与异步指接收端的处理方式,均通过POST接收云端通知,
* 不把浏览器跳转当作可信订单结果。复制到商户项目时应一并迁移验签工具及收件箱表。
*/
@RestController
@org.springframework.scheduling.annotation.EnableScheduling
@ConditionalOnProperty(name = "rental.callback-demo.enabled", havingValue = "true")
@RequestMapping("/api/rental/v1/demo/callback")
public class RentalCallbackDemoController {
private final RentalStore store;
private final ObjectMapper json;
private final TransactionTemplate transaction;
@Value("${rental.callback-demo.api-key:}")
private String apiKey;
@Value("${rental.callback-demo.api-secret:}")
private String apiSecret;
public RentalCallbackDemoController(RentalStore store, ObjectMapper json,
org.springframework.transaction.PlatformTransactionManager transactionManager) {
this.store = store;
this.json = json;
this.transaction = new TransactionTemplate(transactionManager);
}
/** 同步:验签、去重和示例业务记录全部提交成功后,才返回纯文本ok。 */
@PostMapping(value = "/sync", consumes = "application/json", produces = "text/plain")
public ResponseEntity<String> sync(HttpServletRequest request) {
return receive(request, false);
}
/** 异步:先持久化收件箱再确认,由后台扫描处理;进程重启不丢通知。 */
@PostMapping(value = "/async", consumes = "application/json", produces = "text/plain")
public ResponseEntity<String> async(HttpServletRequest request) {
return receive(request, true);
}
private ResponseEntity<String> receive(HttpServletRequest request, boolean asynchronous) {
final String body;
final Map<String, Object> event;
try {
require(!apiKey.isEmpty() && !apiSecret.isEmpty(), "请配置示例接收端凭证");
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int size;
while ((size = request.getInputStream().read(buffer)) != -1) {
require(output.size() + size <= 65536, "通知超过64KiB");
output.write(buffer, 0, size);
}
body = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(java.nio.charset.CodingErrorAction.REPORT)
.decode(java.nio.ByteBuffer.wrap(output.toByteArray())).toString();
RentalJson.bounded(body);
verify(apiKey, apiSecret, request.getHeader("X-Rent-Key"),
Long.parseLong(request.getHeader("X-Rent-Timestamp")),
request.getHeader("X-Rent-Nonce"), request.getRequestURI(), body,
request.getHeader("X-Rent-Signature"), System.currentTimeMillis());
event = json.readValue(body, new TypeReference<Map<String, Object>>() { });
input(event, "event_no", 64);
input(event, "order_no", 64);
input(event, "event_type", 64);
} catch (Exception exception) {
// 绝不回显原始通知、签名或Secret。
return ResponseEntity.status(400).body("invalid notification");
}
try {
transaction.execute(status -> {
// 独立域记录随机数;重复HTTP报文拒绝,合法重投会携带新的随机数。
store.insert("nonce", map("api_key", apiKey, "scope", "DEMO_WEBHOOK",
"nonce", request.getHeader("X-Rent-Nonce"), "expires_at", after(180)));
// 唯一event_no防止并发重复入账;冲突回滚后等待云端使用新nonce重投。
Map<String, Object> existing = store.one(
"SELECT body_hash FROM rent_callback_demo_inbox WHERE event_no=? FOR UPDATE",
text(event, "event_no"));
if (existing != null) {
require(RentalCrypto.sha256(body).equals(text(existing, "body_hash")), "事件内容冲突");
return null;
}
store.execute("INSERT INTO rent_callback_demo_inbox"
+ " (event_no,order_no,event_type,body_hash,processed,created_at) VALUES(?,?,?,?,?,?)",
text(event, "event_no"), text(event, "order_no"), text(event, "event_type"),
RentalCrypto.sha256(body), asynchronous ? 0 : 1, now());
// 同步示例业务为记录已验证事件;真实业务应在本事务中按订单状态机更新。
return null;
});
return ResponseEntity.ok("ok");
} catch (Exception exception) {
return ResponseEntity.status(503).body("retry later");
}
}
/** 验证实际原文及WEBHOOK域;代理必须保留回调路径,不可二次序列化JSON。 */
public static void verify(String expectedKey, String secret, String key, long timestamp,
String nonce, String path, String body, String signature, long now) {
require(expectedKey != null && !expectedKey.isEmpty() && secret != null && !secret.isEmpty()
&& expectedKey.equals(key) && nonce != null && nonce.matches("[A-Za-z0-9_-]{16,64}")
&& timestamp > now - 60000 && timestamp < now + 60000, "通知认证参数无效");
require(RentalCrypto.equal(RentalCrypto.sign(secret, "WEBHOOK", key, timestamp,
nonce, "POST", path, body), signature), "通知签名无效");
}
/** 扫描持久化待处理事件;异常回滚,下次继续。无需依赖内存队列。 */
@Scheduled(fixedDelay = 3000)
public void consume() {
transaction.execute(status -> {
store.execute("DELETE FROM rent_nonce WHERE scope='DEMO_WEBHOOK' AND expires_at<? LIMIT 1000", now());
for (Map<String, Object> event : store.rows("SELECT event_no FROM rent_callback_demo_inbox"
+ " WHERE processed=0 ORDER BY created_at LIMIT 20 FOR UPDATE")) {
// 演示业务为标记验证事件已消费。实际业务在此事务中更新本地订单,
// 使用event_no唯一键去重,并校验order_event_sequence避免倒序覆盖新状态。
store.execute("UPDATE rent_callback_demo_inbox SET processed=1 WHERE event_no=?",
event.get("event_no"));
}
return null;
});
}
}
@@ -76,6 +76,10 @@ public class RentalOrders {
receiver,
"notify_url",
notify)));
// 兼容旧订单请求摘要;只有显式指定租期时才附加租期,重试不得改变租期。
if (request.containsKey("duration_seconds")) {
hash = RentalCrypto.sha256(hash + ":" + number(request, "duration_seconds"));
}
if (existing != null) {
require(hash.equals(text(existing, "request_hash")), "同一商户订单号参数不一致");
return existing;
@@ -97,6 +101,11 @@ public class RentalOrders {
text(product, "resource_type").equals(text(request, "resource_type")),
"资源类型与套餐不符");
}
product = RentalPricing.price(product, request);
if (request.containsKey("expected_amount")) {
require(amount(product, "sale_amount").compareTo(amount(request, "expected_amount")) == 0,
"套餐价格已变更,请重新获取报价后确认");
}
Map<String, Object> account = funds.account(user, network(text(product, "network")));
account = store.get("account", number(account, "id"), true);
require("ACTIVE".equals(text(account, "status")), "租赁账户已冻结");
@@ -0,0 +1,28 @@
package com.ruoyi.system.rental;
import static com.ruoyi.system.rental.RentalValues.*;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
/** 套餐基础租期为计费单位;报价与下单共用,禁止信任浏览器计算的金额。 */
public final class RentalPricing {
private RentalPricing() { }
public static Map<String, Object> price(Map<String, Object> product, Map<String, Object> request) {
long base = number(product, "duration_seconds");
long duration = request.containsKey("duration_seconds")
? number(request, "duration_seconds") : base;
require(base > 0 && duration > 0 && duration % base == 0
&& duration / base <= 720, "租赁时长必须为套餐基础租期的1至720倍");
BigDecimal units = BigDecimal.valueOf(duration / base);
Map<String, Object> result = new HashMap<>(product);
result.put("duration_seconds", duration);
result.put("sale_amount", amount(product, "sale_amount").multiply(units));
result.put("supplier_amount", amount(product, "supplier_amount").multiply(units));
require(amount(result, "sale_amount").precision() <= 30
&& amount(result, "supplier_amount").precision() <= 30, "租赁费用超过允许范围");
return result;
}
}
@@ -407,6 +407,105 @@ public class RentalBusinessTest {
new DataSourceTransactionManager(source));
}
@Test
public void extendedDurationHoldsQuotedFundsAndRetryDoesNotChargeAgain() {
Map<String, Object> request = map("package_id", product, "merchant_order_no", "LONG-RENT",
"receiver_address", ADDRESS, "duration_seconds", 7200, "expected_amount", "20.000000");
Map<String, Object> order = tx.execute(status -> orders.create(app, 10, request));
assertEquals(7200, number(order, "duration_seconds"));
assertEquals(money("20"), amount(order, "sale_amount"));
assertEquals(money("16"), amount(order, "supplier_amount"));
assertEquals(money("80"), amount(store.get("account", payer, false), "available_amount"));
assertEquals(number(order, "id"), number(tx.execute(status -> orders.create(app, 10, request)), "id"));
assertEquals(money("20"), amount(store.get("account", payer, false), "frozen_amount"));
request.put("duration_seconds", 3600);
expectFailure(() -> tx.execute(status -> orders.create(app, 10, request)));
request.put("merchant_order_no", "PRICE-CHANGED");
expectFailure(() -> tx.execute(status -> orders.create(app, 10, request)));
assertEquals(money("80"), amount(store.get("account", payer, false), "available_amount"));
}
@Test
public void callbackDemoPersistsBeforeAckDeduplicatesAndRecoversAsyncInbox() throws Exception {
store.execute("CREATE TABLE rent_callback_demo_inbox(event_no VARCHAR(64) PRIMARY KEY,"
+ "order_no VARCHAR(64),event_type VARCHAR(64),body_hash VARCHAR(64),"
+ "processed INT,created_at TIMESTAMP)");
RentalCallbackDemoController controller = new RentalCallbackDemoController(store, json, tx.getTransactionManager());
for (String fieldName : Arrays.asList("apiKey", "apiSecret")) {
java.lang.reflect.Field field = RentalCallbackDemoController.class.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(controller, fieldName.equals("apiKey") ? "RKdemo" : "test-secret");
}
String body = "{\"event_no\":\"WH-DEMO\",\"order_no\":\"RO-DEMO\",\"event_type\":\"DELIVERED\"}";
assertEquals("ok", controller.async(demoRequest("async", body, "test-secret")).getBody());
assertEquals(0, number(store.one("SELECT * FROM rent_callback_demo_inbox"), "processed"));
// 模拟进程重启后由持久化扫描恢复,无需内存队列。
controller.consume();
assertEquals(1, number(store.one("SELECT * FROM rent_callback_demo_inbox"), "processed"));
assertEquals("ok", controller.async(demoRequest("async", body, "test-secret")).getBody());
assertEquals(1, store.rows("SELECT * FROM rent_callback_demo_inbox").size());
assertEquals(400, controller.sync(demoRequest("sync", body, "wrong-secret")).getStatusCodeValue());
String second = body.replace("WH-DEMO", "WH-SYNC");
assertEquals("ok", controller.sync(demoRequest("sync", second, "test-secret")).getBody());
assertEquals(1, number(store.one("SELECT * FROM rent_callback_demo_inbox WHERE event_no='WH-SYNC'"), "processed"));
assertEquals(503, controller.sync(demoRequest("sync", body.replace("DELIVERED", "CANCELLED"), "test-secret")).getStatusCodeValue());
}
@Test
@SuppressWarnings("unchecked")
public void signedMerchantQuoteAndCreateWorkWithoutBackendLogin() throws Exception {
Map<String, Object> credential = tx.execute(status -> identity.issue("APP", app, 10));
String key = text(credential, "api_key"), secret = text(credential, "api_secret");
RentalApiController controller = new RentalApiController(identity, store, orders, json);
Map<String, Object> data = map("package_id", product, "merchant_order_no", "API-RENT",
"duration_seconds", 7200, "receiver_address", ADDRESS);
Map<String, Object> quote = (Map<String, Object>) controller.execute("quote",
signedRequest("/api/rental/v1/quote", json.writeValueAsString(data), key, secret, "API")).get("data");
assertEquals("20.000000", quote.get("amount"));
assertEquals(money("100"), amount(store.get("account", payer, false), "available_amount"));
data.put("expected_amount", quote.get("amount"));
String body = json.writeValueAsString(data);
Map<String, Object> result = (Map<String, Object>) tx.execute(status -> {
try {
return controller.execute("create", signedRequest("/api/rental/v1/create", body, key, secret, "API"));
} catch (Exception exception) {
throw new IllegalArgumentException(exception);
}
}).get("data");
assertEquals(7200, number(result, "duration_seconds"));
assertEquals(money("20"), amount(result, "amount"));
assertEquals(money("80"), amount(store.get("account", payer, false), "available_amount"));
}
/** Servlet代理保留原始字节,无需启动真实HTTP端口。 */
private javax.servlet.http.HttpServletRequest demoRequest(String operation, String body, String secret) {
return signedRequest("/api/rental/v1/demo/callback/" + operation, body, "RKdemo", secret, "WEBHOOK");
}
private javax.servlet.http.HttpServletRequest signedRequest(String path, String body,
String key, String secret, String scope) {
String nonce = RentalCrypto.random();
long timestamp = System.currentTimeMillis();
Map<String, Object> headers = map("X-Rent-Key", key, "X-Rent-Timestamp", Long.toString(timestamp),
"X-Rent-Nonce", nonce, "X-Rent-Signature",
RentalCrypto.sign(secret, scope, key, timestamp, nonce, "POST", path, body));
java.io.ByteArrayInputStream input = new java.io.ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8));
javax.servlet.ServletInputStream stream = new javax.servlet.ServletInputStream() {
@Override public int read() { return input.read(); }
@Override public boolean isFinished() { return input.available() == 0; }
@Override public boolean isReady() { return true; }
@Override public void setReadListener(javax.servlet.ReadListener listener) { }
};
return (javax.servlet.http.HttpServletRequest) java.lang.reflect.Proxy.newProxyInstance(
getClass().getClassLoader(), new Class<?>[] {javax.servlet.http.HttpServletRequest.class},
(proxy, method, args) -> {
if ("getHeader".equals(method.getName())) { return headers.get(args[0]); }
if ("getRequestURI".equals(method.getName())) { return path; }
if ("getInputStream".equals(method.getName())) { return stream; }
return null;
});
}
private Map<String, Object> create(String number) {
return tx.execute(
status ->
@@ -0,0 +1,43 @@
package com.ruoyi.system.rental;
import static com.ruoyi.system.rental.RentalValues.*;
import static org.junit.Assert.*;
import java.math.BigDecimal;
import java.util.Map;
import org.junit.Test;
/** 计费与回调签名协议的纯函数回归,不访问外部服务。 */
public class RentalPricingTest {
@Test
public void durationScalesBothPricesWithoutChangingQuantityOrOriginal() {
Map<String, Object> product = map("duration_seconds", 3600, "sale_amount", "3.000000",
"supplier_amount", "2.000000", "resource_quantity", 65000);
Map<String, Object> price = RentalPricing.price(product, map("duration_seconds", 7200));
assertEquals(new BigDecimal("6.000000"), amount(price, "sale_amount"));
assertEquals(new BigDecimal("4.000000"), amount(price, "supplier_amount"));
assertEquals(65000, number(price, "resource_quantity"));
assertEquals(3600, number(product, "duration_seconds"));
for (long duration : new long[] {0, -1, 3601, 3600L * 721}) {
assertThrows(IllegalArgumentException.class,
() -> RentalPricing.price(product, map("duration_seconds", duration)));
}
}
@Test
public void callbackRejectsWrongScopeTamperingPathAndExpiredTime() {
long timestamp = System.currentTimeMillis();
String key = "RKdemo", secret = "test-secret", nonce = "1234567890abcdef";
String path = "/api/rental/v1/demo/callback/sync", body = "{\"event_no\":\"WH1\"}";
String signature = RentalCrypto.sign(secret, "WEBHOOK", key, timestamp, nonce, "POST", path, body);
RentalCallbackDemoController.verify(key, secret, key, timestamp, nonce, path, body, signature, timestamp);
assertThrows(IllegalArgumentException.class, () -> RentalCallbackDemoController.verify(
key, secret, key, timestamp, nonce, path, body + " ", signature, timestamp));
assertThrows(IllegalArgumentException.class, () -> RentalCallbackDemoController.verify(
key, secret, key, timestamp, nonce, path + "x", body, signature, timestamp));
assertThrows(IllegalArgumentException.class, () -> RentalCallbackDemoController.verify(
key, secret, key, timestamp, nonce, path, body, signature, timestamp + 61000));
String apiSignature = RentalCrypto.sign(secret, "API", key, timestamp, nonce, "POST", path, body);
assertThrows(IllegalArgumentException.class, () -> RentalCallbackDemoController.verify(
key, secret, key, timestamp, nonce, path, body, apiSignature, timestamp));
}
}