fix: verify payment callbacks
This commit is contained in:
1 parent
6d868552eb
commit
a75869342c
3 files changed
+229
-21
No files matched your search
+91
-10
@@ -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);
|
||||
|
||||
+89
@@ -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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user