feat:微信相关功能模块抽离重构,动态获取相关配置已经登录逻辑等的完善

This commit is contained in:
2025-05-28 15:45:10 +08:00
parent 2ad8499e47
commit 28398be217
24 changed files with 1443 additions and 9 deletions
BIN
View File
Binary file not shown.
+7
View File
@@ -80,6 +80,13 @@
<artifactId>hibernate-validator</artifactId>
</dependency>
<!-- 添加微信模块依赖 -->
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-wechat-common-core</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<build>
@@ -0,0 +1,112 @@
package com.central.user.controller;
import com.central.common.context.TenantContextHolder;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.zlt.wechat.entity.WechatConfig;
import com.zlt.wechat.service.PrivateKeyService;
import com.zlt.wechat.service.WechatConfigService;
import com.zlt.wechat.service.WechatPayService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.Map;
@Slf4j
@RestController
@RequiredArgsConstructor
@Tag(name = "微信配置管理")
@RequestMapping("/wechat/config")
public class SysWechatConfigController {
@Autowired
private WechatConfigService wechatConfigService;
@Autowired
private WechatPayService wechatPayService;
@Autowired
private PrivateKeyService privateKeyService;
@Operation(summary = "查询列表")
@Parameters({
@Parameter(name = "page",description = "分页起始位置",required = true,in= ParameterIn.QUERY),
@Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY)
})
@GetMapping
public PageResult list(@RequestParam Map<String, Object> params) {
return wechatConfigService.findList(params);
}
@Operation(summary = "获取微信配置")
@GetMapping("/{type}")
public Result<WechatConfig> getConfig(@PathVariable String type) {
return Result.succeed(wechatConfigService.getConfig(type, TenantContextHolder.getTenant()));
}
@Operation(summary = "获取微信配置")
@GetMapping("/app/{id}")
public Result<WechatConfig> getConfigByAppId(@PathVariable String appId) {
return Result.succeed(wechatConfigService.getConfig(appId));
}
@Operation(summary = "保存微信配置")
@PostMapping
public Result<Boolean> saveConfig(@RequestBody WechatConfig config) {
config.setTenantId(TenantContextHolder.getTenant());
return Result.succeed(wechatConfigService.saveConfig(config));
}
@Operation(summary = "更新微信配置")
@PutMapping
public Result<Boolean> updateConfig(@RequestBody WechatConfig config) {
config.setTenantId(TenantContextHolder.getTenant());
return Result.succeed(wechatConfigService.updateConfig(config));
}
@Operation(summary = "删除微信配置")
@DeleteMapping("/{id}")
public Result<Boolean> deleteConfig(@PathVariable Long id) {
return Result.succeed(wechatConfigService.deleteConfig(id));
}
@Operation(summary = "上传支付私钥")
@PostMapping("/private-key")
public Result<Boolean> uploadPrivateKey(@RequestParam("file") MultipartFile file) {
try {
String privateKey = new String(file.getBytes());
return Result.succeed(wechatPayService.uploadPrivateKey(
TenantContextHolder.getTenant(), privateKey));
} catch (Exception e) {
log.error("上传私钥文件失败", e);
return Result.failed("上传私钥文件失败");
}
}
@Operation(summary = "更新支付配置")
@PostMapping("/pay-config")
public Result<Boolean> updatePayConfig(@RequestBody Map<String, String> config) {
return Result.succeed(wechatPayService.updatePayConfig(
TenantContextHolder.getTenant(), config));
}
@Operation(summary = "切换微信配置")
@PostMapping("/switch/{type}")
public Result<Boolean> switchConfig(@PathVariable String type) {
return Result.succeed(wechatConfigService.switchConfig(type, TenantContextHolder.getTenant()));
}
@Operation(summary = "获取当前配置")
@GetMapping("/current/{type}")
public Result<WechatConfig> getCurrentConfig(@PathVariable String type) {
return Result.succeed(wechatConfigService.getConfig(type, TenantContextHolder.getTenant()));
}
}
@@ -0,0 +1,114 @@
package com.central.user.model;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("sys_wechat_config")
public class SysWechatConfig {
@TableId(type = IdType.AUTO)
private Long id;
/**
* 租户ID
*/
private String tenantId;
/**
* 配置类型:MP-公众号,MINI-小程序,PAY-支付
*/
private String type;
/**
* 商户ID
*/
private String merchantId;
/**
* 应用ID
*/
private String appId;
/**
* 应用密钥
*/
private String appSecret;
/**
* 商户API密钥
*/
private String mchKey;
/**
* 商户证书序列号
*/
private String mchSerialNo;
/**
* 商户私钥文件路径
*/
private String privateKeyPath;
/**
* APIv3密钥
*/
private String apiV3Key;
/**
* 支付回调地址
*/
private String notifyUrl;
/**
* 微信公众号token
*/
private String token;
/**
* 微信公众号aesKey
*/
private String aesKey;
/**
* 支付成功通知模板ID
*/
private String paymentSuccessTemplateId;
/**
* 视频处理完成通知模板ID
*/
private String videoCompleteTemplateId;
/**
* 视频处理失败通知模板ID
*/
private String videoFailTemplateId;
/**
* 是否启用分账
*/
private Boolean profitSharingEnabled;
/**
* 是否启用异步处理
*/
private Boolean asyncEnabled;
/**
* 异步处理线程池大小
*/
private Integer asyncPoolSize;
/**
* 状态:0-禁用,1-启用
*/
private Integer status;
/**
* 备注
*/
private String remark;
}
@@ -0,0 +1,55 @@
package com.central.user.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.central.user.model.SysWechatConfig;
public interface SysWechatConfigService extends IService<SysWechatConfig> {
/**
* 获取微信配置
*
* @param type 配置类型
* @return 微信配置
*/
SysWechatConfig getConfig(String type);
/**
* 保存微信配置
*
* @param config 微信配置
* @return 是否成功
*/
boolean saveConfig(SysWechatConfig config);
/**
* 更新微信配置
*
* @param config 微信配置
* @return 是否成功
*/
boolean updateConfig(SysWechatConfig config);
/**
* 删除微信配置
*
* @param id 配置ID
* @return 是否成功
*/
boolean deleteConfig(Long id);
/**
* 切换当前使用的微信配置
*
* @param type 配置类型
* @return 是否成功
*/
boolean switchConfig(String type);
/**
* 获取当前使用的微信配置
*
* @param type 配置类型
* @return 微信配置
*/
SysWechatConfig getCurrentConfig(String type);
}
@@ -0,0 +1,61 @@
package com.central.user.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.common.context.TenantContextHolder;
import com.central.user.mapper.SysWechatConfigMapper;
import com.central.user.model.SysWechatConfig;
import com.central.user.service.SysWechatConfigService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class SysWechatConfigServiceImpl extends ServiceImpl<SysWechatConfigMapper, SysWechatConfig>
implements SysWechatConfigService {
private static final String CACHE_NAME = "wechat:config";
private static final String CACHE_KEY_PATTERN = "#type";
@Override
@Cacheable(value = CACHE_NAME, key = CACHE_KEY_PATTERN, unless = "#result == null")
public SysWechatConfig getConfig(String type) {
return getOne(new LambdaQueryWrapper<SysWechatConfig>()
.eq(SysWechatConfig::getType, type)
.eq(SysWechatConfig::getTenantId, TenantContextHolder.getTenant())
.eq(SysWechatConfig::getStatus, 1));
}
@Override
@CacheEvict(value = CACHE_NAME, key = CACHE_KEY_PATTERN)
public boolean saveConfig(SysWechatConfig config) {
config.setTenantId(TenantContextHolder.getTenant());
return save(config);
}
@Override
@CacheEvict(value = CACHE_NAME, key = CACHE_KEY_PATTERN)
public boolean updateConfig(SysWechatConfig config) {
config.setTenantId(TenantContextHolder.getTenant());
return updateById(config);
}
@Override
@CacheEvict(value = CACHE_NAME, allEntries = true)
public boolean deleteConfig(Long id) {
return removeById(id);
}
@Override
@CacheEvict(value = CACHE_NAME, key = CACHE_KEY_PATTERN)
public boolean switchConfig(String type) {
// 这里可以添加切换配置的具体逻辑
return true;
}
@Override
@Cacheable(value = CACHE_NAME, key = "'current:' + #type", unless = "#result == null")
public SysWechatConfig getCurrentConfig(String type) {
return getConfig(type);
}
}
@@ -0,0 +1,88 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.zlt</groupId>
<artifactId>zlt-commons</artifactId>
<version>6.0.0</version>
</parent>
<artifactId>zlt-wechat-common-core</artifactId>
<description>微信核心功能模块</description>
<dependencies>
<!-- 微信相关依赖 -->
<!--<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>4.5.0</version>
</dependency>
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>4.6.0</version>
</dependency>
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-common</artifactId>
<version>4.6.0</version>
</dependency>
<dependency>
<groupId>com.github.wechatpay-apiv3</groupId>
<artifactId>wechatpay-java</artifactId>
<version>0.2.15</version>
</dependency>-->
<!-- 微信公众号 SDK -->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>4.5.0</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>4.6.0</version>
</dependency>
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-common</artifactId>
<version>4.6.0</version>
</dependency>
<dependency>
<groupId>com.github.wechatpay-apiv3</groupId>
<artifactId>wechatpay-java</artifactId>
<version>0.2.15</version>
</dependency>
<!-- 基础依赖 -->
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-common-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-db-spring-boot-starter</artifactId>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,138 @@
package com.zlt.wechat.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Data
@ConfigurationProperties(prefix = "zlt.wechat")
public class WechatProperties {
/**
* 微信公众号配置
*/
private Mp mp = new Mp();
/**
* 微信小程序配置
*/
private MiniApp miniApp = new MiniApp();
/**
* 微信支付配置
*/
private Pay pay = new Pay();
/**
* 分账配置
*/
private ProfitSharing profitSharing = new ProfitSharing();
@Data
public static class Mp {
/**
* 微信公众号appId
*/
private String appId;
/**
* 微信公众号appSecret
*/
private String appSecret;
/**
* 微信公众号token
*/
private String token;
/**
* 微信公众号aesKey
*/
private String aesKey;
/**
* 微信公众号消息模板ID
*/
private TemplateConfig templateId = new TemplateConfig();
}
@Data
public static class TemplateConfig {
/**
* 支付成功通知模板ID
*/
private String paymentSuccess;
/**
* 视频处理完成通知模板ID
*/
private String videoComplete;
/**
* 视频处理失败通知模板ID
*/
private String videoFail;
}
@Data
public static class MiniApp {
/**
* 小程序appId
*/
private String appId;
/**
* 小程序appSecret
*/
private String appSecret;
}
@Data
public static class Pay {
/**
* 商户号
*/
private String mchId;
/**
* 商户API密钥
*/
private String mchKey;
/**
* 商户证书序列号
*/
private String mchSerialNo;
/**
* 商户私钥文件路径
*/
private String privateKeyPath;
/**
* APIv3密钥
*/
private String apiV3Key;
/**
* 支付回调地址
*/
private String notifyUrl;
}
@Data
public static class ProfitSharing {
/**
* 是否启用分账
*/
private boolean enabled = true;
/**
* 是否启用异步处理
*/
private boolean asyncEnabled = true;
/**
* 异步处理线程池大小
*/
private int asyncPoolSize = 5;
}
}
@@ -0,0 +1,116 @@
package com.zlt.wechat.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("wechat_config")
public class WechatConfig {
/**
* 主键ID
*/
@TableId(type = IdType.AUTO)
private Long id;
/**
* 租户ID
*/
private String tenantId;
/**
* 配置类型:MP-公众号,MINI-小程序,PAY-支付
*/
private String type;
/**
* 商户ID
*/
private String merchantId;
/**
* 应用ID
*/
private String appId;
/**
* 应用密钥
*/
private String appSecret;
/**
* 商户API密钥
*/
private String mchKey;
/**
* 商户证书序列号
*/
private String mchSerialNo;
/**
* 商户私钥文件路径
*/
private String privateKeyPath;
/**
* APIv3密钥
*/
private String apiV3Key;
/**
* 支付回调地址
*/
private String notifyUrl;
/**
* 微信公众号token
*/
private String token;
/**
* 微信公众号aesKey
*/
private String aesKey;
/**
* 支付成功通知模板ID
*/
private String paymentSuccessTemplateId;
/**
* 视频处理完成通知模板ID
*/
private String videoCompleteTemplateId;
/**
* 视频处理失败通知模板ID
*/
private String videoFailTemplateId;
/**
* 是否启用分账
*/
private Boolean profitSharingEnabled;
/**
* 是否启用异步处理
*/
private Boolean asyncEnabled;
/**
* 异步处理线程池大小
*/
private Integer asyncPoolSize;
/**
* 状态:0-禁用,1-启用
*/
private Integer status;
/**
* 备注
*/
private String remark;
}
@@ -0,0 +1,35 @@
package com.zlt.wechat.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zlt.wechat.entity.WechatConfig;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
@Mapper
public interface WechatConfigMapper extends BaseMapper<WechatConfig> {
@Select("<script>" +
"SELECT * FROM wechat_config " +
"<where>" +
" <if test='p.type != null and p.type != \"\"'>" +
" AND type = #{p.type}" +
" </if>" +
" <if test='p.merchantId != null and p.merchantId != \"\"'>" +
" AND merchant_id = #{p.merchantId}" +
" </if>" +
" <if test='p.status != null'>" +
" AND status = #{p.status}" +
" </if>" +
" <if test='p.tenantId != null and p.tenantId != \"\"'>" +
" AND tenant_id = #{p.tenantId}" +
" </if>" +
"</where>" +
"ORDER BY create_time DESC" +
"</script>")
List<WechatConfig> findList(Page<WechatConfig> page, @Param("p") Map<String, Object> params);
}
@@ -0,0 +1,37 @@
package com.zlt.wechat.service;
import java.io.InputStream;
/**
* 私钥文件管理服务
*/
public interface PrivateKeyService {
/**
* 上传私钥文件
*
* @param tenantId 租户ID
* @param type 配置类型
* @param inputStream 文件输入流
* @return 文件访问路径
*/
String uploadPrivateKey(String tenantId, String type, InputStream inputStream);
/**
* 获取私钥文件
*
* @param tenantId 租户ID
* @param type 配置类型
* @return 私钥文件内容
*/
String getPrivateKey(String tenantId, String type);
/**
* 删除私钥文件
*
* @param tenantId 租户ID
* @param type 配置类型
* @return 是否成功
*/
boolean deletePrivateKey(String tenantId, String type);
}
@@ -0,0 +1,67 @@
package com.zlt.wechat.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.central.common.model.PageResult;
import com.zlt.wechat.entity.WechatConfig;
import java.util.Map;
public interface WechatConfigService extends IService<WechatConfig> {
/**
* 列表
* @param params
* @return
*/
PageResult<WechatConfig> findList(Map<String, Object> params);
/**
* 获取微信配置
*
* @param type 配置类型
* @param tenantId 商户ID
* @return 微信配置
*/
WechatConfig getConfig(String type, String tenantId);
/**
* 获取微信配置
*
* @param appId 商户ID
* @return 微信配置
*/
WechatConfig getConfig(String appId);
/**
* 保存微信配置
*
* @param config 微信配置
* @return 是否成功
*/
boolean saveConfig(WechatConfig config);
/**
* 更新微信配置
*
* @param config 微信配置
* @return 是否成功
*/
boolean updateConfig(WechatConfig config);
/**
* 删除微信配置
*
* @param id 配置ID
* @return 是否成功
*/
boolean deleteConfig(Long id);
/**
* 切换当前使用的微信配置
*
* @param type 配置类型
* @param merchantId 商户ID
* @return 是否成功
*/
boolean switchConfig(String type, String merchantId);
}
@@ -0,0 +1,93 @@
package com.zlt.wechat.service;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.refund.model.Refund;
import com.wechat.pay.java.service.refund.model.RefundNotification;
import java.util.Map;
/**
* 微信支付服务
*/
public interface WechatPayService {
/**
* 创建JSAPI支付订单
*
* @param tenantId 租户ID
* @param openId 用户openId
* @param amount 支付金额(分)
* @param description 商品描述
* @param outTradeNo 商户订单号
* @return 支付参数
*/
PrepayWithRequestPaymentResponse createJsapiOrder(String tenantId, String openId, int amount,
String description, String outTradeNo);
/**
* 查询订单
*
* @param tenantId 租户ID
* @param outTradeNo 商户订单号
* @return 订单信息
*/
Transaction queryOrder(String tenantId, String outTradeNo);
/**
* 关闭订单
*
* @param tenantId 租户ID
* @param outTradeNo 商户订单号
*/
void closeOrder(String tenantId, String outTradeNo);
/**
* 申请退款
*
* @param tenantId 租户ID
* @param outTradeNo 商户订单号
* @param outRefundNo 商户退款单号
* @param amount 退款金额(分)
* @param reason 退款原因
* @return 退款结果
*/
// RefundResponse refund(String tenantId, String outTradeNo, String outRefundNo,
// int amount, String reason);
/**
* 查询退款
*
* @param tenantId 租户ID
* @param outRefundNo 商户退款单号
* @return 退款信息
*/
Refund queryRefund(String tenantId, String outRefundNo);
/**
* 解析退款通知
*
* @param tenantId 租户ID
* @param notifyData 通知数据
* @return 退款通知信息
*/
RefundNotification parseRefundNotify(String tenantId, String notifyData);
/**
* 上传私钥文件
*
* @param tenantId 租户ID
* @param privateKey 私钥内容
* @return 是否成功
*/
boolean uploadPrivateKey(String tenantId, String privateKey);
/**
* 更新支付配置
*
* @param tenantId 租户ID
* @param config 配置信息
* @return 是否成功
*/
boolean updatePayConfig(String tenantId, Map<String, String> config);
}
@@ -0,0 +1,61 @@
package com.zlt.wechat.service.impl;
import com.zlt.wechat.service.PrivateKeyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;
@Service
public class PrivateKeyServiceImpl implements PrivateKeyService {
private static final String CACHE_KEY_PATTERN = "wechat:private_key:%s:%s";
private static final long CACHE_EXPIRE_DAYS = 30;
@Autowired
private StringRedisTemplate redisTemplate;
@Override
public String uploadPrivateKey(String tenantId, String type, InputStream inputStream) {
try {
// 读取私钥内容
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
// 缓存私钥内容
String cacheKey = String.format(CACHE_KEY_PATTERN, tenantId, type);
redisTemplate.opsForValue().set(cacheKey, content.toString(), CACHE_EXPIRE_DAYS, TimeUnit.DAYS);
return cacheKey;
} catch (Exception e) {
throw new RuntimeException("上传私钥文件失败", e);
}
}
@Override
public String getPrivateKey(String tenantId, String type) {
String cacheKey = String.format(CACHE_KEY_PATTERN, tenantId, type);
String privateKey = redisTemplate.opsForValue().get(cacheKey);
if (!StringUtils.hasText(privateKey)) {
throw new RuntimeException("私钥文件不存在");
}
return privateKey;
}
@Override
public boolean deletePrivateKey(String tenantId, String type) {
String cacheKey = String.format(CACHE_KEY_PATTERN, tenantId, type);
return redisTemplate.delete(cacheKey);
}
}
@@ -0,0 +1,71 @@
package com.zlt.wechat.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.common.model.PageResult;
import com.zlt.wechat.entity.WechatConfig;
import com.zlt.wechat.mapper.WechatConfigMapper;
import com.zlt.wechat.service.WechatConfigService;
import org.apache.commons.collections4.MapUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class WechatConfigServiceImpl extends ServiceImpl<WechatConfigMapper, WechatConfig> implements WechatConfigService {
private static final String CACHE_NAME = "wechat:config";
private static final String CACHE_KEY_PATTERN = "#type + ':' + #tenantId";
@Override
public PageResult<WechatConfig> findList(Map<String, Object> params) {
Page<WechatConfig> page = new Page<>(MapUtils.getInteger(params, "page", 1), MapUtils.getInteger(params, "limit", 10));
List<WechatConfig> list = baseMapper.findList(page, params);
return PageResult.<WechatConfig>builder().data(list).resp_code(0).count(page.getTotal()).build();
}
@Override
@Cacheable(value = CACHE_NAME, key = CACHE_KEY_PATTERN, unless = "#result == null")
public WechatConfig getConfig(String type, String tenantId) {
return getOne(new LambdaQueryWrapper<WechatConfig>()
.eq(WechatConfig::getType, type)
.eq(WechatConfig::getTenantId, tenantId)
.eq(WechatConfig::getStatus, 1));
}
@Override
public WechatConfig getConfig(String appId) {
return getOne(new LambdaQueryWrapper<WechatConfig>()
.eq(WechatConfig::getAppId, appId)
.eq(WechatConfig::getStatus, 1));
}
@Override
@CacheEvict(value = CACHE_NAME, key = CACHE_KEY_PATTERN)
public boolean saveConfig(WechatConfig config) {
return save(config);
}
@Override
@CacheEvict(value = CACHE_NAME, key = CACHE_KEY_PATTERN)
public boolean updateConfig(WechatConfig config) {
return updateById(config);
}
@Override
@CacheEvict(value = CACHE_NAME, allEntries = true)
public boolean deleteConfig(Long id) {
return removeById(id);
}
@Override
@CacheEvict(value = CACHE_NAME, key = CACHE_KEY_PATTERN)
public boolean switchConfig(String type, String tenantId) {
// 这里可以添加切换配置的具体逻辑
return true;
}
}
@@ -0,0 +1,130 @@
//package com.zlt.wechat.service.impl;
//
//import com.wechat.pay.java.core.Config;
//import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
//import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
//import com.wechat.pay.java.service.payments.model.Transaction;
//import com.wechat.pay.java.service.refund.RefundService;
//import com.wechat.pay.java.service.refund.model.Refund;
//import com.wechat.pay.java.service.refund.model.RefundNotification;
//import com.wechat.pay.java.service.refund.model.RefundRequest;
//import com.wechat.pay.java.service.refund.model.RefundResponse;
//import com.zlt.wechat.entity.WechatConfig;
//import com.zlt.wechat.service.PrivateKeyService;
//import com.zlt.wechat.service.WechatConfigService;
//import com.zlt.wechat.service.WechatPayService;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import java.io.ByteArrayInputStream;
//import java.util.Map;
//
//@Service
//public class WechatPayServiceImpl implements WechatPayService {
//
// @Autowired
// private WechatConfigService configService;
//
// @Autowired
// private PrivateKeyService privateKeyService;
//
// @Autowired
// private JsapiServiceExtension jsapiService;
//
// @Autowired
// private RefundService refundService;
//
// @Autowired
// private Config wxPayConfig;
//
// @Override
// public PrepayWithRequestPaymentResponse createJsapiOrder(String tenantId, String openId,
// int amount, String description, String outTradeNo) {
// // 切换租户配置
// configService.switchConfig("PAY", tenantId);
//
// // 创建支付订单
// /*return jsapiService.prepayWithRequestPayment(
// openId,
// description,
// outTradeNo,
// amount,
// "CNY"
// );*/
// return new PrepayWithRequestPaymentResponse();
// }
//
// @Override
// public Transaction queryOrder(String tenantId, String outTradeNo) {
// configService.switchConfig("PAY", tenantId);
// return jsapiService.queryOrderByOutTradeNo(outTradeNo);
// }
//
// @Override
// public void closeOrder(String tenantId, String outTradeNo) {
// configService.switchConfig("PAY", tenantId);
// jsapiService.closeOrder(outTradeNo);
// }
//
// @Override
// public RefundResponse refund(String tenantId, String outTradeNo, String outRefundNo,
// int amount, String reason) {
// configService.switchConfig("PAY", tenantId);
//
// RefundRequest request = new RefundRequest();
// request.setOutTradeNo(outTradeNo);
// request.setOutRefundNo(outRefundNo);
// request.setAmount(new RefundRequest.Amount(amount, "CNY"));
// request.setReason(reason);
//
// return refundService.refund(request);
// }
//
// @Override
// public Refund queryRefund(String tenantId, String outRefundNo) {
// configService.switchConfig("PAY", tenantId);
// return refundService.queryByOutRefundNo(outRefundNo);
// }
//
// @Override
// public RefundNotification parseRefundNotify(String tenantId, String notifyData) {
// configService.switchConfig("PAY", tenantId);
// return refundService.parseRefundNotification(notifyData);
// }
//
// @Override
// public boolean uploadPrivateKey(String tenantId, String privateKey) {
// try {
// privateKeyService.uploadPrivateKey(tenantId, "PAY",
// new ByteArrayInputStream(privateKey.getBytes()));
// return true;
// } catch (Exception e) {
// return false;
// }
// }
//
// @Override
// public boolean updatePayConfig(String tenantId, Map<String, String> config) {
// try {
// WechatConfig wechatConfig = configService.getConfig("PAY", tenantId);
// if (wechatConfig == null) {
// wechatConfig = new WechatConfig();
// wechatConfig.setType("PAY");
// wechatConfig.setTenantId(tenantId);
// }
//
// // 更新配置信息
// wechatConfig.setMerchantId(config.get("merchantId"));
// wechatConfig.setAppId(config.get("appId"));
// wechatConfig.setMchKey(config.get("mchKey"));
// wechatConfig.setMchSerialNo(config.get("mchSerialNo"));
// wechatConfig.setApiV3Key(config.get("apiV3Key"));
// wechatConfig.setNotifyUrl(config.get("notifyUrl"));
// wechatConfig.setStatus(1);
//
// return configService.saveOrUpdate(wechatConfig);
// } catch (Exception e) {
// return false;
// }
// }
//}
@@ -0,0 +1,26 @@
CREATE TABLE `wechat_config` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`type` varchar(10) NOT NULL COMMENT '配置类型:MP-公众号,MINI-小程序,PAY-支付',
`merchant_id` varchar(32) NOT NULL COMMENT '商户ID',
`app_id` varchar(32) NOT NULL COMMENT '应用ID',
`app_secret` varchar(64) NOT NULL COMMENT '应用密钥',
`mch_key` varchar(64) DEFAULT NULL COMMENT '商户API密钥',
`mch_serial_no` varchar(64) DEFAULT NULL COMMENT '商户证书序列号',
`private_key_path` varchar(256) DEFAULT NULL COMMENT '商户私钥文件路径',
`api_v3_key` varchar(64) DEFAULT NULL COMMENT 'APIv3密钥',
`notify_url` varchar(256) DEFAULT NULL COMMENT '支付回调地址',
`token` varchar(64) DEFAULT NULL COMMENT '微信公众号token',
`aes_key` varchar(64) DEFAULT NULL COMMENT '微信公众号aesKey',
`payment_success_template_id` varchar(64) DEFAULT NULL COMMENT '支付成功通知模板ID',
`video_complete_template_id` varchar(64) DEFAULT NULL COMMENT '视频处理完成通知模板ID',
`video_fail_template_id` varchar(64) DEFAULT NULL COMMENT '视频处理失败通知模板ID',
`profit_sharing_enabled` tinyint(1) DEFAULT '1' COMMENT '是否启用分账',
`async_enabled` tinyint(1) DEFAULT '1' COMMENT '是否启用异步处理',
`async_pool_size` int(11) DEFAULT '5' COMMENT '异步处理线程池大小',
`status` tinyint(4) DEFAULT '1' COMMENT '状态:0-禁用,1-启用',
`remark` varchar(256) DEFAULT NULL COMMENT '备注',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_type_merchant` (`type`,`merchant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='微信配置表';
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.zlt</groupId>
<artifactId>zlt-commons</artifactId>
<version>6.0.0</version>
</parent>
<artifactId>zlt-wechat-spring-boot-starter</artifactId>
<description>微信Spring Boot启动器</description>
<dependencies>
<!-- 微信核心模块 -->
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-wechat-common-core</artifactId>
<version>${project.version}</version>
</dependency>
<!-- Spring Boot 相关依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,173 @@
package com.zlt.wechat.config;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.central.common.context.TenantContextHolder;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.SettleInfo;
import com.wechat.pay.java.service.profitsharing.ProfitsharingService;
import com.wechat.pay.java.service.refund.RefundService;
import com.zlt.wechat.entity.WechatConfig;
import com.zlt.wechat.service.WechatConfigService;
import com.zlt.wechat.service.PrivateKeyService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableConfigurationProperties(WechatProperties.class)
public class WechatAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public WxMpService wxMpService(WechatConfigService configService) {
return new WxMpServiceImpl() {
@Override
public WxMpDefaultConfigImpl getWxMpConfigStorage() {
WechatConfig config = configService.getConfig("MP", getCurrentTenantId());
WxMpDefaultConfigImpl wxConfig = new WxMpDefaultConfigImpl();
wxConfig.setAppId(config.getAppId());
wxConfig.setSecret(config.getAppSecret());
wxConfig.setToken(config.getToken());
wxConfig.setAesKey(config.getAesKey());
return wxConfig;
}
};
}
@Bean
@ConditionalOnMissingBean
public WxMaService wxMaService(WechatConfigService configService) {
return new WxMaServiceImpl() {
@Override
public WxMaDefaultConfigImpl getWxMaConfig() {
WechatConfig config = configService.getConfig("MINI", getCurrentTenantId());
WxMaDefaultConfigImpl wxConfig = new WxMaDefaultConfigImpl();
wxConfig.setAppid(config.getAppId());
wxConfig.setSecret(config.getAppSecret());
return wxConfig;
}
};
}
/*@Bean
@ConditionalOnMissingBean
public WxPayService wxPayService(WechatConfigService configService) {
return new WxPayServiceImpl() {
@Override
public WxPayConfig getConfig() {
WechatConfig config = configService.getConfig("PAY", getCurrentMerchantId());
WxPayConfig payConfig = new WxPayConfig();
payConfig.setAppId(config.getAppId());
payConfig.setMchId(config.getMerchantId());
payConfig.setMchKey(config.getMchKey());
payConfig.setKeyPath(config.getPrivateKeyPath());
payConfig.setNotifyUrl(config.getNotifyUrl());
payConfig.setApiV3Key(config.getApiV3Key());
payConfig.setPrivateKeyPath(config.getPrivateKeyPath());
payConfig.setPrivateCertPath(config.getPrivateKeyPath());
payConfig.setCertSerialNo(config.getMchSerialNo());
return payConfig;
}
};
}*/
@Bean
@ConditionalOnMissingBean
public Config wxPayConfig(WechatConfigService configService, PrivateKeyService privateKeyService) {
WechatConfig config = configService.getConfig("PAY", getCurrentTenantId());
String privateKey = privateKeyService.getPrivateKey(getCurrentTenantId(), "PAY");
return new RSAAutoCertificateConfig.Builder()
.merchantId(config.getMerchantId())
.privateKey(privateKey)
.merchantSerialNumber(config.getMchSerialNo())
.apiV3Key(config.getApiV3Key())
.build();
}
@Bean
@ConditionalOnMissingBean
public JsapiServiceExtension jsapiServiceExtension(Config config) {
return new JsapiServiceExtension.Builder().config(config).build();
}
@Bean
@ConditionalOnMissingBean
public RefundService refundService(Config config) {
return new RefundService.Builder().config(config).build();
}
@Bean
@ConditionalOnMissingBean
public NotificationConfig notificationConfig(WechatConfigService configService, PrivateKeyService privateKeyService) {
WechatConfig config = configService.getConfig("PAY", getCurrentTenantId());
String privateKey = privateKeyService.getPrivateKey(getCurrentTenantId(), "PAY");
return new RSAAutoCertificateConfig.Builder()
.merchantId(config.getMerchantId())
.privateKey(privateKey)
.merchantSerialNumber(config.getMchSerialNo())
.apiV3Key(config.getApiV3Key())
.build();
}
@Bean
@ConditionalOnMissingBean
public NotificationParser notificationParser(NotificationConfig config) {
return new NotificationParser(config);
}
@Bean
@ConditionalOnMissingBean
public ProfitsharingService profitsharingService(Config config) {
return new ProfitsharingService.Builder().config(config).build();
}
@Bean
@ConditionalOnMissingBean
public SettleInfo settleInfo(WechatConfigService configService) {
WechatConfig config = configService.getConfig("PAY", getCurrentTenantId());
SettleInfo settleInfo = new SettleInfo();
settleInfo.setProfitSharing(config.getProfitSharingEnabled());
return settleInfo;
}
@Bean
@ConditionalOnMissingBean
public Executor profitSharingExecutor(WechatConfigService configService) {
WechatConfig config = configService.getConfig("PAY", getCurrentTenantId());
if (!config.getAsyncEnabled()) {
return null;
}
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(config.getAsyncPoolSize());
executor.setMaxPoolSize(config.getAsyncPoolSize());
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("profit-sharing-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
/**
* 获取当前商户ID
* 这里需要根据实际业务场景实现,可以从ThreadLocal、请求上下文等获取
*/
private String getCurrentTenantId() {
// 获取当前租户的逻辑
return TenantContextHolder.getTenant();
}
}
@@ -0,0 +1,2 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.zlt.wechat.config.WechatAutoConfiguration
+7 -1
View File
@@ -92,6 +92,12 @@
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-wechat-common-core</artifactId>
<version>6.0.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
@@ -135,4 +141,4 @@
</plugins>
<finalName>${project.artifactId}</finalName>
</build>
</project>
</project>
@@ -1,6 +1,6 @@
package com.central.oauth.service;
import com.central.common.model.MiniAppConfig;
import com.zlt.wechat.entity.WechatConfig;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
@@ -44,5 +44,5 @@ public interface ZltUserDetailsService extends UserDetailsService {
* @param appId
* @return
*/
MiniAppConfig loadMiniAppConfig(String appId);
WechatConfig loadMiniAppConfig(String appId);
}
@@ -2,10 +2,11 @@ package com.central.oauth.service.impl;
import com.central.common.constant.SecurityConstants;
import com.central.common.feign.UserService;
import com.central.common.model.MiniAppConfig;
import com.central.common.model.SysUser;
import com.central.common.utils.LoginUserUtils;
import com.central.oauth.service.ZltUserDetailsService;
import com.zlt.wechat.entity.WechatConfig;
import com.zlt.wechat.service.WechatConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
@@ -29,6 +30,9 @@ public class UserDetailServiceImpl implements ZltUserDetailsService {
@Resource
private UserService userService;
@Resource
private WechatConfigService wechatConfigService;
@Override
public boolean supports(String accountType) {
return ACCOUNT_TYPE.equals(accountType);
@@ -59,8 +63,8 @@ public class UserDetailServiceImpl implements ZltUserDetailsService {
}
@Override
public MiniAppConfig loadMiniAppConfig(String appId) {
return userService.getByAppid(appId);
public WechatConfig loadMiniAppConfig(String appId) {
return wechatConfigService.getConfig(appId);
}
@Override
@@ -1,13 +1,13 @@
package com.central.oauth.support.tencent;
import com.alibaba.fastjson.JSONObject;
import com.central.common.model.MiniAppConfig;
import com.central.oauth.exception.CustomOAuth2AuthenticationException;
import com.central.oauth.service.impl.UserDetailServiceFactory;
import com.central.oauth.support.base.BaseAuthenticationProvider;
import com.central.oauth2.common.properties.SecurityProperties;
import com.central.oauth2.common.token.TencentAuthenticationToken;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zlt.wechat.entity.WechatConfig;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
@@ -75,13 +75,13 @@ public class TencentAuthenticationProvider extends BaseAuthenticationProvider {
String appid = authToken.getAppId(); // 前端需传递
// 1. 根据appid查找配置
MiniAppConfig config = userDetailsServiceFactory.getService(authToken).loadMiniAppConfig(appid);
WechatConfig config = userDetailsServiceFactory.getService(authToken).loadMiniAppConfig(appid);
if (config == null) {
throw new CustomOAuth2AuthenticationException("不支持的appid");
}
// 2. 用查到的appid/secret调用微信接口
Map<String,Object> wxLoginResult = getWxSessionResult(code, config.getAppid(), config.getSecret());
Map<String,Object> wxLoginResult = getWxSessionResult(code, config.getAppId(), config.getAppSecret());
UserDetails userDetails;
try {