商户应用管理

This commit is contained in:
lu7213 committed 2026-10-08 09:45:11 -04:00
1 parent 71035c7fa0
commit 02664623f7
8 files changed
+300 -28

No files matched your search

@@ -11,6 +11,7 @@ import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.Apps;
import com.ruoyi.system.domain.AppsPlus;
import com.ruoyi.system.service.IAppsService;
import com.ruoyi.system.domain.dto.AppPublicKeyRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
@@ -29,6 +30,46 @@ public class AppsController extends BaseController {
@Autowired
private IAppsService appsService;
/**
* 生成 RSA 密钥对。私钥只在本次响应中返回,因此禁止操作日志保存响应体。
*/
@PreAuthorize("@ss.hasPermi('system:apps:add')")
@Log(title = "生成商户 RSA 密钥对", businessType = BusinessType.OTHER,
isSaveRequestData = false, isSaveResponseData = false)
@PostMapping("/generate-key-pair")
public AjaxResult generateKeyPair() {
return AjaxResult.success(appsService.generateKeyPair());
}
/** 商户端生成 RSA 密钥对,私钥同样不保存。 */
@PreAuthorize("@ss.hasPermi('system:apps:user-add')")
@Log(title = "商户生成 RSA 密钥对", businessType = BusinessType.OTHER,
isSaveRequestData = false, isSaveResponseData = false)
@PostMapping("/user/generate-key-pair")
public AjaxResult userGenerateKeyPair() {
return AjaxResult.success(appsService.generateKeyPair());
}
/** 单独设置商户公钥。 */
@PreAuthorize("@ss.hasPermi('system:apps:edit')")
@Log(title = "设置商户公钥", businessType = BusinessType.UPDATE)
@PutMapping("/{id}/public-key")
public AjaxResult updatePublicKey(@PathVariable("id") Long id,
@RequestBody AppPublicKeyRequest request) {
return toAjax(appsService.updatePublicKey(id,
request == null ? null : request.getPublicKey(), false));
}
/** 商户端单独设置自己的公钥。 */
@PreAuthorize("@ss.hasPermi('system:apps:user-edit')")
@Log(title = "商户设置公钥", businessType = BusinessType.UPDATE)
@PutMapping("/user/{id}/public-key")
public AjaxResult userUpdatePublicKey(@PathVariable("id") Long id,
@RequestBody AppPublicKeyRequest request) {
return toAjax(appsService.updatePublicKey(id,
request == null ? null : request.getPublicKey(), true));
}
@PreAuthorize("@ss.hasPermi('system:apps:getByIds')")
@PostMapping("/getByIds")
public AjaxResult getByIds(@RequestBody Ids ids) {
@@ -0,0 +1,9 @@
package com.ruoyi.system.domain.dto;
/** 商户 RSA 公钥设置请求。 */
public class AppPublicKeyRequest {
private String publicKey;
public String getPublicKey() { return publicKey; }
public void setPublicKey(String publicKey) { this.publicKey = publicKey; }
}
@@ -0,0 +1,24 @@
package com.ruoyi.system.domain.vo;
/**
* RSA 密钥对生成结果。
* privateKey 只在生成接口本次响应中出现,服务端绝不持久化。
*/
public class AppKeyPairResult {
private final String algorithm;
private final Integer keySize;
private final String publicKey;
private final String privateKey;
public AppKeyPairResult(String algorithm, Integer keySize, String publicKey, String privateKey) {
this.algorithm = algorithm;
this.keySize = keySize;
this.publicKey = publicKey;
this.privateKey = privateKey;
}
public String getAlgorithm() { return algorithm; }
public Integer getKeySize() { return keySize; }
public String getPublicKey() { return publicKey; }
public String getPrivateKey() { return privateKey; }
}
@@ -15,6 +15,10 @@ import com.ruoyi.system.domain.AppsPlus;
*/
public interface AppsMapper extends BaseMapper<AppsPlus>
{
int updatePublicKey(@Param("id") Long id, @Param("publicKey") String publicKey,
@Param("updatedAt") java.util.Date updatedAt);
int softDeleteAppsByIds(@Param("ids") Long[] ids, @Param("deletedAt") java.util.Date deletedAt);
/**
* 查询【请填写功能名称】
*
@@ -6,6 +6,7 @@ import com.ruoyi.system.domain.AppsPlus;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.ruoyi.common.select.SelectItem;
import com.ruoyi.system.domain.vo.AppKeyPairResult;
/**
* 应用管理Service接口
*
@@ -15,6 +16,12 @@ import com.ruoyi.common.select.SelectItem;
public interface IAppsService extends IService<AppsPlus>
{
/** 生成 RSA 密钥对。私钥仅由返回值交付,不持久化。 */
AppKeyPairResult generateKeyPair();
/** 单独设置并规范化商户 RSA 公钥。 */
int updatePublicKey(Long id, String publicKey, boolean isUser);
List<SelectItem> select(String keyword,boolean isUser);
/**
* 查询应用管理
@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.select.SelectItem;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
@@ -12,11 +13,20 @@ import com.ruoyi.system.domain.Apps;
import com.ruoyi.system.domain.AppsPlus;
import com.ruoyi.system.mapper.AppsMapper;
import com.ruoyi.system.service.IAppsService;
import com.ruoyi.system.domain.vo.AppKeyPairResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.*;
import java.math.BigDecimal;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import org.springframework.transaction.annotation.Transactional;
/**
* 应用管理Service业务层处理
@@ -26,15 +36,44 @@ import java.util.*;
*/
@Service
public class AppsServiceImpl extends ServiceImpl<AppsMapper, AppsPlus> implements IAppsService {
private static final int RSA_KEY_SIZE = 2048;
private static final int MAX_NAME_LENGTH = 100;
private static final int MAX_DESCRIPTION_LENGTH = 255;
@Autowired
private AppsMapper appsMapper;
@Autowired
private JdbcTemplate jdbcTemplate;
/**
* 生成与平台加解密约定一致的 RSA 密钥对。
* 私钥不进入实体、数据库或日志,只随本次方法结果返回给调用方。
*/
@Override
public AppKeyPairResult generateKeyPair() {
try {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(RSA_KEY_SIZE);
KeyPair keyPair = generator.generateKeyPair();
return new AppKeyPairResult("RSA", RSA_KEY_SIZE,
Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded()),
Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()));
} catch (Exception e) {
throw new CustomException("RSA 密钥对生成失败", e);
}
}
@Override
public int updatePublicKey(Long id, String publicKey, boolean isUser) {
Apps current = requireExistingApp(id, isUser);
String normalizedPublicKey = normalizeAndValidatePublicKey(publicKey);
return appsMapper.updatePublicKey(current.getId(), normalizedPublicKey, DateUtils.getNowDate());
}
@Override
public List<AppsPlus> getByIds(List<Long> ids, boolean isUser, SFunction<AppsPlus, ?>... columns) {
LambdaQueryWrapper<AppsPlus> lambdaQueryWrapper = new LambdaQueryWrapper<AppsPlus>()
.select(columns).in(AppsPlus::getId, ids);
.select(columns).in(AppsPlus::getId, ids).isNull(AppsPlus::getDeletedAt);
if (isUser) {
lambdaQueryWrapper.eq(AppsPlus::getUserId, SecurityUtils.getUserId());
}
@@ -46,30 +85,42 @@ public class AppsServiceImpl extends ServiceImpl<AppsMapper, AppsPlus> implement
}
private void checkUserPlus(List<AppsPlus> list) {
Long currentUserId = SecurityUtils.getUserId();
if (currentUserId == null) throw new CustomException("无法获取当前用户");
for (AppsPlus item : list) {
if (null != SecurityUtils.getUserId() && item.getUserId().longValue() != SecurityUtils.getUserId()) {
throw new RuntimeException("无权限");
if (item == null || item.getUserId() == null || !item.getUserId().equals(currentUserId)) {
throw new CustomException("无权操作该商户");
}
}
}
private void checkUser(List<Apps> list) {
Long currentUserId = SecurityUtils.getUserId();
if (currentUserId == null) throw new CustomException("无法获取当前用户");
for (Apps item : list) {
if (null != SecurityUtils.getUserId() && item.getUserId().longValue() != SecurityUtils.getUserId()) {
throw new RuntimeException("无权限");
if (item == null || item.getUserId() == null || !item.getUserId().equals(currentUserId)) {
throw new CustomException("无权操作该商户");
}
}
}
private void checkUser(AppsPlus item) {
if (null != SecurityUtils.getUserId() && item.getUserId().longValue() != SecurityUtils.getUserId()) {
throw new RuntimeException("无权限");
if (item == null) {
throw new CustomException("商户不存在或已删除");
}
Long currentUserId = SecurityUtils.getUserId();
if (currentUserId == null || item.getUserId() == null || !item.getUserId().equals(currentUserId)) {
throw new CustomException("无权操作该商户");
}
}
private void checkUser(Apps item) {
if (null != SecurityUtils.getUserId() && item.getUserId().longValue() != SecurityUtils.getUserId()) {
throw new RuntimeException("无权限");
if (item == null) {
throw new CustomException("商户不存在或已删除");
}
Long currentUserId = SecurityUtils.getUserId();
if (currentUserId == null || item.getUserId() == null || !item.getUserId().equals(currentUserId)) {
throw new CustomException("无权操作该商户");
}
}
@@ -77,7 +128,10 @@ public class AppsServiceImpl extends ServiceImpl<AppsMapper, AppsPlus> implement
public List<SelectItem> select(String keyword, boolean isUser) {
LambdaQueryWrapper<AppsPlus> lambdaQueryWrapper = new LambdaQueryWrapper<AppsPlus>()
.select(AppsPlus::getId, AppsPlus::getUserId, AppsPlus::getName)
.like(AppsPlus::getName, keyword);
.isNull(AppsPlus::getDeletedAt);
if (StringUtils.isNotBlank(keyword)) {
lambdaQueryWrapper.like(AppsPlus::getName, keyword);
}
if (isUser) {
lambdaQueryWrapper.eq(AppsPlus::getUserId, SecurityUtils.getUserId());
}
@@ -98,7 +152,7 @@ public class AppsServiceImpl extends ServiceImpl<AppsMapper, AppsPlus> implement
@Override
public AppsPlus getById(Long id, SFunction<AppsPlus, ?>... columns) {
LambdaQueryWrapper<AppsPlus> lambdaQueryWrapper = new LambdaQueryWrapper<AppsPlus>()
.select(columns).eq(AppsPlus::getId, id);
.select(columns).eq(AppsPlus::getId, id).isNull(AppsPlus::getDeletedAt);
return baseMapper.selectOne(lambdaQueryWrapper);
}
@@ -124,7 +178,8 @@ public class AppsServiceImpl extends ServiceImpl<AppsMapper, AppsPlus> implement
@Override
public List<AppsPlus> getByIds(List<Long> ids) {
LambdaQueryWrapper<AppsPlus> lambdaQueryWrapper = new LambdaQueryWrapper<AppsPlus>().in(AppsPlus::getId, ids);
LambdaQueryWrapper<AppsPlus> lambdaQueryWrapper = new LambdaQueryWrapper<AppsPlus>()
.in(AppsPlus::getId, ids).isNull(AppsPlus::getDeletedAt);
return this.list(lambdaQueryWrapper);
}
@@ -181,6 +236,9 @@ public class AppsServiceImpl extends ServiceImpl<AppsMapper, AppsPlus> implement
@Override
public Apps selectAppsById(Long id, boolean isUser) {
Apps vo = appsMapper.selectAppsById(id);
if (vo == null) {
throw new CustomException("商户不存在或已删除");
}
if (isUser) {
checkUser(vo);
}
@@ -216,10 +274,27 @@ public class AppsServiceImpl extends ServiceImpl<AppsMapper, AppsPlus> implement
*/
@Override
public int insertApps(Apps apps, boolean isUser) {
validateAppForCreate(apps, isUser);
apps.setCreatedAt(DateUtils.getNowDate());
apps.setUpdatedAt(DateUtils.getNowDate());
apps.setDeletedAt(null);
if (isUser) {
apps.setUserId(SecurityUtils.getUserId());
apps.setTrxBalance(BigDecimal.ZERO);
apps.setUsdtBalance(BigDecimal.ZERO);
apps.setCreditLimit(BigDecimal.ZERO);
apps.setGoogleSub(null);
apps.setGoogleEmail(null);
apps.setGoogleName(null);
apps.setGooglePicture(null);
apps.setDistTokenAddress(null);
}
if (apps.getStatus() == null) apps.setStatus(1);
if (apps.getTrxBalance() == null) apps.setTrxBalance(BigDecimal.ZERO);
if (apps.getUsdtBalance() == null) apps.setUsdtBalance(BigDecimal.ZERO);
if (apps.getCreditLimit() == null) apps.setCreditLimit(BigDecimal.ZERO);
if (StringUtils.isNotBlank(apps.getPublicKey())) {
apps.setPublicKey(normalizeAndValidatePublicKey(apps.getPublicKey()));
}
return appsMapper.insertApps(apps);
}
@@ -232,11 +307,21 @@ public class AppsServiceImpl extends ServiceImpl<AppsMapper, AppsPlus> implement
*/
@Override
public int updateApps(Apps apps, boolean isUser) {
apps.setUpdatedAt(DateUtils.getNowDate());
if (isUser) {
checkUser(apps);
validateAppForUpdate(apps);
Apps current = requireExistingApp(apps.getId(), isUser);
// 通用修改仅允许维护商户基本资料;余额、身份绑定、公钥和归集地址走各自专用流程。
Apps update = new Apps();
update.setId(current.getId());
update.setName(apps.getName().trim());
update.setDescription(apps.getDescription());
update.setStatus(apps.getStatus());
update.setUpdatedAt(DateUtils.getNowDate());
if (!isUser) {
update.setUserId(apps.getUserId());
update.setCreditLimit(apps.getCreditLimit());
}
return appsMapper.updateApps(apps);
return appsMapper.updateApps(update);
}
/**
@@ -246,12 +331,14 @@ public class AppsServiceImpl extends ServiceImpl<AppsMapper, AppsPlus> implement
* @return 结果
*/
@Override
@Transactional(rollbackFor = Exception.class)
public int deleteAppsByIds(Long[] ids, boolean isUser) {
if (isUser) {
List<AppsPlus> list = getByIds(Arrays.asList(ids), false, AppsPlus::getUserId, AppsPlus::getId);
checkUserPlus(list);
validateIds(ids);
for (Long id : ids) {
requireExistingApp(id, isUser);
ensureNoBusinessReferences(id);
}
return appsMapper.deleteAppsByIds(ids);
return appsMapper.softDeleteAppsByIds(ids, DateUtils.getNowDate());
}
/**
@@ -262,10 +349,88 @@ public class AppsServiceImpl extends ServiceImpl<AppsMapper, AppsPlus> implement
*/
@Override
public int deleteAppsById(Long id, boolean isUser) {
if (isUser) {
AppsPlus vo = getById(id, AppsPlus::getUserId, AppsPlus::getId);
checkUser(vo);
return deleteAppsByIds(new Long[] { id }, isUser);
}
private Apps requireExistingApp(Long id, boolean isUser) {
if (id == null) throw new CustomException("商户 ID 不能为空");
Apps current = appsMapper.selectAppsById(id);
if (current == null) throw new CustomException("商户不存在或已删除");
if (isUser) checkUser(current);
return current;
}
private void validateAppForCreate(Apps apps, boolean isUser) {
if (apps == null) throw new CustomException("商户参数不能为空");
validateNameAndDescription(apps);
validateStatus(apps.getStatus());
if (!isUser && apps.getUserId() == null) throw new CustomException("用户 ID 不能为空");
if (isUser && SecurityUtils.getUserId() == null) throw new CustomException("无法获取当前用户");
validateNonNegative(apps.getCreditLimit(), "信用额度");
validateNonNegative(apps.getTrxBalance(), "TRX 余额");
validateNonNegative(apps.getUsdtBalance(), "USDT 余额");
}
private void validateAppForUpdate(Apps apps) {
if (apps == null || apps.getId() == null) throw new CustomException("商户 ID 不能为空");
validateNameAndDescription(apps);
validateStatus(apps.getStatus());
validateNonNegative(apps.getCreditLimit(), "信用额度");
}
private void validateNameAndDescription(Apps apps) {
if (StringUtils.isBlank(apps.getName())) throw new CustomException("商户名称不能为空");
if (apps.getName().trim().length() > MAX_NAME_LENGTH) throw new CustomException("商户名称不能超过 100 个字符");
if (apps.getDescription() != null && apps.getDescription().length() > MAX_DESCRIPTION_LENGTH) {
throw new CustomException("商户描述不能超过 255 个字符");
}
}
private void validateStatus(Integer status) {
if (status != null && status.intValue() != 0 && status.intValue() != 1) {
throw new CustomException("商户状态只能为 0(停用)或 1(启用)");
}
}
private void validateNonNegative(BigDecimal value, String fieldName) {
if (value != null && value.signum() < 0) throw new CustomException(fieldName + "不能小于 0");
}
private String normalizeAndValidatePublicKey(String publicKey) {
if (StringUtils.isBlank(publicKey)) throw new CustomException("公钥不能为空");
String normalized = publicKey.trim()
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replaceAll("\\s", "");
try {
byte[] encoded = Base64.getDecoder().decode(normalized);
RSAPublicKey key = (RSAPublicKey) KeyFactory.getInstance("RSA")
.generatePublic(new X509EncodedKeySpec(encoded));
if (key.getModulus().bitLength() < RSA_KEY_SIZE) {
throw new CustomException("RSA 公钥长度不能小于 2048 位");
}
return Base64.getEncoder().encodeToString(key.getEncoded());
} catch (CustomException e) {
throw e;
} catch (Exception e) {
throw new CustomException("公钥格式错误,请使用 X.509 Base64 或 PUBLIC KEY PEM 格式");
}
}
private void validateIds(Long[] ids) {
if (ids == null || ids.length == 0) throw new CustomException("请选择要删除的商户");
for (Long id : ids) if (id == null) throw new CustomException("商户 ID 不能为空");
}
private void ensureNoBusinessReferences(Long appId) {
String[] tables = { "app_api_keys", "wallet_address", "orders", "usdt_aggregation_task" };
String[] labels = { "API 密钥", "支付钱包", "支付订单", "归集任务" };
for (int i = 0; i < tables.length; i++) {
Long count = jdbcTemplate.queryForObject(
"select count(1) from " + tables[i] + " where app_id = ?", Long.class, appId);
if (count != null && count.longValue() > 0) {
throw new CustomException("商户存在关联的" + labels[i] + ",不能删除;如需停止使用请将状态改为停用");
}
}
return appsMapper.deleteAppsById(id);
}
}
@@ -30,7 +30,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<select id="selectAppsList" parameterType="Apps" resultMap="AppsResult">
<include refid="selectAppsVo"/>
<where>
<where>
and deleted_at is null
<if test="userId != null "> and user_id = #{userId}</if>
<if test="name != null and name != ''"> and name like concat('%', #{name}, '%')</if>
<if test="description != null and description != ''"> and description = #{description}</if>
@@ -52,8 +53,24 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<select id="selectAppsById" parameterType="Long" resultMap="AppsResult">
<include refid="selectAppsVo"/>
where id = #{id}
where id = #{id} and deleted_at is null
</select>
<update id="updatePublicKey">
update apps
set public_key = #{publicKey}, updated_at = #{updatedAt}
where id = #{id} and deleted_at is null
</update>
<update id="softDeleteAppsByIds">
update apps
set status = 0, deleted_at = #{deletedAt}, updated_at = #{deletedAt}
where deleted_at is null
and id in
<foreach item="id" collection="ids" open="(" separator="," close=")">
#{id}
</foreach>
</update>
<insert id="insertApps" parameterType="Apps" useGeneratedKeys="true" keyProperty="id">
insert into apps
@@ -115,7 +132,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="googlePicture != null">google_picture = #{googlePicture},</if>
<if test="distTokenAddress != null">dist_token_address = #{distTokenAddress},</if>
</trim>
where id = #{id}
where id = #{id} and deleted_at is null
</update>
<delete id="deleteAppsById" parameterType="Long">
@@ -128,4 +145,4 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
#{id}
</foreach>
</delete>
</mapper>
</mapper>