fix(分润支付):新增分润支付后端逻辑

This commit is contained in:
2025-04-15 10:29:39 +08:00
parent 981699d9d0
commit 10b35d21f9
16 changed files with 1623 additions and 34 deletions
@@ -0,0 +1,58 @@
package com.central.order.config;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ConfigurationProperties(prefix = "wechat.pay.profit-sharing")
@Component
public class ProfitSharingProperties {
/**
* 是否启用分账功能
*/
@Builder.Default
private boolean enabled = true;
/**
* 最大重试次数
*/
@Builder.Default
private int maxRetryTimes = 3;
/**
* 重试间隔(毫秒)
*/
@Builder.Default
private long retryInterval = 300000; // 5分钟
/**
* 平台分账比例(%)
*/
@Builder.Default
private String platformRate = "30";
/**
* 分账超时时间(毫秒)
*/
@Builder.Default
private long timeout = 1800000; // 30分钟
/**
* 是否启用异步处理
*/
@Builder.Default
private boolean asyncEnabled = true;
/**
* 异步处理线程池大小
*/
@Builder.Default
private int asyncPoolSize = 5;
}
@@ -3,13 +3,23 @@ package com.central.order.config;
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 lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
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 org.springframework.beans.factory.annotation.Qualifier;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 支付配置类
@@ -22,6 +32,7 @@ import org.springframework.context.annotation.Configuration;
@Setter
@Configuration
@ConfigurationProperties(prefix = "tencent")
@EnableConfigurationProperties(ProfitSharingProperties.class)
public class TencentPayConfiguration {
private String merchantId;
@@ -90,4 +101,45 @@ public class TencentPayConfiguration {
tencentPayProperties.setNotifyUrl(notifyUrl);
return tencentPayProperties;
}
@Value("${wechat.pay.profit-sharing.enabled:true}")
private boolean profitSharingEnabled;
@Bean
public SettleInfo defaultSettleInfo() {
SettleInfo settleInfo = new SettleInfo();
settleInfo.setProfitSharing(profitSharingEnabled);
return settleInfo;
}
@Bean
public NotificationParser notificationParser(NotificationConfig config) {
return new NotificationParser(config);
}
@Bean
public ProfitsharingService profitsharingService() {
// 使用已有的配置方法
Config config = getConfig();
return new ProfitsharingService.Builder()
.config(config)
.build();
}
@Bean
public Executor profitSharingExecutor(@Qualifier("wechat.pay.profit-sharing-com.central.order.config.ProfitSharingProperties")
ProfitSharingProperties properties) {
if (!properties.isAsyncEnabled()) {
return null;
}
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(properties.getAsyncPoolSize());
executor.setMaxPoolSize(properties.getAsyncPoolSize());
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("profit-sharing-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}
@@ -0,0 +1,16 @@
package com.central.order.constants;
public interface ProfitSharingConstants {
String PROFIT_SHARING_PREFIX = "PS";
String PROFIT_SHARING_DESC = "二维码分账";
int MAX_RETRY_TIMES = 3;
long RETRY_INTERVAL = 300000; // 5分钟
interface Status {
int INIT = 0;
int PROCESSING = 1;
int SUCCESS = 2;
int FAILED = 3;
}
}
@@ -18,10 +18,7 @@ import com.central.order.feign.UserCenterService;
import com.central.order.model.*;
import com.central.order.service.*;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
@@ -97,7 +94,11 @@ public class OrderController {
@Autowired
private DeviceCenterService deviceCenterService;
@Autowired
private IProfitSharingService profitSharingService;
@Autowired
private SettleInfo defaultSettleInfo; // 注入配置的SettleInfo
/**
* 列表
@@ -234,31 +235,49 @@ public class OrderController {
@Operation(summary = "生成预支付订单")
@PutMapping("/{orderId}/pay")
public Result<PrepayWithRequestPaymentResponse> payOrder(@PathVariable("orderId") Long orderId) {
try {
// 1. 获取用户和订单信息
SysUser user = userCenterService.findUserById(LoginUserContextHolder.getUser().getId());
Order order = orderService.getById(orderId);
if (order == null) {
return Result.failed("订单数据不存在");
}
SysUser user = userCenterService.findUserById(LoginUserContextHolder.getUser().getId());
Order order = orderService.getById(orderId);
if (order == null) {
return Result.failed("订单数据不存在");
// 3. 创建支付请求
PrepayRequest request = new PrepayRequest();
// 设置基本支付信息
Amount amount = new Amount();
amount.setTotal(Integer.parseInt(order.getOrderAmount()));
request.setAmount(amount);
request.setAppid(tencentPayProperties.getAppId());
request.setMchid(tencentPayProperties.getMerchantId());
request.setDescription(order.getOrderNo());
request.setNotifyUrl(tencentPayProperties.getNotifyUrl());
request.setOutTradeNo(order.getOrderNo());
// 设置支付者信息
Payer payer = new Payer();
payer.setOpenid(user.getOpenId());
request.setPayer(payer);
// 设置分账信息
SettleInfo settleInfo = new SettleInfo();
settleInfo.setProfitSharing(true); // 直接设置分账标识为true
request.setSettleInfo(settleInfo);
// 4. 创建分账记录
ProfitSharing profitSharing = profitSharingService.createProfitSharing(order);
// 5. 调用支付接口
PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request);
// 6. 返回结果
return Result.succeed(response, order.getOrderNo());
} catch (Exception e) {
log.error("创建预支付订单失败", e);
return Result.failed("创建预支付订单失败:" + e.getMessage());
}
// request.setXxx(val)设置所需参数,具体参数可见Request定义
PrepayRequest request = new PrepayRequest();
Amount amount = new Amount();
amount.setTotal(Integer.parseInt(order.getOrderAmount()));
request.setAmount(amount);
request.setAppid(tencentPayProperties.getAppId());
request.setMchid(tencentPayProperties.getMerchantId());
request.setDescription(order.getOrderNo());
request.setNotifyUrl(tencentPayProperties.getNotifyUrl());
request.setOutTradeNo(order.getOrderNo());
Payer payer = new Payer();
payer.setOpenid(user.getOpenId());
request.setPayer(payer);
// 调用下单方法,得到应答
// response包含了调起支付所需的所有参数,可直接用于前端调起支付
PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request);
return Result.succeed(response, order.getOrderNo());
}
@Operation(summary = "获取排队总览信息")
@@ -0,0 +1,48 @@
package com.central.order.controller;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.order.model.ProfitSharing;
import com.central.order.service.IProfitSharingService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/profitSharing")
@Tag(name = "分账管理")
@RequiredArgsConstructor
public class ProfitSharingController {
private final IProfitSharingService profitSharingService;
@Operation(summary = "分页查询分账记录")
@GetMapping("/list")
public PageResult<ProfitSharing> list(@RequestParam Map<String, Object> params) {
return profitSharingService.findList(params);
}
@Operation(summary = "获取分账记录详情")
@GetMapping("/{orderNo}")
public Result<ProfitSharing> detail(@PathVariable String orderNo) {
ProfitSharing profitSharing = profitSharingService.getByOrderNo(orderNo);
return Result.succeed(profitSharing);
}
@Operation(summary = "手动触发分账")
@PostMapping("/execute/{orderNo}")
public Result<String> executeProfitSharing(@PathVariable String orderNo) {
try {
profitSharingService.executeProfitSharing(orderNo);
return Result.succeed("分账执行成功");
} catch (Exception e) {
log.error("手动触发分账失败", e);
return Result.failed("分账执行失败:" + e.getMessage());
}
}
}
@@ -1,9 +1,12 @@
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.service.IOrderService;
import com.central.order.service.IProfitSharingService;
import com.central.order.service.IRefundService;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
@@ -12,13 +15,18 @@ 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.util.Assert;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Slf4j
@RestController
@@ -33,6 +41,9 @@ public class WxPayController {
@Autowired
private NotificationConfig config;
@Autowired
private IProfitSharingService profitSharingService;
/**
* 支付回调
*
@@ -78,15 +89,26 @@ public class WxPayController {
String outTradeNo = transaction.getOutTradeNo();
String tradeState = transaction.getTradeState().toString();
// 根据支付状态进行相应处理
// 2. 根据支付状态进行相应处理
if ("SUCCESS".equals(tradeState)) {
// 支付成功,更新订单状态等操作
System.out.println("支付成功,商户订单号:" + outTradeNo);
// 3. 更新订单状态
Order order = orderService.getOrderByNumber(transaction.getOutTradeNo());
order.setOrderStatus(OrderStatus.PAID.getId());
order.setPayTime(new Date());
orderService.updateOrder(order);
// 这里可以添加更新数据库订单状态的代码
// 4. 更新分账记录
profitSharingService.updateTransactionId(
transaction.getOutTradeNo(),
transaction.getTransactionId()
);
// 5. 发起分账请求
profitSharingService.executeProfitSharing(transaction.getOutTradeNo());
} else {
// 其他支付状态,如支付中、失败等
System.out.println("支付状态:" + tradeState + ",商户订单号:" + outTradeNo);
@@ -129,6 +151,182 @@ public class WxPayController {
}
}
/**
* 构建请求参数
*/
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();
}
/**
* 解析通知数据
*/
private ProfitSharingNotification parseNotification(RequestParam requestParam) {
try {
NotificationParser parser = new NotificationParser(config);
// 解析为Map后转换为ProfitSharingNotification对象
Map<String, Object> result = parser.parse(requestParam, Map.class);
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);
}
}
/**
* 处理分账失败
*/
private void handleProfitSharingFailure(String orderNo, String failReason) {
try {
log.error("分账失败: orderNo={}, reason={}", orderNo, failReason);
// 1. 更新分账状态为失败
profitSharingService.updateProfitSharingStatus(
orderNo,
ProfitSharingConstants.Status.FAILED
);
// 2. 获取分账记录
ProfitSharing profitSharing = profitSharingService.getByOrderNo(orderNo);
if (profitSharing == null) {
log.error("分账记录不存在: {}", orderNo);
return;
}
// 3. 更新失败原因
profitSharing.setFailReason(failReason);
profitSharing.setUpdateTime(new Date());
// 4. 判断是否需要重试
if (profitSharing.canRetry()) {
log.info("准备重试分账: orderNo={}, retryTimes={}",
orderNo, profitSharing.getRetryTimes());
profitSharingService.retryFailedProfitSharing(orderNo);
} else {
log.warn("分账失败且不再重试: orderNo={}, retryTimes={}",
orderNo, profitSharing.getRetryTimes());
// 可以在这里添加告警通知
sendFailureAlert(profitSharing);
}
} catch (Exception e) {
log.error("处理分账失败异常", e);
// 确保状态更新为失败
profitSharingService.updateProfitSharingStatus(
orderNo,
ProfitSharingConstants.Status.FAILED
);
}
}
/**
* 发送失败告警
*/
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);
}
}
/**
* 优化后的分账回调处理方法
*/
@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();
switch (state) {
case "FINISHED":
profitSharingService.updateProfitSharingStatus(
orderNo,
ProfitSharingConstants.Status.SUCCESS
);
break;
case "FAILED":
handleProfitSharingFailure(orderNo, notification.getFailReason());
break;
default:
log.warn("未知的分账状态: {}", state);
}
}
/**
* 退款订单结果处理逻辑
* @param notification
@@ -167,3 +365,27 @@ public class WxPayController {
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; // 分账明细单号
}
}
@@ -0,0 +1,26 @@
package com.central.order.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum PayeeTypeEnum {
MERCHANT_ID("MERCHANT_ID", "商户ID"),
PERSONAL_OPENID("PERSONAL_OPENID", "个人openid");
private final String code;
private final String desc;
public static String getDesc(String code) {
if (code == null) {
return "";
}
for (PayeeTypeEnum type : values()) {
if (type.getCode().equals(code)) {
return type.getDesc();
}
}
return "未知类型";
}
}
@@ -0,0 +1,28 @@
package com.central.order.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum ProfitSharingStatusEnum {
INIT(0, "待分账"),
PROCESSING(1, "分账中"),
SUCCESS(2, "分账成功"),
FAILED(3, "分账失败");
private final int code;
private final String desc;
public static String getDesc(Integer code) {
if (code == null) {
return "";
}
for (ProfitSharingStatusEnum status : values()) {
if (status.getCode() == code) {
return status.getDesc();
}
}
return "未知状态";
}
}
@@ -0,0 +1,9 @@
package com.central.order.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.order.model.ProfitSharing;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ProfitSharingMapper extends BaseMapper<ProfitSharing> {
}
@@ -0,0 +1,163 @@
package com.central.order.model;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableField;
import com.central.order.enums.PayeeTypeEnum;
import com.central.order.enums.ProfitSharingStatusEnum;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.Date;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@TableName("profit_sharing")
@Schema(description = "分账记录")
public class ProfitSharing {
@TableId
@Schema(description = "主键ID")
private Long id;
@NotNull(message = "订单ID不能为空")
@Length(max = 64, message = "订单ID长度不能超过64")
@Schema(description = "订单ID")
private String orderId;
@NotNull(message = "订单编号不能为空")
@Length(max = 64, message = "订单编号长度不能超过64")
@Schema(description = "订单编号")
private String orderNo;
@Length(max = 64, message = "微信支付订单号长度不能超过64")
@Schema(description = "微信支付订单号")
private String transactionId;
@Length(max = 64, message = "微信分账单号长度不能超过64")
@Schema(description = "微信分账单号")
@TableField("profit_sharing_id")
private String profitSharingId;
@NotNull(message = "订单总金额不能为空")
@Min(value = 1, message = "订单总金额必须大于0")
@Schema(description = "订单总金额(分)")
private Long totalAmount;
@NotNull(message = "平台分账金额不能为空")
@Min(value = 0, message = "平台分账金额不能小于0")
@Schema(description = "平台分账金额(分)")
private Long platformAmount;
@NotNull(message = "二维码分账金额不能为空")
@Min(value = 1, message = "二维码分账金额必须大于0")
@Schema(description = "二维码分账金额(分)")
@TableField("qrcode_amount")
private Long qrCodeAmount;
@Schema(description = "分账状态:0-待分账 1-分账中 2-分账成功 3-分账失败")
private Integer status;
@NotNull(message = "二维码ID不能为空")
@Schema(description = "二维码ID")
private String codeId;
@NotNull(message = "分账接收账号不能为空")
@Schema(description = "分账接收账号")
@TableField("payee_account")
private String payeeAccount;
@NotNull(message = "分账账号类型不能为空")
@Schema(description = "分账账号类型:MERCHANT_ID-商户ID,PERSONAL_OPENID-个人openid")
@TableField("payee_type")
private String payeeType;
@Length(max = 256, message = "分账描述长度不能超过256")
@Schema(description = "分账描述")
@TableField("description")
private String description;
@Length(max = 256, message = "分账失败原因长度不能超过256")
@Schema(description = "分账失败原因")
@TableField("fail_reason")
private String failReason;
@Schema(description = "实际分账金额(分)")
@TableField("receiver_amount")
private Long receiverAmount;
@Schema(description = "分账完成时间")
@TableField("finish_time")
private Date finishTime;
@Length(max = 64, message = "分账请求号长度不能超过64")
@Schema(description = "分账请求号")
@TableField("out_order_no")
private String outOrderNo;
@Schema(description = "重试次数")
@TableField("retry_times")
private Integer retryTimes;
@Schema(description = "最后重试时间")
@TableField("last_retry_time")
private Date lastRetryTime;
@Schema(description = "创建时间")
private Date createTime;
@Schema(description = "更新时间")
private Date updateTime;
/**
* 获取状态描述
*/
public String getStatusDesc() {
return ProfitSharingStatusEnum.getDesc(status);
}
/**
* 获取分账账号类型描述
*/
public String getPayeeTypeDesc() {
return PayeeTypeEnum.getDesc(payeeType);
}
/**
* 判断是否可以重试
* 条件:
* 1. 状态为失败
* 2. 重试次数小于3次
* 3. 距离上次重试时间超过5分钟
*/
public boolean canRetry() {
return status == ProfitSharingStatusEnum.FAILED.getCode()
&& (retryTimes == null || retryTimes < 3)
&& (lastRetryTime == null || System.currentTimeMillis() - lastRetryTime.getTime() > 300000);
}
/**
* 更新重试信息
*/
public void updateRetryInfo() {
this.retryTimes = (this.retryTimes == null ? 0 : this.retryTimes) + 1;
this.lastRetryTime = new Date();
}
/**
* 检查金额是否合法
*/
public boolean isAmountValid() {
return totalAmount != null && totalAmount > 0
&& platformAmount != null && platformAmount >= 0
&& qrCodeAmount != null && qrCodeAmount > 0
&& (platformAmount + qrCodeAmount == totalAmount);
}
}
@@ -0,0 +1,104 @@
package com.central.order.model;
import com.central.order.enums.ProfitSharingStatusEnum;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "分账结果")
public class ProfitSharingResult {
@Schema(description = "订单号")
private String orderNo;
@Schema(description = "微信支付订单号")
private String transactionId;
@Schema(description = "分账单号")
private String profitSharingId;
@Schema(description = "分账状态")
private Integer status;
@Schema(description = "分账状态描述")
private String statusDesc;
@Schema(description = "分账总金额(分)")
private Long totalAmount;
@Schema(description = "实际分账金额(分)")
private Long receiverAmount;
@Schema(description = "分账完成时间")
private Date finishTime;
@Schema(description = "失败原因")
private String failReason;
@Schema(description = "分账接收方列表")
private List<ReceiverResult> receivers;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class ReceiverResult {
@Schema(description = "接收方类型")
private String type;
@Schema(description = "接收方账号")
private String account;
@Schema(description = "分账金额(分)")
private Long amount;
@Schema(description = "分账描述")
private String description;
@Schema(description = "分账结果")
private String result;
@Schema(description = "失败原因")
private String failReason;
@Schema(description = "分账明细单号")
private String detailId;
}
/**
* 获取状态描述
*/
public String getStatusDesc() {
return ProfitSharingStatusEnum.getDesc(status);
}
/**
* 判断分账是否成功
*/
public boolean isSuccess() {
return ProfitSharingStatusEnum.SUCCESS.getCode() == status;
}
/**
* 判断分账是否失败
*/
public boolean isFailed() {
return ProfitSharingStatusEnum.FAILED.getCode() == status;
}
/**
* 判断分账是否处理中
*/
public boolean isProcessing() {
return ProfitSharingStatusEnum.PROCESSING.getCode() == status;
}
}
@@ -4,10 +4,10 @@ import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.central.common.model.SuperEntity;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;
import java.math.BigDecimal;
import java.util.Date;
/**
@@ -16,8 +16,10 @@ import java.util.Date;
* @author lsl
* @date 2024-12-19 17:51:47
*/
@Getter
@Setter
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
@TableName("qrcodes")
public class QrCode extends SuperEntity {
@@ -26,7 +28,7 @@ public class QrCode extends SuperEntity {
private String codeId;
private Long tourismId;
// 新增二维码名称字段
private String name;
@@ -51,4 +53,31 @@ public class QrCode extends SuperEntity {
private Long tenantId;
private String company;
private Integer isDel;
/**
* 分账接收账号
*/
private String payeeAccount;
/**
* 分账比例(百分比,例如:30.00 表示 30%)
*/
private BigDecimal profitRate;
/**
* 分账账号类型(MERCHANT_ID:商户ID,PERSONAL_OPENID:个人openid)
*/
private String payeeType;
/**
* 分账账号状态(0:未验证,1:已验证,2:验证失败)
*/
private Integer payeeStatus;
@Schema(description = "分账失败原因")
private String payeeFailReason;
}
@@ -0,0 +1,57 @@
package com.central.order.service;
import com.central.common.model.PageResult;
import com.central.common.service.ISuperService;
import com.central.order.model.Order;
import com.central.order.model.ProfitSharing;
import com.central.order.model.ProfitSharingResult;
import com.central.order.model.QrCode;
import java.util.Map;
public interface IProfitSharingService extends ISuperService<ProfitSharing> {
/**
* 创建分账记录
*/
ProfitSharing createProfitSharing(Order order);
/**
* 更新微信支付订单号
*/
void updateTransactionId(String orderNo, String transactionId);
/**
* 执行分账
*/
void executeProfitSharing(String orderNo);
/**
* 获取分账记录
*/
ProfitSharing getByOrderNo(String orderNo);
/**
* 更新分账状态
*/
void updateProfitSharingStatus(String orderNo, Integer status);
/**
* 分页查询分账记录
*/
PageResult<ProfitSharing> findList(Map<String, Object> params);
/**
* 重试失败的分账
*/
void retryFailedProfitSharing(String orderNo);
/**
* 验证并添加接收者
*/
boolean validateAndAddReceiver(QrCode qrCode);
/**
* 查询分账状态
*/
ProfitSharingResult queryProfitSharingStatus(String orderNo);
}
@@ -0,0 +1,696 @@
package com.central.order.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.exception.BusinessException;
import com.central.common.model.PageResult;
import com.central.common.service.impl.SuperServiceImpl;
import com.central.order.config.ProfitSharingProperties;
import com.central.order.config.TencentPayProperties;
import com.central.order.constants.ProfitSharingConstants;
import com.central.order.enums.ProfitSharingStatusEnum;
import com.central.order.mapper.ProfitSharingMapper;
import com.central.order.model.Order;
import com.central.order.model.ProfitSharing;
import com.central.order.model.ProfitSharingResult;
import com.central.order.model.QrCode;
import com.central.order.service.IProfitSharingService;
import com.central.order.service.IQrCodeService;
import com.wechat.pay.java.service.profitsharing.ProfitsharingService;
import com.wechat.pay.java.service.profitsharing.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;
@Slf4j
@Service
public class ProfitSharingServiceImpl extends SuperServiceImpl<ProfitSharingMapper, ProfitSharing> implements IProfitSharingService {
@Autowired
private TencentPayProperties tencentPayProperties;
@Autowired
private ProfitsharingService profitsharingService;
@Autowired
private IQrCodeService qrCodeService;
@Autowired
private ProfitSharingProperties profitSharingProperties;
@Autowired(required = false)
private Executor profitSharingExecutor;
@Value("${wechat.pay.platform-rate:0.30}")
private String platformRate;
@Override
@Transactional(rollbackFor = Exception.class)
public ProfitSharing createProfitSharing(Order order) {
try {
// 1. 参数校验
if (order == null || order.getCodeId() == null) {
throw new IllegalArgumentException("订单或二维码ID不能为空");
}
// 2. 获取二维码信息
QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId());
if (qrCode == null) {
throw new IllegalArgumentException("二维码信息不存在");
}
// 3. 验证分账账号
validatePayeeAccount(qrCode);
// 4. 计算分账金额
long totalAmount = Long.parseLong(order.getOrderAmount());
if (totalAmount <= 0) {
throw new IllegalArgumentException("订单金额必须大于0");
}
// 使用二维码的分账比例计算
long qrCodeAmount = calculateQrCodeAmount(totalAmount, qrCode.getProfitRate());
long platformAmount = totalAmount - qrCodeAmount;
// 5. 创建分账记录
ProfitSharing profitSharing = ProfitSharing.builder()
.orderId(order.getId().toString())
.orderNo(order.getOrderNo())
.totalAmount(totalAmount)
.platformAmount(platformAmount)
.qrCodeAmount(qrCodeAmount)
.payeeAccount(qrCode.getPayeeAccount())
.payeeType(qrCode.getPayeeType())
.codeId(qrCode.getCodeId())
.status(0)
.createTime(new Date())
.updateTime(new Date())
.build();
// 6. 保存记录
save(profitSharing);
log.info("创建分账记录成功: {}", profitSharing);
return profitSharing;
} catch (Exception e) {
log.error("创建分账记录失败: orderId={}, codeId={}", order.getId(), order.getCodeId(), e);
throw new RuntimeException("创建分账记录失败", e);
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateTransactionId(String orderNo, String transactionId) {
ProfitSharing profitSharing = getByOrderNo(orderNo);
if (profitSharing != null) {
profitSharing.setTransactionId(transactionId);
profitSharing.setUpdateTime(new Date());
updateById(profitSharing);
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void executeProfitSharing(String orderNo) {
try {
// 1. 获取并验证分账记录
ProfitSharing profitSharing = validateProfitSharingRecord(orderNo);
// 2. 检查状态和重试次数
if (!canExecuteProfitSharing(profitSharing)) {
return;
}
// 3. 更新状态为处理中
updateProfitSharingStatus(orderNo, ProfitSharingConstants.Status.PROCESSING);
// 4. 构建并执行分账请求
OrdersEntity response = executeProfitSharingRequest(profitSharing);
// 5. 处理响应
handleProfitSharingResponse(orderNo, response);
} catch (Exception e) {
handleProfitSharingError(orderNo, e);
}
}
private ProfitSharing validateProfitSharingRecord(String orderNo) {
ProfitSharing profitSharing = getByOrderNo(orderNo);
if (profitSharing == null) {
throw new BusinessException("分账记录不存在");
}
if (StringUtils.isEmpty(profitSharing.getTransactionId())) {
throw new BusinessException("支付交易号不存在");
}
return profitSharing;
}
private boolean canExecuteProfitSharing(ProfitSharing profitSharing) {
if (profitSharing.getStatus() == ProfitSharingConstants.Status.SUCCESS) {
log.info("分账已成功完成: {}", profitSharing.getOrderNo());
return false;
}
if (profitSharing.getRetryTimes() >= profitSharingProperties.getMaxRetryTimes()) {
log.warn("分账重试次数超限: {}", profitSharing.getOrderNo());
return false;
}
return true;
}
private OrdersEntity executeProfitSharingRequest(ProfitSharing profitSharing) {
CreateOrderRequest request = buildProfitSharingRequest(profitSharing);
try {
return profitsharingService.createOrder(request);
} catch (Exception e) {
log.error("调用微信分账接口失败", e);
throw new BusinessException("分账请求失败");
}
}
@Async
public void retryFailedProfitSharing(String orderNo) {
ProfitSharing profitSharing = getByOrderNo(orderNo);
if (profitSharing == null || !canRetry(profitSharing)) {
return;
}
try {
// 更新重试信息
updateRetryInfo(profitSharing);
// 执行分账
executeProfitSharing(orderNo);
} catch (Exception e) {
log.error("重试分账失败: orderNo={}", orderNo, e);
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean validateAndAddReceiver(QrCode qrCode) {
try {
// 1. 参数校验
if (qrCode == null) {
log.error("二维码信息为空");
return false;
}
if (StringUtils.isEmpty(qrCode.getPayeeAccount())) {
log.error("分账接收方账号为空: codeId={}", qrCode.getCodeId());
return false;
}
if (StringUtils.isEmpty(qrCode.getPayeeType())) {
log.error("分账接收方类型为空: codeId={}", qrCode.getCodeId());
return false;
}
// 2. 构建添加接收方请求
AddReceiverRequest request = new AddReceiverRequest();
request.setAppid(tencentPayProperties.getAppId());
// 设置接收方类型
try {
request.setType(ReceiverType.valueOf(qrCode.getPayeeType()));
} catch (IllegalArgumentException e) {
log.error("无效的接收方类型: type={}", qrCode.getPayeeType());
updateReceiverStatus(qrCode, 2, "无效的接收方类型");
return false;
}
// 设置接收方账号和名称
request.setAccount(qrCode.getPayeeAccount());
request.setName(qrCode.getName());
request.setRelationType(ReceiverRelationType.CUSTOM);
// 3. 调用微信接口添加接收方
try {
AddReceiverResponse response = profitsharingService.addReceiver(request);
// 4. 处理响应结果
if (response != null && response.getAccount() != null) {
// 更新接收方状态为验证成功
updateReceiverStatus(qrCode, 1, null);
log.info("添加分账接收方成功: account={}", qrCode.getPayeeAccount());
return true;
} else {
log.error("添加分账接收方失败: response={}", response);
updateReceiverStatus(qrCode, 2, "接口返回为空");
return false;
}
} catch (Exception e) {
String errorMsg = getErrorMessage(e);
log.error("添加分账接收方异常: account={}, error={}", qrCode.getPayeeAccount(), errorMsg);
updateReceiverStatus(qrCode, 2, errorMsg);
return false;
}
} catch (Exception e) {
log.error("验证并添加分账接收方失败", e);
updateReceiverStatus(qrCode, 2, "系统异常");
return false;
}
}
/**
* 更新接收方状态
*/
private void updateReceiverStatus(QrCode qrCode, Integer status, String failReason) {
try {
qrCode.setPayeeStatus(status);
if (failReason != null) {
// 假设QrCode类中有payeeFailReason字段
qrCode.setPayeeFailReason(failReason);
}
qrCode.setUpdateTime(new Date());
qrCodeService.updateById(qrCode);
} catch (Exception e) {
log.error("更新接收方状态失败: codeId={}, status={}", qrCode.getCodeId(), status, e);
}
}
/**
* 验证接收方类型是否合法
*/
private boolean isValidReceiverType(String type) {
try {
ReceiverType.valueOf(type);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
/**
* 获取格式化的错误信息
*/
private String getErrorMessage(Exception e) {
String message = e.getMessage();
if (message == null) {
return "未知错误";
}
// 移除敏感信息
message = message.replaceAll("\\{\"password\":\"[^\"]*\"\\}", "{\"password\":\"***\"}");
// 限制长度
return message.length() > 200 ? message.substring(0, 200) : message;
}
private boolean canRetry(ProfitSharing profitSharing) {
return profitSharing.getStatus() == ProfitSharingStatusEnum.FAILED.getCode()
&& (profitSharing.getRetryTimes() == null
|| profitSharing.getRetryTimes() < profitSharingProperties.getMaxRetryTimes())
&& (profitSharing.getLastRetryTime() == null
|| System.currentTimeMillis() - profitSharing.getLastRetryTime().getTime()
> profitSharingProperties.getRetryInterval());
}
private void updateRetryInfo(ProfitSharing profitSharing) {
profitSharing.setRetryTimes(
(profitSharing.getRetryTimes() == null ? 0 : profitSharing.getRetryTimes()) + 1
);
profitSharing.setLastRetryTime(new Date());
updateById(profitSharing);
}
/**
* 处理分账响应
* @param orderNo 订单号
* @param response 分账响应
*/
private void handleProfitSharingResponse(String orderNo, OrdersEntity response) {
try {
if (response == null) {
log.error("分账响应为空: orderNo={}", orderNo);
updateProfitSharingStatus(orderNo, 3);
throw new RuntimeException("分账响应为空");
}
OrderStatus state = response.getState();
ProfitSharing profitSharing = getByOrderNo(orderNo);
if (state == null) {
log.error("分账状态为空: orderNo={}", orderNo);
updateProfitSharingStatus(orderNo, 3);
throw new RuntimeException("分账状态为空");
}
switch (state) {
case PROCESSING:
// 处理中,更新状态并记录
log.info("分账处理中: orderNo={}", orderNo);
updateProfitSharingStatus(orderNo, 1);
// 可以考虑添加异步任务进行后续查询
break;
case FINISHED:
// 分账完成,更新状态和其他相关信息
log.info("分账成功: orderNo={}, response={}", orderNo, response);
profitSharing.setStatus(2);
profitSharing.setFinishTime(new Date());
profitSharing.setOrderId(response.getOrderId());
profitSharing.setUpdateTime(new Date());
updateById(profitSharing);
// 记录分账结果详情
recordProfitSharingResult(orderNo, response);
break;
default:
// 未知状态
log.error("未知的分账状态: orderNo={}, state={}", orderNo, state);
updateProfitSharingStatus(orderNo, 3);
throw new RuntimeException("未知的分账状态:" + state);
}
} catch (Exception e) {
log.error("处理分账响应失败: orderNo={}, response={}", orderNo, response, e);
updateProfitSharingStatus(orderNo, 3);
throw new RuntimeException("处理分账响应失败: " + e.getMessage(), e);
}
}
/**
* 记录分账结果详情
*/
private void recordProfitSharingResult(String orderNo, OrdersEntity response) {
try {
ProfitSharing profitSharing = getByOrderNo(orderNo);
if (profitSharing != null) {
// 更新分账接收方信息
List<OrderReceiverDetail> receivers = response.getReceivers();
if (receivers != null && !receivers.isEmpty()) {
OrderReceiverDetail receiver = receivers.get(0);
profitSharing.setReceiverAmount(receiver.getAmount());
profitSharing.setFinishTime(new Date());
profitSharing.setUpdateTime(new Date());
updateById(profitSharing);
}
}
} catch (Exception e) {
log.error("记录分账结果详情失败: orderNo={}", orderNo, e);
// 这里只记录日志,不抛出异常,避免影响主流程
}
}
@Override
public ProfitSharing getByOrderNo(String orderNo) {
return getOne(new LambdaQueryWrapper<ProfitSharing>()
.eq(ProfitSharing::getOrderNo, orderNo));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateProfitSharingStatus(String orderNo, Integer status) {
ProfitSharing profitSharing = getByOrderNo(orderNo);
if (profitSharing != null) {
profitSharing.setStatus(status);
profitSharing.setUpdateTime(new Date());
updateById(profitSharing);
}
}
@Override
public PageResult<ProfitSharing> findList(Map<String, Object> params) {
Page<ProfitSharing> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
LambdaQueryWrapper<ProfitSharing> wrapper = new LambdaQueryWrapper<>();
wrapper.orderByDesc(ProfitSharing::getCreateTime);
Page<ProfitSharing> result = baseMapper.selectPage(page, wrapper);
return PageResult.<ProfitSharing>builder().data(result.getRecords()).count(result.getTotal()).build();
}
private String generateProfitSharingNo() {
return "PS" + System.currentTimeMillis() + RandomStringUtils.randomNumeric(4);
}
private void validatePayeeAccount(QrCode qrCode) {
if (qrCode.getPayeeAccount() == null) {
throw new IllegalArgumentException("分账账号不能为空");
}
if (qrCode.getPayeeStatus() != 1) {
throw new IllegalArgumentException("分账账号未验证或验证失败");
}
}
private long calculateQrCodeAmount(long totalAmount, BigDecimal profitRate) {
try {
return profitRate.multiply(new BigDecimal(totalAmount))
.divide(new BigDecimal("100"), 0, RoundingMode.HALF_UP)
.longValue();
} catch (Exception e) {
log.error("计算分账金额失败: totalAmount={}, profitRate={}", totalAmount, profitRate, e);
throw new RuntimeException("计算分账金额失败", e);
}
}
// 查询分账结果
public OrdersEntity queryProfitSharingResult(String outOrderNo, String transactionId) {
try {
QueryOrderRequest request = new QueryOrderRequest();
request.setOutOrderNo(outOrderNo);
request.setTransactionId(transactionId);
return profitsharingService.queryOrder(request);
} catch (Exception e) {
log.error("查询分账结果失败: outOrderNo={}, transactionId={}", outOrderNo, transactionId, e);
throw new RuntimeException("查询分账结果失败", e);
}
}
@Override
public ProfitSharingResult queryProfitSharingStatus(String orderNo) {
try {
// 1. 获取分账记录
ProfitSharing profitSharing = getByOrderNo(orderNo);
if (profitSharing == null) {
throw new IllegalArgumentException("分账记录不存在: " + orderNo);
}
// 2. 如果分账已完成,直接返回结果
if (profitSharing.getStatus() == ProfitSharingStatusEnum.SUCCESS.getCode()) {
return buildProfitSharingResult(profitSharing, null);
}
// 3. 查询微信分账结果
OrdersEntity response = null;
if (profitSharing.getTransactionId() != null && profitSharing.getOutOrderNo() != null) {
QueryOrderRequest request = new QueryOrderRequest();
request.setOutOrderNo(profitSharing.getOutOrderNo());
request.setTransactionId(profitSharing.getTransactionId());
response = profitsharingService.queryOrder(request);
}
// 4. 构建返回结果
return buildProfitSharingResult(profitSharing, response);
} catch (Exception e) {
log.error("查询分账状态失败: orderNo={}", orderNo, e);
throw new RuntimeException("查询分账状态失败", e);
}
}
private ProfitSharingResult buildProfitSharingResult(ProfitSharing profitSharing, OrdersEntity response) {
ProfitSharingResult result = ProfitSharingResult.builder()
.orderNo(profitSharing.getOrderNo())
.transactionId(profitSharing.getTransactionId())
.profitSharingId(profitSharing.getProfitSharingId())
.status(profitSharing.getStatus())
.totalAmount(profitSharing.getTotalAmount())
.receiverAmount(profitSharing.getReceiverAmount())
.finishTime(profitSharing.getFinishTime())
.failReason(profitSharing.getFailReason())
.build();
// 如果有微信返回的分账结果,添加接收方详情
if (response != null && response.getReceivers() != null) {
List<ProfitSharingResult.ReceiverResult> receivers = response.getReceivers().stream()
.map(this::convertToReceiverResult)
.collect(Collectors.toList());
result.setReceivers(receivers);
}
return result;
}
private ProfitSharingResult.ReceiverResult convertToReceiverResult(OrderReceiverDetail detail) {
return ProfitSharingResult.ReceiverResult.builder()
.type(String.valueOf(detail.getType()))
.account(detail.getAccount())
.amount(detail.getAmount())
.description(detail.getDescription())
.result(detail.getResult().toString())
.failReason(detail.getFailReason().toString())
.detailId(detail.getDetailId())
.build();
}
private void handleProfitSharingError(String orderNo, Exception e) {
try {
log.error("分账执行失败: orderNo={}", orderNo, e);
// 1. 获取分账记录
ProfitSharing profitSharing = getByOrderNo(orderNo);
if (profitSharing == null) {
return;
}
// 2. 更新分账状态为失败
profitSharing.setStatus(ProfitSharingStatusEnum.FAILED.getCode());
profitSharing.setFailReason(getErrorMessage(e));
profitSharing.setUpdateTime(new Date());
// 3. 保存更新
updateById(profitSharing);
// 4. 如果开启了自动重试且满足重试条件,则添加重试任务
if (shouldRetry(profitSharing)) {
scheduleRetry(orderNo);
}
// 5. 发送告警通知(如果需要)
sendAlertNotification(profitSharing, e);
} catch (Exception ex) {
log.error("处理分账错误时发生异常", ex);
}
}
private boolean shouldRetry(ProfitSharing profitSharing) {
return profitSharingProperties.isEnabled()
&& profitSharing.canRetry()
&& !isSystemError(profitSharing.getFailReason());
}
private boolean isSystemError(String failReason) {
// 系统级错误不进行重试,例如:参数错误、签名错误等
if (failReason == null) {
return false;
}
return failReason.contains("PARAM_ERROR")
|| failReason.contains("SIGN_ERROR")
|| failReason.contains("INVALID_REQUEST");
}
@Async
protected void scheduleRetry(String orderNo) {
try {
// 延迟指定时间后执行重试
Thread.sleep(profitSharingProperties.getRetryInterval());
retryFailedProfitSharing(orderNo);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error("重试任务被中断: orderNo={}", orderNo);
}
}
private void sendAlertNotification(ProfitSharing profitSharing, Exception e) {
try {
// 这里实现告警通知逻辑,例如:
// 1. 发送邮件
// 2. 发送钉钉消息
// 3. 发送微信消息
// 4. 写入告警日志
String alertMessage = String.format(
"分账失败告警\n订单号:%s\n失败原因:%s\n重试次数:%d\n异常信息:%s",
profitSharing.getOrderNo(),
profitSharing.getFailReason(),
profitSharing.getRetryTimes(),
e.getMessage()
);
log.warn(alertMessage);
// TODO: 实现具体的告警通知逻辑
} catch (Exception ex) {
log.error("发送告警通知失败", ex);
}
}
/**
* 构建分账请求
*/
private CreateOrderRequest buildProfitSharingRequest(ProfitSharing profitSharing) {
try {
// 1. 创建分账请求对象
CreateOrderRequest request = new CreateOrderRequest();
// 2. 设置基本信息
request.setAppid(tencentPayProperties.getAppId());
request.setTransactionId(profitSharing.getTransactionId());
request.setOutOrderNo(generateProfitSharingNo());
// 3. 设置分账接收方列表
List<CreateOrderReceiver> receivers = new ArrayList<>();
CreateOrderReceiver receiver = new CreateOrderReceiver();
// 4. 设置接收方信息
receiver.setType(profitSharing.getPayeeType());
receiver.setAccount(profitSharing.getPayeeAccount());
receiver.setAmount(profitSharing.getQrCodeAmount());
receiver.setDescription("二维码分账");
receivers.add(receiver);
request.setReceivers(receivers);
// 5. 保存分账请求号
profitSharing.setOutOrderNo(request.getOutOrderNo());
profitSharing.setUpdateTime(new Date());
updateById(profitSharing);
log.info("构建分账请求: orderNo={}, request={}", profitSharing.getOrderNo(), request);
return request;
} catch (Exception e) {
log.error("构建分账请求失败: profitSharing={}", profitSharing, e);
throw new BusinessException("构建分账请求失败: " + e.getMessage());
}
}
/**
* 验证分账请求参数
*/
private void validateProfitSharingRequest(ProfitSharing profitSharing) {
if (StringUtils.isEmpty(profitSharing.getTransactionId())) {
throw new BusinessException("支付交易号不能为空");
}
if (StringUtils.isEmpty(profitSharing.getPayeeAccount())) {
throw new BusinessException("分账接收方账号不能为空");
}
if (StringUtils.isEmpty(profitSharing.getPayeeType())) {
throw new BusinessException("分账接收方类型不能为空");
}
if (profitSharing.getQrCodeAmount() == null || profitSharing.getQrCodeAmount() <= 0) {
throw new BusinessException("分账金额必须大于0");
}
// 验证金额不超过订单总额
if (profitSharing.getQrCodeAmount() > profitSharing.getTotalAmount()) {
throw new BusinessException("分账金额不能超过订单总额");
}
}
}
@@ -0,0 +1,51 @@
package com.central.order.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
@Slf4j
public class ExceptionUtils {
/**
* 获取异常的根本原因
*/
public static String getRootCauseMessage(Throwable throwable) {
Throwable rootCause = getRootCause(throwable);
return rootCause.getMessage();
}
/**
* 获取异常的根本原因对象
*/
public static Throwable getRootCause(Throwable throwable) {
Throwable cause = throwable;
while (cause.getCause() != null) {
cause = cause.getCause();
}
return cause;
}
/**
* 格式化异常信息
*/
public static String formatErrorMessage(String message) {
if (!StringUtils.hasText(message)) {
return "未知错误";
}
// 移除敏感信息
message = message.replaceAll("\\{\"password\":\"[^\"]*\"\\}", "{\"password\":\"***\"}");
// 限制长度
return message.length() > 200 ? message.substring(0, 200) : message;
}
/**
* 判断是否为业务异常
*/
public static boolean isBusinessException(Throwable throwable) {
String message = getRootCauseMessage(throwable);
// 根据错误信息判断是否为业务异常
return message.contains("PARAM_ERROR")
|| message.contains("SIGN_ERROR")
|| message.contains("INVALID_REQUEST");
}
}
@@ -49,6 +49,17 @@ tencent:
app-secret:
token:
encoding-aes-key:
pay:
profit-sharing:
enabled: true
max-retry-times: 3
retry-interval: 300000
platform-rate: 30
timeout: 1800000
async-enabled: true
async-pool-size: 5
api:
profit-sharing-url: https://api.mch.weixin.qq.com/v3/profitsharing/orders
file:
oss-url: goflyapp.oss-cn-beijing.aliyuncs.com
cdn-url: cdn.goflytec.com