fix(服务商模式支付管理): 服务商支付流程打通

This commit is contained in:
2025-07-14 00:38:12 +08:00
parent 74ebf2e947
commit a333a1a663
7 changed files with 297 additions and 400 deletions
@@ -1,13 +1,10 @@
package com.central.order.controller;
import com.central.order.constants.ProfitSharingConstants;
import com.central.order.enums.OrderStatus;
import com.central.order.enums.RefundState;
import com.central.order.model.Order;
import com.central.order.model.ProfitSharing;
import com.central.order.model.QrCode;
import com.central.order.service.IOrderService;
import com.central.order.service.IProfitSharingService;
import com.central.order.service.IQrCodeService;
import com.central.order.service.IRefundService;
import com.central.wechat.config.WxPayConfigFactory;
@@ -19,18 +16,13 @@ import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.refund.model.RefundNotification;
import com.wechat.pay.java.service.refund.model.Status;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Slf4j
@RestController
@@ -44,8 +36,6 @@ public class WxPayController {
private IRefundService refundService;
@Autowired
private IQrCodeService qrCodeService;
@Autowired
private IProfitSharingService profitSharingService;
@Autowired
private WxPayConfigFactory wxPayConfigFactory;
@@ -74,13 +64,11 @@ public class WxPayController {
.build();
log.info("------收到微信支付成功回调通知------");
log.info(requestParam.toString());
// 根据证书序列号获取配置
WechatConfig config = wechatConfigService.getConfigBySerialNumber(serial);
String tenantId = defaultTenantId;
if (config != null) {
tenantId = config.getTenantId();
}
Assert.notNull(config,"支付配置参数为空,请确认参数是否正确配置");
String tenantId = config.getTenantId();
// 创建通知解析器
NotificationParser notificationParser;
@@ -91,7 +79,7 @@ public class WxPayController {
// 普通商户模式:根据租户ID创建通知解析器
notificationParser = wxPayConfigFactory.createNotificationParser(tenantId);
}
// 解析通知
Transaction transaction = notificationParser.parse(requestParam, Transaction.class);
@@ -112,9 +100,9 @@ public class WxPayController {
*/
private void handlePaymentResult(Transaction transaction, WechatConfig config) {
try {
log.info("处理支付结果,交易号:{}, 商户订单号:{}",
log.info("处理支付结果,交易号:{}, 商户订单号:{}",
transaction.getTransactionId(), transaction.getOutTradeNo());
// 根据是否为服务商模式处理不同的逻辑
if (Boolean.TRUE.equals(config.getIsServiceMode())) {
// 服务商模式:处理子商户订单
@@ -134,7 +122,7 @@ public class WxPayController {
private void handleSubMerchantPaymentResult(Transaction transaction, WechatConfig config) {
// TODO: 实现服务商模式下的支付结果处理逻辑
log.info("处理服务商模式支付结果,子商户号:{}", config.getSubMchId());
// 1. 更新订单状态
// 2. 处理分账逻辑(如果需要)
// 3. 发送通知
@@ -144,48 +132,39 @@ public class WxPayController {
* 处理普通商户模式下的支付结果
*/
private void handleMerchantPaymentResult(Transaction transaction, WechatConfig config) {
// TODO: 实现普通商户模式下的支付结果处理逻辑
log.info("处理普通商户模式支付结果,商户号:{}", config.getMerchantId());
// 1. 更新订单状态
// 2. 处理分账逻辑(如果需要)
// 3. 发送通知
}
/**
* 检查是否开启分润
*/
private boolean isEnableProfit(QrCode qrCode) {
return qrCode != null &&
Integer.valueOf(1).equals(qrCode.getEnableProfit()) &&
qrCode.getPayeeStatus() != null &&
qrCode.getPayeeStatus() == 1 && // 确保分账账号已验证
qrCode.getPayeeAccount() != null && // 确保有收款账号
qrCode.getProfitRate() != null; // 确保有分润比例
}
String outTradeNo = transaction.getOutTradeNo();
String tradeState = transaction.getTradeState().toString();
/**
* 发送分账异常告警
*/
private void sendProfitSharingAlert(Order order, String errorMessage) {
try {
String alertMessage = String.format(
"分账处理异常告警\n" +
"订单号:%s\n" +
"异常信息:%s\n" +
"时间:%s",
order.getOrderNo(),
errorMessage,
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())
);
if ("SUCCESS".equals(tradeState)) {
// 1. 获取订单和二维码信息
Order order = orderService.getOrderByNumber(outTradeNo);
if (order == null) {
log.error("订单不存在: {}", outTradeNo);
return;
}
log.error(alertMessage);
// TODO: 实现具体的告警通知逻辑
} catch (Exception e) {
log.error("发送分账异常告警失败", e);
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);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@PostMapping("/refund/notify")
public String refundCallback(@RequestHeader("Wechatpay-Signature") String signature,
@RequestHeader("Wechatpay-Timestamp") String timestamp,
@@ -220,7 +199,7 @@ public class WxPayController {
// 普通商户模式:根据租户ID创建通知解析器
notificationParser = wxPayConfigFactory.createNotificationParser(tenantId);
}
// 解析通知
RefundNotification notification = notificationParser.parse(requestParam, RefundNotification.class);
@@ -241,9 +220,9 @@ public class WxPayController {
*/
private void handleRefundResult(RefundNotification notification, WechatConfig config) {
try {
log.info("处理退款结果,退款单号:{}, 商户退款单号:{}",
log.info("处理退款结果,退款单号:{}, 商户退款单号:{}",
notification.getRefundId(), notification.getOutRefundNo());
// 根据是否为服务商模式处理不同的逻辑
if (Boolean.TRUE.equals(config.getIsServiceMode())) {
// 服务商模式:处理子商户退款
@@ -263,7 +242,7 @@ public class WxPayController {
private void handleSubMerchantRefundResult(RefundNotification notification, WechatConfig config) {
// TODO: 实现服务商模式下的退款结果处理逻辑
log.info("处理服务商模式退款结果,子商户号:{}", config.getSubMchId());
// 1. 更新退款状态
// 2. 处理相关业务逻辑
}
@@ -272,214 +251,31 @@ public class WxPayController {
* 处理普通商户模式下的退款结果
*/
private void handleMerchantRefundResult(RefundNotification notification, WechatConfig config) {
// TODO: 实现普通商户模式下的退款结果处理逻辑
log.info("处理普通商户模式退款结果,商户号:{}", config.getMerchantId());
// 1. 更新退款状态
// 2. 处理相关业务逻辑
}
/**
* 构建请求参数
*/
private RequestParam buildRequestParam(Map<String, String> headers, String body) {
return new RequestParam.Builder()
.serialNumber(headers.get("Wechatpay-Serial"))
.nonce(headers.get("Wechatpay-Nonce"))
.signature(headers.get("Wechatpay-Signature"))
.timestamp(headers.get("Wechatpay-Timestamp"))
.body(body)
.build();
}
// 获取退款通知中的关键信息
String outRefundNo = notification.getOutRefundNo();
/**
* 解析通知数据
*/
private ProfitSharingNotification parseNotification(RequestParam requestParam) {
try {
NotificationParser parser = wxPayConfigFactory.createNotificationParser(defaultTenantId);
// 解析为Map后转换为ProfitSharingNotification对象
Map<String, Object> result = parser.parse(requestParam, Map.class);
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);
ProfitSharingNotification notification = new ProfitSharingNotification();
notification.setMchid((String) result.get("mchid"));
notification.setTransactionId((String) result.get("transaction_id"));
notification.setOutOrderNo((String) result.get("out_order_no"));
notification.setState((String) result.get("state"));
notification.setFailReason((String) result.get("fail_reason"));
// 处理接收方列表
if (result.containsKey("receivers")) {
List<Map<String, Object>> receiversMap = (List<Map<String, Object>>) result.get("receivers");
List<ProfitSharingNotification.Receiver> receivers = new ArrayList<>();
for (Map<String, Object> receiverMap : receiversMap) {
ProfitSharingNotification.Receiver receiver = new ProfitSharingNotification.Receiver();
receiver.setType((String) receiverMap.get("type"));
receiver.setAccount((String) receiverMap.get("account"));
receiver.setAmount(Long.valueOf(receiverMap.get("amount").toString()));
receiver.setDescription((String) receiverMap.get("description"));
receiver.setResult((String) receiverMap.get("result"));
receiver.setFailReason((String) receiverMap.get("fail_reason"));
receiver.setDetailId((String) receiverMap.get("detail_id"));
receivers.add(receiver);
}
notification.setReceivers(receivers);
}
return notification;
} catch (Exception e) {
log.error("解析分账回调通知失败", e);
throw new RuntimeException("解析分账回调通知失败", e);
}
}
/**
* 优化后的分账回调处理方法
*/
@PostMapping("/profitsharing/notify")
public String handleProfitSharingNotify(@RequestHeader Map<String, String> headers,
@RequestBody String body) {
log.info("收到分账回调通知: headers={}, body={}", headers, body);
try {
// 1. 验证通知签名
RequestParam requestParam = buildRequestParam(headers, body);
// 2. 解析通知数据
ProfitSharingNotification notification = parseNotification(requestParam);
// 3. 处理分账结果
handleProfitSharingNotification(notification);
// 4. 返回成功响应
return buildSuccessResponse();
} catch (Exception e) {
log.error("处理分账回调失败", e);
return buildErrorResponse();
}
}
private void handleProfitSharingNotification(ProfitSharingNotification notification) {
String orderNo = notification.getOutOrderNo();
String state = notification.getState();
try {
// 1. 获取分账记录
ProfitSharing profitSharing = profitSharingService.getByOrderNo(orderNo);
if (profitSharing == null) {
log.error("分账记录不存在: {}", orderNo);
return;
}
// 2. 根据状态处理
switch (state) {
case "FINISHED":
// 分账成功
handleProfitSharingSuccess(profitSharing, notification);
break;
case "FAILED":
// 分账失败
handleProfitSharingFailure(profitSharing, notification);
break;
default:
log.warn("未知的分账状态: orderNo={}, state={}", orderNo, state);
}
} catch (Exception e) {
log.error("处理分账回调异常: orderNo={}", orderNo, e);
// 确保更新状态
profitSharingService.updateProfitSharingStatus(
orderNo,
ProfitSharingConstants.Status.FAILED
);
}
}
/**
* 处理分账成功
*/
private void handleProfitSharingSuccess(ProfitSharing profitSharing,
ProfitSharingNotification notification) {
// 1. 更新分账状态
profitSharing.setStatus(ProfitSharingConstants.Status.SUCCESS);
profitSharing.setFinishTime(new Date());
// 2. 如果有接收方信息,更新接收方结果
if (notification.getReceivers() != null && !notification.getReceivers().isEmpty()) {
ProfitSharingNotification.Receiver receiver = notification.getReceivers().get(0);
profitSharing.setReceiverAmount(receiver.getAmount());
profitSharing.setProfitSharingId(receiver.getDetailId());
}
// 3. 保存更新
profitSharingService.updateById(profitSharing);
log.info("分账成功: orderNo={}", profitSharing.getOrderNo());
}
/**
* 处理分账失败
*/
private void handleProfitSharingFailure(ProfitSharing profitSharing,
ProfitSharingNotification notification) {
// 1. 更新分账状态和失败原因
profitSharing.setStatus(ProfitSharingConstants.Status.FAILED);
profitSharing.setFailReason(notification.getFailReason());
profitSharing.setUpdateTime(new Date());
// 2. 判断是否需要重试
if (profitSharing.canRetry()) {
log.info("准备重试分账: orderNo={}, retryTimes={}",
profitSharing.getOrderNo(), profitSharing.getRetryTimes());
// 更新重试信息
profitSharing.setRetryTimes(profitSharing.getRetryTimes() + 1);
profitSharing.setLastRetryTime(new Date());
profitSharingService.updateById(profitSharing);
// 发起重试
profitSharingService.retryFailedProfitSharing(profitSharing.getOrderNo());
Order order = orderService.getOrderByNumber(refund.getOrderNo());
Assert.notNull(order,"订单数据不存在");
order.setOrderStatus(OrderStatus.REFUNDED.getId());
orderService.updateOrder(order);
} else if ("CLOSED".equals(notification.getRefundStatus())) {
// 退款关闭,处理退款关闭逻辑
} else {
log.warn("分账失败且不再重试: orderNo={}, retryTimes={}",
profitSharing.getOrderNo(), profitSharing.getRetryTimes());
// 发送告警
sendFailureAlert(profitSharing);
// 保存最终状态
profitSharingService.updateById(profitSharing);
}
}
/**
* 发送失败告警
*/
private void sendFailureAlert(ProfitSharing profitSharing) {
try {
String alertMessage = String.format(
"分账失败告警\n" +
"订单号:%s\n" +
"交易号:%s\n" +
"失败原因:%s\n" +
"重试次数:%d\n" +
"分账金额:%d分\n" +
"失败时间:%s",
profitSharing.getOrderNo(),
profitSharing.getTransactionId(),
profitSharing.getFailReason(),
profitSharing.getRetryTimes(),
profitSharing.getQrCodeAmount(),
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())
);
log.error(alertMessage);
// TODO: 实现具体的告警通知逻辑,如发送邮件、钉钉消息等
} catch (Exception e) {
log.error("发送分账失败告警异常", e);
// 其他退款状态,如退款中、失败等
}
}
@@ -490,28 +286,5 @@ public class WxPayController {
private String buildErrorResponse() {
return "{\"code\":\"FAIL\",\"message\":\"失败\"}";
}
}
/**
* 分账通知解析实体类
*/
@Data
class ProfitSharingNotification {
private String mchid; // 商户号
private String transactionId; // 微信订单号
private String outOrderNo; // 商户分账单号
private String state; // 分账状态
private String failReason; // 失败原因
private List<Receiver> receivers; // 分账接收方列表
@Data
public static class Receiver {
private String type; // 分账接收方类型
private String account; // 分账接收方账号
private Long amount; // 分账金额
private String description; // 分账描述
private String result; // 分账结果
private String failReason; // 分账失败原因
private String detailId; // 分账明细单号
}
}