新增apiKey和相关逻辑
This commit is contained in:
1 parent
bc772b8b15
commit
051f78b59c
9 files changed
+77
-15
No files matched your search
@@ -32,14 +32,14 @@ public class AppApiKeysController extends BaseController {
|
||||
@PreAuthorize("@ss.hasPermi('system:keys:getByIds')" )
|
||||
@PostMapping("/getByIds" )
|
||||
public AjaxResult getByIds(@RequestBody Ids ids) {
|
||||
List<AppApiKeysPlus> list = appApiKeysService.getByIds(ids.getLongIds(), false, AppApiKeysPlus::getApiSecret, AppApiKeysPlus::getId);
|
||||
List<AppApiKeysPlus> 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<AppApiKeysPlus> list = appApiKeysService.getByIds(ids.getLongIds(), true, AppApiKeysPlus::getApiSecret,AppApiKeysPlus::getUserId, AppApiKeysPlus::getId);
|
||||
List<AppApiKeysPlus> list = appApiKeysService.getByIds(ids.getLongIds(), true, AppApiKeysPlus::getApiKey, AppApiKeysPlus::getUserId, AppApiKeysPlus::getId);
|
||||
return AjaxResult.success(list);
|
||||
}
|
||||
|
||||
|
||||
@@ -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<String, Object> 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<String, Object> 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<UsdtOrdersPlus>().eq(UsdtOrdersPlus::getAppId, appId).eq(UsdtOrdersPlus::getOrderId, String.valueOf(body.get("order_id"))));
|
||||
if (order == null) return AjaxResult.error("订单不存在");
|
||||
Map<String, Object> result = new HashMap<String, Object>(); 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<AppApiKeysPlus>().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<AppApiKeysPlus>().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; } }
|
||||
}
|
||||
@@ -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", "<redacted>")
|
||||
.append("status", getStatus())
|
||||
.append("expiredAt", getExpiredAt())
|
||||
|
||||
@@ -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", "<redacted>")
|
||||
.append("status", getStatus())
|
||||
.append("expiredAt", getExpiredAt())
|
||||
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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<String, ?> 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<String, ?> 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);
|
||||
}
|
||||
}
|
||||
@@ -233,6 +233,10 @@ public class AppApiKeysServiceImpl extends ServiceImpl<AppApiKeysMapper, AppApiK
|
||||
byte[] secretBytes = new byte[32];
|
||||
new SecureRandom().nextBytes(secretBytes);
|
||||
String secret = Base64.getUrlEncoder().withoutPadding().encodeToString(secretBytes);
|
||||
byte[] keyBytes = new byte[24];
|
||||
new SecureRandom().nextBytes(keyBytes);
|
||||
String apiKey = "ak_" + Base64.getUrlEncoder().withoutPadding().encodeToString(keyBytes);
|
||||
appApiKeys.setApiKey(apiKey);
|
||||
appApiKeys.setApiSecret(secret);
|
||||
appApiKeys.setUserId(app.getUserId());
|
||||
if (appApiKeys.getStatus() == null) appApiKeys.setStatus(1);
|
||||
@@ -240,7 +244,7 @@ public class AppApiKeysServiceImpl extends ServiceImpl<AppApiKeysMapper, AppApiK
|
||||
appApiKeys.setUpdatedAt(DateUtils.getNowDate());
|
||||
appApiKeys.setDeletedAt(null);
|
||||
if (appApiKeysMapper.insertAppApiKeys(appApiKeys) != 1) throw new CustomException("API Key 创建失败");
|
||||
return new AppApiKeyCreateResult(appApiKeys.getId(), appApiKeys.getAppId(), secret);
|
||||
return new AppApiKeyCreateResult(appApiKeys.getId(), appApiKeys.getAppId(), apiKey, secret);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -26,9 +26,13 @@ public class PaymentCallbackWorker {
|
||||
if (order.getNotifyUrl() == null || order.getNotifyUrl().trim().isEmpty()) 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));
|
||||
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, 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 (response.getStatusCode().is2xxSuccessful() && "ok".equalsIgnoreCase(response.getBody() == null ? "" : response.getBody().trim())) order.setCallbackConfirm(1L);
|
||||
|
||||
@@ -8,6 +8,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<result property="id" column="id" />
|
||||
<result property="appId" column="app_id" />
|
||||
<result property="userId" column="user_id" />
|
||||
<result property="apiKey" column="api_key" />
|
||||
<result property="apiSecret" column="api_secret" />
|
||||
<result property="status" column="status" />
|
||||
<result property="expiredAt" column="expired_at" />
|
||||
@@ -17,7 +18,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
</resultMap>
|
||||
|
||||
<sql id="selectAppApiKeysVo">
|
||||
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
|
||||
</sql>
|
||||
|
||||
<select id="selectAppApiKeysList" parameterType="AppApiKeys" resultMap="AppApiKeysResult">
|
||||
@@ -27,6 +28,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<if test="appId != null "> and app_id = #{appId}</if>
|
||||
<if test="userId != null "> and user_id = #{userId}</if>
|
||||
<if test="apiSecret != null and apiSecret != ''"> and api_secret = #{apiSecret}</if>
|
||||
<if test="apiKey != null and apiKey != ''"> and api_key = #{apiKey}</if>
|
||||
<if test="status != null "> and status = #{status}</if>
|
||||
<if test="expiredAt != null "> and expired_at = #{expiredAt}</if>
|
||||
</where>
|
||||
@@ -42,6 +44,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<trim prefix="(" suffix=")" suffixOverrides=",">
|
||||
<if test="appId != null">app_id,</if>
|
||||
<if test="userId != null">user_id,</if>
|
||||
<if test="apiKey != null and apiKey != ''">api_key,</if>
|
||||
<if test="apiSecret != null and apiSecret != ''">api_secret,</if>
|
||||
<if test="status != null">status,</if>
|
||||
<if test="expiredAt != null">expired_at,</if>
|
||||
@@ -52,6 +55,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<trim prefix="values (" suffix=")" suffixOverrides=",">
|
||||
<if test="appId != null">#{appId},</if>
|
||||
<if test="userId != null">#{userId},</if>
|
||||
<if test="apiKey != null and apiKey != ''">#{apiKey},</if>
|
||||
<if test="apiSecret != null and apiSecret != ''">#{apiSecret},</if>
|
||||
<if test="status != null">#{status},</if>
|
||||
<if test="expiredAt != null">#{expiredAt},</if>
|
||||
@@ -66,6 +70,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<trim prefix="SET" suffixOverrides=",">
|
||||
<if test="appId != null">app_id = #{appId},</if>
|
||||
<if test="userId != null">user_id = #{userId},</if>
|
||||
<if test="apiKey != null and apiKey != ''">api_key = #{apiKey},</if>
|
||||
<if test="apiSecret != null and apiSecret != ''">api_secret = #{apiSecret},</if>
|
||||
<if test="status != null">status = #{status},</if>
|
||||
<if test="expiredAt != null">expired_at = #{expiredAt},</if>
|
||||
|
||||
Reference in new issue
Block a user