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
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user