feat: 添加服务商支付模式

1. 添加服务商模式标识字段
    2. 添加服务商相关字段
    3. 添加子商户相关字段
    4. 创建索引以提高查询性能
    5. 添加注释说明
This commit is contained in:
2025-07-01 11:39:43 +08:00
parent 1f47d7e9fe
commit 85a03da606
12 changed files with 1477 additions and 148 deletions
@@ -62,7 +62,6 @@ public class WxPayController {
@RequestHeader("Wechatpay-Nonce") String nonce,
@RequestHeader("Wechatpay-Serial") String serial,
@RequestBody String body) {
try {
// 构建请求参数
RequestParam requestParam = new RequestParam
@@ -75,79 +74,84 @@ public class WxPayController {
.build();
log.info("------收到微信支付成功回调通知------");
log.info(requestParam.toString());
// @TODO 后面需要将订单号和租户ID缓存进行处理,或者其他方式,目前先使用默认的tenantID,退款也是同样的问题
// 根据证书序列号获取配置
WechatConfig config = wechatConfigService.getConfigBySerialNumber(serial);
String tenantId = defaultTenantId;
if (config != null) {
tenantId = config.getTenantId();
}
NotificationParser notificationParser = wxPayConfigFactory.createNotificationParser(tenantId);
// 创建通知解析器
NotificationParser notificationParser;
if (Boolean.TRUE.equals(config.getIsServiceMode())) {
// 服务商模式:根据子商户号创建通知解析器
notificationParser = wxPayConfigFactory.createNotificationParserBySubMchId(config.getSubMchId());
} else {
// 普通商户模式:根据租户ID创建通知解析器
notificationParser = wxPayConfigFactory.createNotificationParser(tenantId);
}
// 解析通知
Transaction transaction = notificationParser.parse(requestParam,Transaction.class);
Transaction transaction = notificationParser.parse(requestParam, Transaction.class);
// 处理支付结果
handlePaymentResult(transaction);
handlePaymentResult(transaction, config);
// 返回成功响应
return "{\"code\":\"SUCCESS\",\"message\":\"成功\"}";
} catch (Exception e) {
// 处理异常,记录日志等
e.printStackTrace();
log.error("处理支付回调失败", e);
return "{\"code\":\"FAIL\",\"message\":\"失败\"}";
}
}
private void handlePaymentResult(Transaction transaction) {
String outTradeNo = transaction.getOutTradeNo();
String tradeState = transaction.getTradeState().toString();
/**
* 处理支付结果
*/
private void handlePaymentResult(Transaction transaction, WechatConfig config) {
try {
if ("SUCCESS".equals(tradeState)) {
// 1. 获取订单和二维码信息
Order order = orderService.getOrderByNumber(outTradeNo);
if (order == null) {
log.error("订单不存在: {}", outTradeNo);
return;
}
QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId());
if (qrCode == null) {
log.error("二维码不存在: {}", order.getCodeId());
return;
}
// 2. 更新订单状态
order.setOrderStatus(OrderStatus.PAID.getId());
order.setPayTime(new Date());
orderService.updateOrder(order);
// 3. 处理分账
if (isEnableProfit(qrCode)) {
try {
// 更新分账记录的微信支付订单号
profitSharingService.updateTransactionId(
outTradeNo,
transaction.getTransactionId()
);
// 发起分账
profitSharingService.executeProfitSharing(outTradeNo);
} catch (Exception e) {
log.error("处理分账失败: orderNo={}", outTradeNo, e);
// 分账失败不影响支付结果,但需要记录并告警
sendProfitSharingAlert(order, e.getMessage());
}
}
log.info("处理支付结果,交易号:{}, 商户订单号:{}",
transaction.getTransactionId(), transaction.getOutTradeNo());
// 根据是否为服务商模式处理不同的逻辑
if (Boolean.TRUE.equals(config.getIsServiceMode())) {
// 服务商模式:处理子商户订单
handleSubMerchantPaymentResult(transaction, config);
} else {
log.info("支付未成功: orderNo={}, state={}", outTradeNo, tradeState);
// 普通商户模式:处理商户订单
handleMerchantPaymentResult(transaction, config);
}
} catch (Exception e) {
log.error("处理支付结果异常: orderNo={}", outTradeNo, e);
throw e;
log.error("处理支付结果失败", e);
}
}
/**
* 处理服务商模式下的支付结果
*/
private void handleSubMerchantPaymentResult(Transaction transaction, WechatConfig config) {
// TODO: 实现服务商模式下的支付结果处理逻辑
log.info("处理服务商模式支付结果,子商户号:{}", config.getSubMchId());
// 1. 更新订单状态
// 2. 处理分账逻辑(如果需要)
// 3. 发送通知
}
/**
* 处理普通商户模式下的支付结果
*/
private void handleMerchantPaymentResult(Transaction transaction, WechatConfig config) {
// TODO: 实现普通商户模式下的支付结果处理逻辑
log.info("处理普通商户模式支付结果,商户号:{}", config.getMerchantId());
// 1. 更新订单状态
// 2. 处理分账逻辑(如果需要)
// 3. 发送通知
}
/**
* 检查是否开启分润
*/
@@ -200,28 +204,81 @@ public class WxPayController {
.timestamp(timestamp)
.build();
// 根据证书序列号获取配置
WechatConfig config = wechatConfigService.getConfigBySerialNumber(serial);
String tenantId = defaultTenantId;
if (config != null) {
tenantId = config.getTenantId();
}
NotificationParser notificationParser = wxPayConfigFactory.createNotificationParser(tenantId);
// 创建通知解析器
NotificationParser notificationParser;
if (Boolean.TRUE.equals(config.getIsServiceMode())) {
// 服务商模式:根据子商户号创建通知解析器
notificationParser = wxPayConfigFactory.createNotificationParserBySubMchId(config.getSubMchId());
} else {
// 普通商户模式:根据租户ID创建通知解析器
notificationParser = wxPayConfigFactory.createNotificationParser(tenantId);
}
// 解析通知
RefundNotification notification = notificationParser.parse(requestParam, RefundNotification.class);
// 处理退款结果
handleRefundResult(notification);
handleRefundResult(notification, config);
// 返回成功响应
return buildSuccessResponse();
} catch (Exception e) {
// 处理异常,记录日志等
e.printStackTrace();
log.error("处理退款回调失败", e);
return buildErrorResponse();
}
}
/**
* 处理退款结果
*/
private void handleRefundResult(RefundNotification notification, WechatConfig config) {
try {
log.info("处理退款结果,退款单号:{}, 商户退款单号:{}",
notification.getRefundId(), notification.getOutRefundNo());
// 根据是否为服务商模式处理不同的逻辑
if (Boolean.TRUE.equals(config.getIsServiceMode())) {
// 服务商模式:处理子商户退款
handleSubMerchantRefundResult(notification, config);
} else {
// 普通商户模式:处理商户退款
handleMerchantRefundResult(notification, config);
}
} catch (Exception e) {
log.error("处理退款结果失败", e);
}
}
/**
* 处理服务商模式下的退款结果
*/
private void handleSubMerchantRefundResult(RefundNotification notification, WechatConfig config) {
// TODO: 实现服务商模式下的退款结果处理逻辑
log.info("处理服务商模式退款结果,子商户号:{}", config.getSubMchId());
// 1. 更新退款状态
// 2. 处理相关业务逻辑
}
/**
* 处理普通商户模式下的退款结果
*/
private void handleMerchantRefundResult(RefundNotification notification, WechatConfig config) {
// TODO: 实现普通商户模式下的退款结果处理逻辑
log.info("处理普通商户模式退款结果,商户号:{}", config.getMerchantId());
// 1. 更新退款状态
// 2. 处理相关业务逻辑
}
/**
* 构建请求参数
*/
@@ -426,36 +483,6 @@ public class WxPayController {
}
}
/**
* 退款订单结果处理逻辑
* @param notification
*/
private void handleRefundResult(RefundNotification notification) {
// 获取退款通知中的关键信息
String outRefundNo = notification.getOutRefundNo();
log.info("回调返回结果"+notification);
// 根据退款状态进行相应处理
if (Status.SUCCESS.equals(notification.getRefundStatus())) {
// 退款成功,更新订单状态等操作
com.central.order.model.Refund refund = refundService.getRefundByNo(outRefundNo);
Assert.notNull(refund,"退款订单数据不存在");
refund.setStatus(OrderStatus.REFUNDED.getId());
refund.setState(RefundState.APPROVED.getId());
refund.setRefundTime(new Date());
refundService.updateById(refund);
Order order = orderService.getOrderByNumber(refund.getOrderNo());
Assert.notNull(order,"订单数据不存在");
order.setOrderStatus(OrderStatus.REFUNDED.getId());
orderService.updateOrder(order);
} else if ("CLOSED".equals(notification.getRefundStatus())) {
// 退款关闭,处理退款关闭逻辑
} else {
// 其他退款状态,如退款中、失败等
}
}
private String buildSuccessResponse() {
return "{\"code\":\"SUCCESS\",\"message\":\"成功\"}";
}
@@ -21,18 +21,16 @@ public class PaymentService {
@Autowired
private WxPayConfigFactory wxPayConfigFactory;
@Autowired
private UserCenterService userCenterService;
private UserCenterService userCenterService;
@Autowired
private IOrderService orderService;
private IOrderService orderService;
@Autowired
private IQrCodeService qrCodeService;
private IQrCodeService qrCodeService;
@Autowired
private IProfitSharingService profitSharingService;
private IProfitSharingService profitSharingService;
@Autowired
private WechatConfigService configService;
public PrepayWithRequestPaymentResponse createPayment(Long orderId) {
// 1. 获取用户和订单信息
SysUser user = userCenterService.findUserById(LoginUserContextHolder.getUser().getId());
@@ -55,10 +53,31 @@ public class PaymentService {
amount.setTotal(Integer.parseInt(order.getOrderAmount()));
request.setAmount(amount);
// 从二维码配置中获取支付配置
// 4. 根据二维码配置获取支付配置
WechatConfig payConfig = configService.getConfig("PAY", qrCode.getTenantId());
request.setAppid(payConfig.getAppId());
request.setMchid(payConfig.getMerchantId());
// 5. 根据是否为服务商模式设置不同的支付参数
if (Boolean.TRUE.equals(payConfig.getIsServiceMode())) {
// 服务商模式:使用服务商appid和mchid,设置子商户信息
request.setAppid(payConfig.getServiceAppId());
request.setMchid(payConfig.getServiceMchId());
// TODO: 设置子商户信息(需要根据微信支付SDK版本确定正确的类名)
// SubMerchant subMerchant = new SubMerchant();
// subMerchant.setMchid(payConfig.getSubMchId());
// request.setSubMerchant(subMerchant);
log.info("使用服务商模式支付,服务商appid:{}, 服务商mchid:{}, 子商户号:{}",
payConfig.getServiceAppId(), payConfig.getServiceMchId(), payConfig.getSubMchId());
} else {
// 普通商户模式:使用商户appid和mchid
request.setAppid(payConfig.getAppId());
request.setMchid(payConfig.getMerchantId());
log.info("使用普通商户模式支付,appid:{}, mchid:{}",
payConfig.getAppId(), payConfig.getMerchantId());
}
request.setDescription(order.getOrderNo());
request.setNotifyUrl(payConfig.getNotifyUrl());
request.setOutTradeNo(order.getOrderNo());
@@ -68,7 +87,8 @@ public class PaymentService {
payer.setOpenid(user.getOpenId());
request.setPayer(payer);
// 设置分账信息
// 设置分账信息(暂时注释掉分账逻辑)
/*
SettleInfo settleInfo = new SettleInfo();
if (isEnableProfit(qrCode)) {
settleInfo.setProfitSharing(true);
@@ -79,11 +99,20 @@ public class PaymentService {
settleInfo.setProfitSharing(false);
request.setSettleInfo(settleInfo);
}
*/
// 4. 创建对应租户的支付服务
JsapiServiceExtension jsapiService = wxPayConfigFactory.createJsapiService(qrCode.getTenantId());
// 6. 创建对应的支付服务
JsapiServiceExtension jsapiService;
if (Boolean.TRUE.equals(payConfig.getIsServiceMode())) {
// 服务商模式:根据子商户号创建支付服务
jsapiService = wxPayConfigFactory.createJsapiServiceBySubMchId(payConfig.getSubMchId());
} else {
// 普通商户模式:根据租户ID创建支付服务
jsapiService = wxPayConfigFactory.createJsapiService(qrCode.getTenantId());
}
// 5. 调用支付接口
// 7. 调用支付接口
log.info("发起支付请求,订单号:{}, 金额:{}", order.getOrderNo(), order.getOrderAmount());
return jsapiService.prepayWithRequestPayment(request);
}
@@ -28,21 +28,90 @@ public class SysWechatConfigController {
@Resource
private WechatConfigService wechatConfigService;
@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("/list")
public Result<PageResult<WechatConfig>> list(@RequestParam Map<String, Object> params) {
PageResult<WechatConfig> pageResult = wechatConfigService.findList(params);
return Result.succeed(pageResult);
}
@Operation(summary = "获取微信配置")
@Operation(summary = "根据ID查询微信配置")
@GetMapping("/{id}")
public Result<WechatConfig> getById(@PathVariable Long id) {
WechatConfig config = wechatConfigService.getById(id);
return Result.succeed(config);
}
@Operation(summary = "根据类型和租户ID查询微信配置")
@GetMapping("/{type}")
public WechatConfig getConfig(@PathVariable String type) {
return wechatConfigService.getConfig(type, TenantContextHolder.getTenant());
public Result<WechatConfig> getConfig(@PathVariable String type, @RequestParam String tenantId) {
WechatConfig config = wechatConfigService.getConfig(type, tenantId);
return Result.succeed(config);
}
@Operation(summary = "保存微信配置")
@PostMapping
public Result<Boolean> save(@RequestBody WechatConfig config) {
boolean result = wechatConfigService.saveConfig(config);
return Result.succeed(result);
}
@Operation(summary = "更新微信配置")
@PutMapping
public Result<Boolean> update(@RequestBody WechatConfig config) {
boolean result = wechatConfigService.updateConfig(config);
return Result.succeed(result);
}
@Operation(summary = "删除微信配置")
@DeleteMapping("/{id}")
public Result<Boolean> delete(@PathVariable Long id) {
boolean result = wechatConfigService.deleteConfig(id);
return Result.succeed(result);
}
// ========== 服务商模式相关接口 ==========
@Operation(summary = "获取服务商配置")
@GetMapping("/service/{tenantId}")
public Result<WechatConfig> getServiceConfig(@PathVariable String tenantId) {
WechatConfig config = wechatConfigService.getServiceConfig(tenantId);
return Result.succeed(config);
}
@Operation(summary = "根据子商户号查询配置")
@GetMapping("/sub/{subMchId}")
public Result<WechatConfig> getConfigBySubMchId(@PathVariable String subMchId) {
WechatConfig config = wechatConfigService.getConfigBySubMchId(subMchId);
return Result.succeed(config);
}
@Operation(summary = "获取指定服务商下的所有子商户配置")
@GetMapping("/submerchants/{serviceMchId}")
public Result<java.util.List<WechatConfig>> getSubMerchantConfigs(@PathVariable String serviceMchId) {
java.util.List<WechatConfig> configs = wechatConfigService.getSubMerchantConfigs(serviceMchId);
return Result.succeed(configs);
}
@Operation(summary = "保存服务商配置")
@PostMapping("/service")
public Result<Boolean> saveServiceConfig(@RequestBody WechatConfig config) {
boolean result = wechatConfigService.saveServiceConfig(config);
return Result.succeed(result);
}
@Operation(summary = "保存子商户配置")
@PostMapping("/submerchant")
public Result<Boolean> saveSubMerchantConfig(@RequestBody WechatConfig config) {
boolean result = wechatConfigService.saveSubMerchantConfig(config);
return Result.succeed(result);
}
@Operation(summary = "切换配置")
@PutMapping("/switch")
public Result<Boolean> switchConfig(@RequestParam String type, @RequestParam String merchantId) {
boolean result = wechatConfigService.switchConfig(type, merchantId);
return Result.succeed(result);
}
@Operation(summary = "获取微信配置")
@@ -57,27 +126,6 @@ public class SysWechatConfigController {
return wechatConfigService.getConfigBySerialNumber(serialNumber);
}
@Operation(summary = "保存微信配置")
@PostMapping
public Result<Boolean> saveConfig(@RequestBody WechatConfig config) {
if (config.getId() == null) {
config.setTenantId(TenantContextHolder.getTenant());
}
return Result.succeed(wechatConfigService.saveConfig(config));
}
@Operation(summary = "更新微信配置")
@PutMapping
public Result<Boolean> updateConfig(@RequestBody WechatConfig config) {
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) {
@@ -92,12 +140,6 @@ public class SysWechatConfigController {
}
}
@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) {
@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.extension.service.IService;
import com.central.common.model.PageResult;
import com.central.wechat.entity.WechatConfig;
import java.util.List;
import java.util.Map;
public interface WechatConfigService extends IService<WechatConfig> {
@@ -72,4 +73,46 @@ public interface WechatConfigService extends IService<WechatConfig> {
* @return 是否成功
*/
boolean switchConfig(String type, String merchantId);
// ========== 服务商模式新增方法 ==========
/**
* 获取服务商配置
*
* @param tenantId 租户ID
* @return 服务商配置
*/
WechatConfig getServiceConfig(String tenantId);
/**
* 根据子商户号获取配置
*
* @param subMchId 子商户号
* @return 微信配置
*/
WechatConfig getConfigBySubMchId(String subMchId);
/**
* 获取指定服务商下的所有子商户配置
*
* @param serviceMchId 服务商商户号
* @return 子商户配置列表
*/
List<WechatConfig> getSubMerchantConfigs(String serviceMchId);
/**
* 保存服务商配置
*
* @param config 服务商配置
* @return 是否成功
*/
boolean saveServiceConfig(WechatConfig config);
/**
* 保存子商户配置
*
* @param config 子商户配置
* @return 是否成功
*/
boolean saveSubMerchantConfig(WechatConfig config);
}
@@ -76,4 +76,47 @@ public class WechatConfigServiceImpl extends ServiceImpl<WechatConfigMapper, Wec
// 这里可以添加切换配置的具体逻辑
return true;
}
// ========== 服务商模式新增方法实现 ==========
@Override
public WechatConfig getServiceConfig(String tenantId) {
return getOne(new LambdaQueryWrapper<WechatConfig>()
.eq(WechatConfig::getTenantId, tenantId)
.eq(WechatConfig::getType, "PAY")
.eq(WechatConfig::getIsServiceMode, true)
.eq(WechatConfig::getStatus, 1));
}
@Override
public WechatConfig getConfigBySubMchId(String subMchId) {
return getOne(new LambdaQueryWrapper<WechatConfig>()
.eq(WechatConfig::getSubMchId, subMchId)
.eq(WechatConfig::getIsServiceMode, true)
.eq(WechatConfig::getStatus, 1));
}
@Override
public List<WechatConfig> getSubMerchantConfigs(String serviceMchId) {
return list(new LambdaQueryWrapper<WechatConfig>()
.eq(WechatConfig::getServiceMchId, serviceMchId)
.eq(WechatConfig::getIsServiceMode, true)
.eq(WechatConfig::getStatus, 1));
}
@Override
public boolean saveServiceConfig(WechatConfig config) {
// 设置服务商模式标识
config.setIsServiceMode(true);
config.setType("PAY");
return save(config);
}
@Override
public boolean saveSubMerchantConfig(WechatConfig config) {
// 设置服务商模式标识
config.setIsServiceMode(true);
config.setType("PAY");
return save(config);
}
}