diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/controller/AppApiKeysController.java b/ruoyi-system/src/main/java/com/ruoyi/system/controller/AppApiKeysController.java index e38cbc6..755d497 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/controller/AppApiKeysController.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/controller/AppApiKeysController.java @@ -32,14 +32,14 @@ public class AppApiKeysController extends BaseController { @PreAuthorize("@ss.hasPermi('system:keys:getByIds')" ) @PostMapping("/getByIds" ) public AjaxResult getByIds(@RequestBody Ids ids) { - List list = appApiKeysService.getByIds(ids.getLongIds(), false, AppApiKeysPlus::getApiSecret, AppApiKeysPlus::getId); + List list = appApiKeysService.getByIds(ids.getLongIds(), false, AppApiKeysPlus::getApiKey, AppApiKeysPlus::getId); return AjaxResult.success(list); } @PreAuthorize("@ss.hasPermi('system:keys:user-getByIds')" ) @PostMapping("/user/getByIds" ) public AjaxResult userGetByIds(@RequestBody Ids ids) { - List list = appApiKeysService.getByIds(ids.getLongIds(), true, AppApiKeysPlus::getApiSecret,AppApiKeysPlus::getUserId, AppApiKeysPlus::getId); + List list = appApiKeysService.getByIds(ids.getLongIds(), true, AppApiKeysPlus::getApiKey, AppApiKeysPlus::getUserId, AppApiKeysPlus::getId); return AjaxResult.success(list); } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/controller/PaymentApiController.java b/ruoyi-system/src/main/java/com/ruoyi/system/controller/PaymentApiController.java index a8d544c..5496d1f 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/controller/PaymentApiController.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/controller/PaymentApiController.java @@ -16,6 +16,7 @@ import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.net.URI; +import java.util.Date; /** 对外支付 API,统一使用 JSON 和签名校验。 */ @RestController @@ -29,8 +30,8 @@ public class PaymentApiController { public AjaxResult create(@RequestBody Map body) { String signature = String.valueOf(body.get("signature")); Long appId = parseLong(body.get("app_id")); - AppApiKeysPlus key = activeKey(appId); - if (key == null || !PaymentSignatureService.sign(body, key.getApiSecret()).equalsIgnoreCase(signature)) return AjaxResult.error("签名无效"); + AppApiKeysPlus key = activeKey(appId, body.get("api_key")); + if (key == null || !PaymentSignatureService.verify(body, key.getApiSecret(), signature)) return AjaxResult.error("签名无效"); String orderId = String.valueOf(body.get("order_id")); if (orderId.length() == 0 || orderId.length() > 32 || body.get("amount") == null || body.get("wallet_user_name") == null) return AjaxResult.error("缺少必要参数"); if (!validUrl(body.get("notify_url")) || (body.get("redirect_url") != null && !validUrl(body.get("redirect_url")))) return AjaxResult.error("回调地址无效"); @@ -49,13 +50,19 @@ public class PaymentApiController { @PostMapping("/query") public AjaxResult query(@RequestBody Map body) { - Long appId = parseLong(body.get("app_id")); AppApiKeysPlus key = activeKey(appId); String signature = String.valueOf(body.get("signature")); - if (key == null || !PaymentSignatureService.sign(body, key.getApiSecret()).equalsIgnoreCase(signature)) return AjaxResult.error("签名无效"); + Long appId = parseLong(body.get("app_id")); AppApiKeysPlus key = activeKey(appId, body.get("api_key")); String signature = String.valueOf(body.get("signature")); + if (key == null || !PaymentSignatureService.verify(body, key.getApiSecret(), signature)) return AjaxResult.error("签名无效"); UsdtOrdersPlus order = orders.getOne(new LambdaQueryWrapper().eq(UsdtOrdersPlus::getAppId, appId).eq(UsdtOrdersPlus::getOrderId, String.valueOf(body.get("order_id")))); if (order == null) return AjaxResult.error("订单不存在"); Map result = new HashMap(); result.put("order_id", order.getOrderId()); result.put("trade_id", order.getTradeId()); result.put("status", order.getStatus()); result.put("transaction_id", order.getBlockTransactionId()); return AjaxResult.success(result); } - private AppApiKeysPlus activeKey(Long appId) { return appId == null ? null : keys.getOne(new LambdaQueryWrapper().eq(AppApiKeysPlus::getAppId, appId).eq(AppApiKeysPlus::getStatus, 1)); } + private AppApiKeysPlus activeKey(Long appId, Object apiKey) { + if (appId == null || apiKey == null || String.valueOf(apiKey).trim().isEmpty()) return null; + return keys.getOne(new LambdaQueryWrapper().eq(AppApiKeysPlus::getAppId, appId) + .eq(AppApiKeysPlus::getApiKey, String.valueOf(apiKey)).eq(AppApiKeysPlus::getStatus, 1) + .isNull(AppApiKeysPlus::getDeletedAt) + .and(wrapper -> wrapper.isNull(AppApiKeysPlus::getExpiredAt).or().gt(AppApiKeysPlus::getExpiredAt, new Date()))); + } private Long parseLong(Object value) { try { return value == null ? null : Long.valueOf(String.valueOf(value)); } catch (Exception ex) { return null; } } private boolean validUrl(Object value) { try { if (value == null) return false; URI uri = new URI(String.valueOf(value)); return ("https".equalsIgnoreCase(uri.getScheme()) || "http".equalsIgnoreCase(uri.getScheme())) && uri.getHost() != null; } catch (Exception ex) { return false; } } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/AppApiKeys.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/AppApiKeys.java index 8717361..576c01e 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/AppApiKeys.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/AppApiKeys.java @@ -29,6 +29,10 @@ public class AppApiKeys extends BaseEntity @Excel(name = "用户") private Long userId; + /** API 公钥标识 */ + @Excel(name = "API Key") + private String apiKey; + /** 密钥 */ @JsonIgnore private String apiSecret; @@ -82,6 +86,15 @@ public class AppApiKeys extends BaseEntity { return userId; } + public void setApiKey(String apiKey) + { + this.apiKey = apiKey; + } + + public String getApiKey() + { + return apiKey; + } public void setApiSecret(String apiSecret) { this.apiSecret = apiSecret; @@ -143,6 +156,7 @@ public class AppApiKeys extends BaseEntity .append("id", getId()) .append("appId", getAppId()) .append("userId", getUserId()) + .append("apiKey", getApiKey()) .append("apiSecret", "") .append("status", getStatus()) .append("expiredAt", getExpiredAt()) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/AppApiKeysPlus.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/AppApiKeysPlus.java index c9211c6..10cf292 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/AppApiKeysPlus.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/AppApiKeysPlus.java @@ -33,6 +33,9 @@ public class AppApiKeysPlus implements Serializable /** 用户 */ @Excel(name = "用户") private Long userId; + /** API 公钥标识 */ + @Excel(name = "API Key") + private String apiKey; /** 密钥 */ @JsonIgnore private String apiSecret; @@ -80,6 +83,15 @@ public class AppApiKeysPlus implements Serializable { return userId; } + public void setApiKey(String apiKey) + { + this.apiKey = apiKey; + } + + public String getApiKey() + { + return apiKey; + } public void setApiSecret(String apiSecret) { this.apiSecret = apiSecret; @@ -141,6 +153,7 @@ public class AppApiKeysPlus implements Serializable .append("id", getId()) .append("appId", getAppId()) .append("userId", getUserId()) + .append("apiKey", getApiKey()) .append("apiSecret", "") .append("status", getStatus()) .append("expiredAt", getExpiredAt()) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/AppApiKeyCreateResult.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/AppApiKeyCreateResult.java index 9907e7f..742698c 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/AppApiKeyCreateResult.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/AppApiKeyCreateResult.java @@ -5,13 +5,16 @@ public class AppApiKeyCreateResult { private final Long id; private final Long appId; private final String apiSecret; + private final String apiKey; - public AppApiKeyCreateResult(Long id, Long appId, String apiSecret) { + public AppApiKeyCreateResult(Long id, Long appId, String apiKey, String apiSecret) { this.id = id; this.appId = appId; this.apiSecret = apiSecret; + this.apiKey = apiKey; } public Long getId() { return id; } public Long getAppId() { return appId; } public String getApiSecret() { return apiSecret; } + public String getApiKey() { return apiKey; } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/PaymentSignatureService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/PaymentSignatureService.java index 5eca38f..df4b21e 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/PaymentSignatureService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/PaymentSignatureService.java @@ -1,10 +1,13 @@ package com.ruoyi.system.service; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; import java.security.MessageDigest; +import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.TreeMap; -/** 支付 API 签名:按键排序拼接非空参数后追加 secret,MD5 小写。 */ +/** 支付 API 签名:按键排序拼接非空参数后使用 secret 计算 HMAC-SHA256。 */ public final class PaymentSignatureService { private PaymentSignatureService() { } public static String sign(Map values, String secret) { @@ -16,12 +19,21 @@ public final class PaymentSignatureService { text.append(entry.getKey()).append('=').append(entry.getValue()); } } - text.append(secret); try { - byte[] digest = MessageDigest.getInstance("MD5").digest(text.toString().getBytes("UTF-8")); + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256")); + byte[] digest = mac.doFinal(text.toString().getBytes("UTF-8")); StringBuilder result = new StringBuilder(); for (byte b : digest) result.append(String.format("%02x", b & 0xff)); return result.toString(); - } catch (Exception ex) { throw new IllegalStateException("MD5 unavailable", ex); } + } catch (Exception ex) { throw new IllegalStateException("HMAC-SHA256 unavailable", ex); } + } + + /** 使用常量时间比较签名,避免普通字符串比较泄露匹配前缀信息。 */ + public static boolean verify(Map values, String secret, String signature) { + if (secret == null || signature == null) return false; + byte[] expected = sign(values, secret).getBytes(StandardCharsets.US_ASCII); + byte[] actual = signature.toLowerCase().getBytes(StandardCharsets.US_ASCII); + return MessageDigest.isEqual(expected, actual); } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/AppApiKeysServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/AppApiKeysServiceImpl.java index 95a1aa0..30df6d7 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/AppApiKeysServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/AppApiKeysServiceImpl.java @@ -233,6 +233,10 @@ public class AppApiKeysServiceImpl extends ServiceImpl().eq(AppApiKeysPlus::getAppId, order.getAppId()).eq(AppApiKeysPlus::getStatus, 1)); + AppApiKeysPlus key = keys.getOne(new LambdaQueryWrapper().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 signatureValues = new java.util.HashMap(); 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, key.getApiSecret())); + headers.set("X-Payment-Api-Key", key == null ? "" : key.getApiKey()); ResponseEntity response = http.postForEntity(order.getNotifyUrl(), new HttpEntity(body, headers), String.class); order.setCallbackNum(order.getCallbackNum() == null ? 1L : order.getCallbackNum() + 1L); if (response.getStatusCode().is2xxSuccessful() && "ok".equalsIgnoreCase(response.getBody() == null ? "" : response.getBody().trim())) order.setCallbackConfirm(1L); diff --git a/ruoyi-system/src/main/resources/mapper/system/AppApiKeysMapper.xml b/ruoyi-system/src/main/resources/mapper/system/AppApiKeysMapper.xml index 6d13292..15ce22e 100644 --- a/ruoyi-system/src/main/resources/mapper/system/AppApiKeysMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/system/AppApiKeysMapper.xml @@ -8,6 +8,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" + @@ -17,7 +18,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" - select id, app_id, user_id, api_secret, status, expired_at, created_at, deleted_at, updated_at from app_api_keys + select id, app_id, user_id, api_key, api_secret, status, expired_at, created_at, deleted_at, updated_at from app_api_keys