1.PROXY\_ACCOUNT 租赁账户,首页中的租赁套餐 ,立即租赁按钮不可操作,帮我完成这个功能,点击立即租赁,跳出输入地址,apiKey,apiSecret,时长,对接地址,回调地址等,然后显示预计费用,然后调用租赁api 2. 帮我实现回调地址同步和异步验证的demo的controller
This commit is contained in:
1 parent
127d575a1c
commit
8dcb313454
9 files changed
+408
-3
No files matched your search
@@ -0,0 +1,62 @@
|
|||||||
|
# 租赁API下单与商户回调示例
|
||||||
|
|
||||||
|
## 首页立即租赁
|
||||||
|
|
||||||
|
PROXY_ACCOUNT 的“我的套餐”点击立即租赁,填写资源接收地址、应用 API Key / Secret、租期(秒)、API对接基地址、可选回调地址、商户订单号。先获取预计费用,再点击确认费用并租赁。移除了该按钮对后台 `rent:order:create` 权限的依赖,实际下单仍由应用凭证验签和所属用户的套餐绑定、账户余额共同校验。
|
||||||
|
|
||||||
|
Secret只在弹窗内存中用于签名,关闭弹窗清除,不写浏览器缓存、不作为请求参数发送。浏览器签名使用Web Crypto,需要HTTPS页面或localhost。应用Secret只在签发时展示,遗失时请重新签发。不要填节点凭证。所填凭证决定实际应用和扣费用户;填写当前账户自己的应用凭证。
|
||||||
|
|
||||||
|
默认API基地址为当前前端配置的代理前缀,例如 `/prod-api`。远程对接填写 `https://rent.example.com`,不含 `/api/rental/v1/create`;远程服务需允许浏览器当前来源、POST和X-Rent-*请求头。反向代理应将前缀去除,使服务端看到原始 `/api/rental/v1/quote` 或 `/api/rental/v1/create` 路径。时钟需同步。
|
||||||
|
|
||||||
|
## 报价与计费
|
||||||
|
|
||||||
|
`POST /api/rental/v1/quote` 和 `create` 都要求 `X-Rent-Key`、`X-Rent-Timestamp`(毫秒)、`X-Rent-Nonce`、`X-Rent-Signature`。HMAC协议保持不变:API域、POST、服务端实际路径、原始UTF-8请求体SHA256,按换行连接后HMAC-SHA256,小写十六进制。签名后不得重新序列化JSON。
|
||||||
|
|
||||||
|
示例请求体(两接口共用,create额外带expected_amount):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"package_id": 1,
|
||||||
|
"duration_seconds": 7200,
|
||||||
|
"receiver_address": "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf",
|
||||||
|
"merchant_order_no": "WEB_UNIQUE_ORDER_NO",
|
||||||
|
"notify_url": "https://merchant.example.com/api/rental/v1/demo/callback/async"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
报价返回 `amount`(精确十进制字符串)、`currency=USDT`、`duration_seconds`、`network`、`resource_quantity`。确认下单传 `expected_amount`,服务端重新计算并比较,价格变更则拒绝。所有费用使用BigDecimal。
|
||||||
|
|
||||||
|
租期为套餐基础租期的1至720个整数倍,总售价、供应商毛收入同比例增加,资源数量保持不变。例如基础3600秒、售价3USDT,7200秒为6USDT。该规则同时作用于登录入口及外部API;不传租期继续使用基础租期,兼容现有调用。实际资源回收按订单租期快照执行。请求超时后使用相同商户单号及原参数重试;不要更换单号重复扣费。
|
||||||
|
|
||||||
|
回调地址只允许公网HTTPS、443端口、无查询参数,不允许内网或回环目标。留空沿用应用默认地址。订单创建成功是同步API响应,不代表链上已经交付;以查询API及已验签异步通知为准。当前协议没有浏览器return_url跳转回调。
|
||||||
|
|
||||||
|
## 同步、异步验签Controller
|
||||||
|
|
||||||
|
实现:`RentalCallbackDemoController`,默认关闭,仅演示商户接收端。部署于同一云端项目中,或连同验签工具、事务仓储迁入商户项目。
|
||||||
|
|
||||||
|
先执行 `sql/rent_callback_demo.sql` 创建独立演示收件箱;租赁基础表(含rent_nonce)仍需先初始化。然后通过外部配置启用,凭证必须是该应用当前ACTIVE凭证:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
rental:
|
||||||
|
callback-demo:
|
||||||
|
enabled: true
|
||||||
|
api-key: ${RENT_DEMO_API_KEY:}
|
||||||
|
api-secret: ${RENT_DEMO_API_SECRET:}
|
||||||
|
```
|
||||||
|
|
||||||
|
接口使用既有 `/api/rental/v1/**` 公开入口,但每个请求都验证WEBHOOK域签名、Key、60秒时间窗、随机数和原始请求体;没有关闭认证。不要在日志输出Secret、签名或请求体。轮换应用凭证后同步更新接收端凭证;生产建议支持受控的多Key过渡。
|
||||||
|
|
||||||
|
| 接口 | 处理流程 | 成功确认 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| POST /api/rental/v1/demo/callback/sync | 验签→随机数防重放→event_no去重→同步事务记录处理结果 | 事务提交后返回HTTP 200、纯文本ok |
|
||||||
|
| POST /api/rental/v1/demo/callback/async | 验签→随机数防重放→event_no去重→持久化待处理收件箱 | 持久化提交后返回HTTP 200、纯文本ok;每3秒扫描事务处理 |
|
||||||
|
|
||||||
|
无效签名返回400,持久化失败返回503,不返回ok。并发事件冲突会回滚并让云端用新随机数重投;重复事件内容一致则确认,内容冲突拒绝。同一HTTP报文重放不通过随机数唯一约束。异步处理不使用易丢失的内存队列,重启后扫描继续。
|
||||||
|
|
||||||
|
示例业务仅记录验签事件/消费标记,不执行真实商户履约或入账。接入实际业务时,应保存所需通知字段,在同一事务中按本地订单号及event_no更新业务,并利用order_event_sequence防止乱序状态回退;外部副作用使用事务发件箱。不要照搬演示标记替代实际业务处理。
|
||||||
|
|
||||||
|
租赁云端仅在回调HTTP 200且正文严格为`ok`时确认,失败按既有任务重试,达到上限保留DEAD记录供处理。应用当前有效凭证用于签名,WEBHOOK域与API域严格隔离。
|
||||||
|
|
||||||
|
## 验证
|
||||||
|
|
||||||
|
JDK8下64项租赁测试通过,覆盖已签名报价/下单、报价不扣费、租期计费、冻结资金、幂等重试、价格变化拒绝,以及回调原文/路径/域/时间窗验签、落库确认、重复事件及异步消费。前端ESLint、Vue模板/CSS解析、独立HMAC及UTF8签名校验通过,staging完整构建成功;保留其他模块已有导出缺失和资源体积警告。实际浏览器、公网回调、数据库迁移及链上交付尚需部署后联调。
|
||||||
@@ -6,9 +6,9 @@
|
|||||||
|
|
||||||
PROXY_ACCOUNT 首页“租赁套餐”及应用页的套餐区统一为单套餐卡片,展示名称、网络、资源类型/数量、租期、冗余和 USDT 单价;不显示用户可选套餐列表。
|
PROXY_ACCOUNT 首页“租赁套餐”及应用页的套餐区统一为单套餐卡片,展示名称、网络、资源类型/数量、租期、冗余和 USDT 单价;不显示用户可选套餐列表。
|
||||||
|
|
||||||
点击立即租赁后选择本人启用应用、填写接收地址并确认,商户单号自动生成;请求失败保留单号供幂等重试。请求固定用户确认时的套餐ID,管理员切换套餐后服务端拒绝旧ID的新单,避免悄悄换价。订单结果在“我的订单”查看。
|
点击立即租赁后填写应用API Key、Secret、接收地址、租期、API基地址及可选回调地址,先获取服务端报价再确认下单,商户单号自动生成;请求失败保留单号供幂等重试。请求固定用户确认时的套餐ID,管理员切换套餐后服务端拒绝旧ID的新单,避免悄悄换价。订单结果在“我的订单”查看。详见[API下单及回调示例](merchant-order-callback-demo.md)。
|
||||||
|
|
||||||
无当前绑定时引导联系管理员,套餐下架时展示不可用提示并禁止下单。无下单权限时按钮禁用。
|
无当前绑定时引导联系管理员,套餐下架时展示不可用提示并禁止下单。API下单通过应用凭证认证,不依赖后台rent:order:create权限。
|
||||||
|
|
||||||
## 管理及部署
|
## 管理及部署
|
||||||
|
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ public class RentalApiController {
|
|||||||
public AjaxResult execute(@PathVariable String operation, HttpServletRequest request)
|
public AjaxResult execute(@PathVariable String operation, HttpServletRequest request)
|
||||||
throws Exception {
|
throws Exception {
|
||||||
require(
|
require(
|
||||||
Arrays.asList("create", "query", "packages").contains(operation)
|
Arrays.asList("create", "query", "packages", "quote").contains(operation)
|
||||||
&& request.getQueryString() == null,
|
&& request.getQueryString() == null,
|
||||||
"接口或查询参数不支持");
|
"接口或查询参数不支持");
|
||||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||||
@@ -79,6 +79,22 @@ public class RentalApiController {
|
|||||||
return AjaxResult.success(products);
|
return AjaxResult.success(products);
|
||||||
}
|
}
|
||||||
Map<String, Object> order;
|
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)) {
|
if ("create".equals(operation)) {
|
||||||
order = orders.create(number(app, "id"), number(app, "user_id"), data);
|
order = orders.create(number(app, "id"), number(app, "user_id"), data);
|
||||||
} else {
|
} else {
|
||||||
@@ -109,6 +125,8 @@ public class RentalApiController {
|
|||||||
order.get("reclaim_status"),
|
order.get("reclaim_status"),
|
||||||
"amount",
|
"amount",
|
||||||
order.get("sale_amount"),
|
order.get("sale_amount"),
|
||||||
|
"duration_seconds",
|
||||||
|
order.get("duration_seconds"),
|
||||||
"refunded_amount",
|
"refunded_amount",
|
||||||
order.get("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,
|
receiver,
|
||||||
"notify_url",
|
"notify_url",
|
||||||
notify)));
|
notify)));
|
||||||
|
// 兼容旧订单请求摘要;只有显式指定租期时才附加租期,重试不得改变租期。
|
||||||
|
if (request.containsKey("duration_seconds")) {
|
||||||
|
hash = RentalCrypto.sha256(hash + ":" + number(request, "duration_seconds"));
|
||||||
|
}
|
||||||
if (existing != null) {
|
if (existing != null) {
|
||||||
require(hash.equals(text(existing, "request_hash")), "同一商户订单号参数不一致");
|
require(hash.equals(text(existing, "request_hash")), "同一商户订单号参数不一致");
|
||||||
return existing;
|
return existing;
|
||||||
@@ -97,6 +101,11 @@ public class RentalOrders {
|
|||||||
text(product, "resource_type").equals(text(request, "resource_type")),
|
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")));
|
Map<String, Object> account = funds.account(user, network(text(product, "network")));
|
||||||
account = store.get("account", number(account, "id"), true);
|
account = store.get("account", number(account, "id"), true);
|
||||||
require("ACTIVE".equals(text(account, "status")), "租赁账户已冻结");
|
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));
|
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) {
|
private Map<String, Object> create(String number) {
|
||||||
return tx.execute(
|
return tx.execute(
|
||||||
status ->
|
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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
-- 仅启用回调接收端Demo时执行;正常租赁服务不依赖此表。不记录Secret或签名。
|
||||||
|
CREATE TABLE IF NOT EXISTS rent_callback_demo_inbox (
|
||||||
|
event_no VARCHAR(64) NOT NULL COMMENT '云端事件唯一编号,防重复消费',
|
||||||
|
order_no VARCHAR(64) NOT NULL COMMENT '云端租赁订单编号',
|
||||||
|
event_type VARCHAR(64) NOT NULL COMMENT '事件类型',
|
||||||
|
body_hash CHAR(64) NOT NULL COMMENT '原始请求体SHA256,防同事件内容冲突',
|
||||||
|
processed TINYINT NOT NULL DEFAULT 0 COMMENT '0持久化待处理,1已处理',
|
||||||
|
created_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||||
|
PRIMARY KEY (event_no),
|
||||||
|
KEY idx_demo_pending (processed,created_at)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='可选的商户回调接收端演示收件箱';
|
||||||
Reference in new issue
Block a user