fix: verify payment callbacks

This commit is contained in:
lu7213 committed 2026-10-15 04:06:20 -04:00
1 parent 6d868552eb
commit a75869342c
3 files changed
+229 -21

No files matched your search

@@ -8,6 +8,7 @@ import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.dto.EncryptedRequest;
import com.ruoyi.system.security.RsaKeyUtil;
import com.ruoyi.system.security.SecureClient;
import com.ruoyi.system.service.PaymentSignatureService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -16,21 +17,23 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientResponseException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;
@@ -57,17 +60,42 @@ public class SysUsdtDemoController {
@ApiOperation(value = "notify")
@ResponseBody
@PostMapping("/notify")
public String notify(HttpServletRequest request, HttpServletResponse response,
public ResponseEntity<String> notify(
@RequestHeader(value = "X-Payment-Api-Key", required = false) String apiKey,
@RequestHeader(value = "X-Payment-Signature", required = false) String signature,
@RequestBody(required = false) String body) {
// 回调正文可能包含订单数据,只记录收到事件,避免在日志中扩散业务报文。
log.info("支付演示回调已接收");
return "ok";
try {
JSONObject payload = parseCallbackPayload(body);
if (!verifyCallback(payload, apiKey, signature)) {
log.warn("支付演示异步回调验签失败");
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("invalid signature");
}
// 不记录完整回调正文、签名或API Key,避免业务数据和凭据进入日志。
log.info("支付演示异步回调验签成功,orderId={}", payload.getString("order_id"));
return ResponseEntity.ok("ok");
} catch (Exception exception) {
log.warn("支付演示异步回调格式或配置校验失败,异常类型={}",
exception.getClass().getSimpleName());
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("invalid signature");
}
}
@GetMapping("/redirect")
@ResponseBody
public String redirect() {
return "redirect SUCCESS";
public ResponseEntity<String> redirect(
@RequestParam(value = "order_id", required = false) String orderId,
@RequestParam(value = "trade_id", required = false) String tradeId,
@RequestParam(value = "status", required = false) Integer status,
@RequestParam(value = "transaction_id", required = false) String transactionId,
@RequestParam(value = "api_key", required = false) String apiKey,
@RequestParam(value = "signature", required = false) String signature) {
Map<String, Object> values = callbackValues(orderId, tradeId, status, transactionId);
if (!hasRequiredCallbackFields(values) || !verifyCallback(values, apiKey, signature)) {
log.warn("支付演示同步跳转验签失败");
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("invalid signature");
}
log.info("支付演示同步跳转验签成功,orderId={}", orderId);
return ResponseEntity.ok("redirect SUCCESS");
}
/** 使用 RSA-AES-HMAC 协议创建支付订单。 */
@@ -157,6 +185,59 @@ public class SysUsdtDemoController {
}
}
/** 将异步通知JSON规范化为签名字段,拒绝嵌套值和缺失的核心订单字段。 */
private JSONObject parseCallbackPayload(String body) {
if (StringUtils.isBlank(body)) {
throw new CustomException("回调正文为空");
}
JSONObject payload = JSON.parseObject(body);
if (payload == null || !hasRequiredCallbackFields(payload)) {
throw new CustomException("回调参数不完整");
}
for (Object value : payload.values()) {
if (value instanceof Map || value instanceof Iterable) {
throw new CustomException("回调参数格式错误");
}
}
return payload;
}
private Map<String, Object> callbackValues(String orderId, String tradeId,
Integer status, String transactionId) {
Map<String, Object> values = new HashMap<String, Object>();
values.put("order_id", orderId);
values.put("trade_id", tradeId);
values.put("status", status);
values.put("transaction_id", transactionId);
return values;
}
private boolean hasRequiredCallbackFields(Map<String, ?> values) {
Object orderId = values.get("order_id");
Object tradeId = values.get("trade_id");
Object status = values.get("status");
return orderId != null && StringUtils.isNotBlank(String.valueOf(orderId))
&& tradeId != null && StringUtils.isNotBlank(String.valueOf(tradeId))
&& status != null && "2".equals(String.valueOf(status));
}
/** API Key和签名均使用常量时间比较,避免泄露匹配前缀。 */
private boolean verifyCallback(Map<String, ?> values, String apiKey, String signature) {
String expectedApiKey = requiredEnvWithAlias("PAYMENT_API_KEY", "PAYMENT_API_KEK");
if (!constantTimeEquals(expectedApiKey, apiKey)) {
return false;
}
return PaymentSignatureService.verify(values, requiredEnv("PAYMENT_API_SECRET"), signature);
}
private boolean constantTimeEquals(String expected, String actual) {
if (expected == null || actual == null) {
return false;
}
return MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8),
actual.getBytes(StandardCharsets.UTF_8));
}
private String normalizeWalletUserName(String value) {
if (StringUtils.isBlank(value)) {
return "demo-user-" + UUID.randomUUID().toString().replace("-", "");
@@ -168,7 +249,7 @@ public class SysUsdtDemoController {
return normalized;
}
private String requiredEnv(String name) {
protected String requiredEnv(String name) {
String value = System.getenv(name);
if (StringUtils.isBlank(value)) {
throw new CustomException("服务端缺少环境变量 " + name);
@@ -176,7 +257,7 @@ public class SysUsdtDemoController {
return value.trim();
}
private String requiredEnvWithAlias(String name, String alias) {
protected String requiredEnvWithAlias(String name, String alias) {
String value = System.getenv(name);
if (StringUtils.isBlank(value)) {
value = System.getenv(alias);
@@ -0,0 +1,89 @@
package com.ruoyi.web.controller.system;
import com.alibaba.fastjson.JSON;
import com.ruoyi.system.service.PaymentSignatureService;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class SysUsdtDemoControllerTest {
private static final String API_KEY = "demo-api-key";
private static final String API_SECRET = "demo-api-secret-value";
private SysUsdtDemoController controller;
private Map<String, Object> values;
@Before
public void setUp() {
controller = new SysUsdtDemoController() {
@Override
protected String requiredEnv(String name) {
return API_SECRET;
}
@Override
protected String requiredEnvWithAlias(String name, String alias) {
return API_KEY;
}
};
values = new HashMap<String, Object>();
values.put("order_id", "merchant-1001");
values.put("trade_id", "trade-1001");
values.put("status", 2);
values.put("transaction_id", "tx-1001");
}
@Test
public void notifyShouldAcceptValidSignature() {
String signature = PaymentSignatureService.sign(values, API_SECRET);
ResponseEntity<String> response = controller.notify(API_KEY, signature,
JSON.toJSONString(values));
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("ok", response.getBody());
}
@Test
public void notifyShouldRejectForgedSignature() {
ResponseEntity<String> response = controller.notify(API_KEY, "forged",
JSON.toJSONString(values));
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
assertEquals("invalid signature", response.getBody());
}
@Test
public void notifyShouldRejectWrongApiKey() {
String signature = PaymentSignatureService.sign(values, API_SECRET);
ResponseEntity<String> response = controller.notify("wrong-key", signature,
JSON.toJSONString(values));
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
}
@Test
public void redirectShouldAcceptValidSignature() {
String signature = PaymentSignatureService.sign(values, API_SECRET);
ResponseEntity<String> response = controller.redirect("merchant-1001", "trade-1001",
2, "tx-1001", API_KEY, signature);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("redirect SUCCESS", response.getBody());
}
@Test
public void redirectShouldRejectMissingOrInvalidSignature() {
ResponseEntity<String> response = controller.redirect("merchant-1001", "trade-1001",
2, "tx-1001", API_KEY, null);
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
}
}
@@ -12,34 +12,72 @@ import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.Date;
/** 回调只在对方响应正文严格为 ok 时确认,失败保留未确认状态并重试。 */
@Component
public class PaymentCallbackWorker {
private static final Logger LOGGER = LoggerFactory.getLogger(PaymentCallbackWorker.class);
@Autowired private IUsdtOrdersService orders;
@Autowired private IAppApiKeysService keys;
@Autowired private AppPrivateKeyCipher privateKeyCipher;
private final RestTemplate http = new RestTemplate();
@Scheduled(fixedDelay = 30000L)
private final RestTemplate http;
public PaymentCallbackWorker() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(60000);
factory.setReadTimeout(60000);
this.http = new RestTemplate(factory);
}
@Scheduled(fixedDelay = 10000L)
public void dispatch() {
for (UsdtOrdersPlus order : orders.list(new LambdaQueryWrapper<UsdtOrdersPlus>().eq(UsdtOrdersPlus::getStatus, 2).eq(UsdtOrdersPlus::getCallbackConfirm, 2).lt(UsdtOrdersPlus::getCallbackNum, 10))) {
try {
if (order.getNotifyUrl() == null || order.getNotifyUrl().trim().isEmpty()) continue;
if (order.getNotifyUrl() == null || order.getNotifyUrl().trim().isEmpty()) {
// 兼容历史无通知地址订单,避免定时任务永久重复扫描。
order.setCallbackConfirm(1L);
continue;
}
HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON);
String body = "{\"order_id\":\"" + order.getOrderId() + "\",\"trade_id\":\"" + order.getTradeId() + "\",\"status\":" + order.getStatus() + ",\"transaction_id\":\"" + (order.getBlockTransactionId() == null ? "" : order.getBlockTransactionId()) + "\"}";
AppApiKeysPlus key = keys.getOne(new LambdaQueryWrapper<AppApiKeysPlus>().eq(AppApiKeysPlus::getAppId, order.getAppId())
.eq(AppApiKeysPlus::getStatus, 1).isNull(AppApiKeysPlus::getDeletedAt)
.and(wrapper -> wrapper.isNull(AppApiKeysPlus::getExpiredAt).or().gt(AppApiKeysPlus::getExpiredAt, new Date()))
.last("limit 1"));
java.util.Map<String, Object> signatureValues = new java.util.HashMap<String, Object>(); signatureValues.put("order_id", order.getOrderId()); signatureValues.put("trade_id", order.getTradeId()); signatureValues.put("status", order.getStatus()); signatureValues.put("transaction_id", order.getBlockTransactionId());
headers.set("X-Payment-Signature", key == null ? "" : PaymentSignatureService.sign(signatureValues, privateKeyCipher.decryptCredentialSecret(key.getApiSecret())));
headers.set("X-Payment-Api-Key", key == null ? "" : key.getApiKey());
ResponseEntity<String> response = http.postForEntity(order.getNotifyUrl(), new HttpEntity<String>(body, headers), String.class);
order.setCallbackNum(order.getCallbackNum() == null ? 1L : order.getCallbackNum() + 1L);
if (key == null || key.getApiKey() == null || key.getApiSecret() == null) {
throw new IllegalStateException("订单所属应用没有有效回调密钥");
}
Map<String, Object> signatureValues = new HashMap<String, Object>();
signatureValues.put("order_id", order.getOrderId());
signatureValues.put("trade_id", order.getTradeId());
signatureValues.put("status", order.getStatus());
signatureValues.put("transaction_id", order.getBlockTransactionId());
headers.set("X-Payment-Signature", PaymentSignatureService.sign(signatureValues,
privateKeyCipher.decryptCredentialSecret(key.getApiSecret())));
headers.set("X-Payment-Api-Key", key.getApiKey());
ResponseEntity<String> response = http.postForEntity(order.getNotifyUrl(),
new HttpEntity<String>(JSON.toJSONString(signatureValues), headers), String.class);
if (response.getStatusCode().is2xxSuccessful() && "ok".equalsIgnoreCase(response.getBody() == null ? "" : response.getBody().trim())) order.setCallbackConfirm(1L);
order.setUpdatedAt(new Date()); orders.updateById(order);
} catch (Exception ignored) { }
} catch (Exception exception) {
LOGGER.warn("订单支付回调失败,orderId={},异常类型={}", order.getOrderId(),
exception.getClass().getSimpleName());
} finally {
order.setCallbackNum(order.getCallbackNum() == null ? 1L : order.getCallbackNum() + 1L);
order.setUpdatedAt(new Date());
try {
orders.updateById(order);
} catch (Exception exception) {
// 单条订单状态落库失败不能阻塞同批次其他订单,下一轮仍会重新读取数据库状态。
LOGGER.error("订单支付回调状态更新失败,orderId={},异常类型={}", order.getOrderId(),
exception.getClass().getSimpleName());
}
}
}
}
}