fix:支付通用模块功能逻辑完善,订单模块动态引入逻辑调整

This commit is contained in:
2025-06-03 17:28:26 +08:00
parent 1dec9d2035
commit 45b6afcbff
10 changed files with 114 additions and 130 deletions
@@ -4,20 +4,18 @@ 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.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
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.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
@Configuration
@RequiredArgsConstructor
//@Configuration
//@RequiredArgsConstructor
public class WxMpConfiguration {
@Bean
@@ -9,7 +9,6 @@ import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.common.model.SysUser;
import com.central.log.annotation.AuditLog;
import com.central.order.config.TencentPayProperties;
import com.central.order.enums.CommonStatus;
import com.central.order.enums.OrderStatus;
import com.central.order.feign.DeviceCenterService;
@@ -17,7 +16,9 @@ import com.central.order.feign.FileCenterService;
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.central.wechat.config.WxPayConfigFactory;
import com.central.wechat.entity.WechatConfig;
import com.central.wechat.feign.WechatConfigService;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
@@ -71,14 +72,11 @@ public class OrderController {
@Autowired
private FileCenterService fileCenterService;
@Autowired
private JsapiServiceExtension service;
@Autowired
private IQrCodeService qrCodeService;
@Autowired
private TencentPayProperties tencentPayProperties;
private WechatConfigService wechatConfigService;
@Value("${file.oss-url}")
private String cdnOssUrl;
@@ -97,6 +95,9 @@ public class OrderController {
@Autowired
private IProfitSharingService profitSharingService;
@Autowired
private WxPayConfigFactory wxPayConfigFactory;
/**
* 列表
*/
@@ -247,15 +248,16 @@ public class OrderController {
// 3. 创建支付请求
PrepayRequest request = new PrepayRequest();
WechatConfig wechatConfig = wechatConfigService.getConfig("PAY",qrCode.getTenantId());
// 设置基本支付信息
Amount amount = new Amount();
amount.setTotal(Integer.parseInt(order.getOrderAmount()));
request.setAmount(amount);
request.setAppid(tencentPayProperties.getAppId());
request.setMchid(tencentPayProperties.getMerchantId());
request.setAppid(wechatConfig.getAppId());
request.setMchid(wechatConfig.getMerchantId());
request.setDescription(order.getOrderNo());
request.setNotifyUrl(tencentPayProperties.getNotifyUrl());
request.setNotifyUrl(wechatConfig.getNotifyUrl());
request.setOutTradeNo(order.getOrderNo());
// 设置支付者信息
@@ -277,7 +279,7 @@ public class OrderController {
}
// 5. 调用支付接口
PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request);
PrepayWithRequestPaymentResponse response = wxPayConfigFactory.createJsapiService(qrCode.getTenantId()).prepayWithRequestPayment(request);
// 6. 返回结果
return Result.succeed(response, order.getOrderNo());
@@ -7,7 +7,7 @@ import com.central.order.enums.RefundState;
import com.central.order.model.Order;
import com.central.order.service.IOrderService;
import com.central.order.service.IRefundService;
import com.wechat.pay.java.service.refund.RefundService;
import com.central.wechat.config.WxPayConfigFactory;
import com.wechat.pay.java.service.refund.model.AmountReq;
import com.wechat.pay.java.service.refund.model.CreateRequest;
import com.wechat.pay.java.service.refund.model.Refund;
@@ -28,7 +28,7 @@ import java.util.Map;
public class RefundController {
@Autowired
private RefundService service;
private WxPayConfigFactory wxPayConfigFactory;
@Autowired
private IOrderService orderService;
@@ -135,7 +135,7 @@ public class RefundController {
request.setAmount(amount);
// 发起退款请求
Refund response = service.create(request);
Refund response = wxPayConfigFactory.createRefundService(order.getTenantId()).create(request);
Assert.notNull(response, "退款失败");
} catch (Exception e) {
// 记录异常信息
@@ -10,7 +10,7 @@ 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.wechat.pay.java.core.notification.NotificationConfig;
import com.central.wechat.config.WxPayConfigFactory;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.model.Transaction;
@@ -45,7 +45,7 @@ public class WxPayController {
private IProfitSharingService profitSharingService;
@Autowired
private NotificationConfig config;
private WxPayConfigFactory wxPayConfigFactory;
@PostMapping("/pay/notify")
public String handleCallback(@RequestHeader("Wechatpay-Signature") String signature,
@@ -65,7 +65,7 @@ public class WxPayController {
.build();
NotificationParser notificationParser = new NotificationParser(config);
NotificationParser notificationParser = wxPayConfigFactory.createNotificationParser("");
// 解析通知
Transaction transaction = notificationParser.parse(requestParam,Transaction.class);
@@ -183,7 +183,7 @@ public class WxPayController {
.timestamp(timestamp)
.build();
NotificationParser notificationParser = new NotificationParser(config);
NotificationParser notificationParser = wxPayConfigFactory.createNotificationParser("");
// 解析通知
RefundNotification notification = notificationParser.parse(requestParam, RefundNotification.class);
@@ -217,7 +217,7 @@ public class WxPayController {
*/
private ProfitSharingNotification parseNotification(RequestParam requestParam) {
try {
NotificationParser parser = new NotificationParser(config);
NotificationParser parser = wxPayConfigFactory.createNotificationParser("");
// 解析为Map后转换为ProfitSharingNotification对象
Map<String, Object> result = parser.parse(requestParam, Map.class);
@@ -1,15 +1,15 @@
package com.central.order.model;
import com.baomidou.mybatisplus.annotation.TableField;
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.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.Min;
@@ -26,49 +26,49 @@ 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")
@@ -78,44 +78,46 @@ public class ProfitSharing {
@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;
private String tenantId;
/**
* 获取状态描述
*/
@@ -138,8 +140,8 @@ public class ProfitSharing {
* 3. 距离上次重试时间超过5分钟
*/
public boolean canRetry() {
return status == ProfitSharingStatusEnum.FAILED.getCode()
&& (retryTimes == null || retryTimes < 3)
return status == ProfitSharingStatusEnum.FAILED.getCode()
&& (retryTimes == null || retryTimes < 3)
&& (lastRetryTime == null || System.currentTimeMillis() - lastRetryTime.getTime() > 300000);
}
@@ -155,9 +157,9 @@ public class ProfitSharing {
* 检查金额是否合法
*/
public boolean isAmountValid() {
return totalAmount != null && totalAmount > 0
return totalAmount != null && totalAmount > 0
&& platformAmount != null && platformAmount >= 0
&& qrCodeAmount != null && qrCodeAmount > 0
&& (platformAmount + qrCodeAmount == totalAmount);
}
}
}
@@ -6,7 +6,6 @@ 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;
@@ -17,14 +16,14 @@ import com.central.order.model.QrCode;
import com.central.order.model.vo.ProfitSharingStatisticsVO;
import com.central.order.service.IProfitSharingService;
import com.central.order.service.IQrCodeService;
import com.wechat.pay.java.service.profitsharing.ProfitsharingService;
import com.central.wechat.config.WxPayConfigFactory;
import com.central.wechat.feign.WechatConfigService;
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.apache.commons.lang3.time.DateUtils;
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;
@@ -36,7 +35,6 @@ 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
@@ -44,10 +42,10 @@ import java.util.stream.Collectors;
public class ProfitSharingServiceImpl extends SuperServiceImpl<ProfitSharingMapper, ProfitSharing> implements IProfitSharingService {
@Autowired
private TencentPayProperties tencentPayProperties;
private WechatConfigService wechatConfigService;
@Autowired
private ProfitsharingService profitsharingService;
private WxPayConfigFactory wxPayConfigFactory;
@Autowired
private IQrCodeService qrCodeService;
@@ -55,12 +53,6 @@ public class ProfitSharingServiceImpl extends SuperServiceImpl<ProfitSharingMapp
@Autowired
private ProfitSharingProperties profitSharingProperties;
@Autowired(required = false)
private Executor profitSharingExecutor;
@Value("${wechat.pay.platform-rate:0.30}")
private String platformRate;
@Autowired
private ProfitSharingMapper profitSharingMapper;
@@ -97,6 +89,7 @@ public class ProfitSharingServiceImpl extends SuperServiceImpl<ProfitSharingMapp
.payeeType(qrCode.getPayeeType())
.codeId(qrCode.getCodeId())
.status(0)
.tenantId(qrCode.getTenantId())
.createTime(new Date())
.updateTime(new Date())
.build();
@@ -177,7 +170,7 @@ public class ProfitSharingServiceImpl extends SuperServiceImpl<ProfitSharingMapp
private OrdersEntity executeProfitSharingRequest(ProfitSharing profitSharing) {
CreateOrderRequest request = buildProfitSharingRequest(profitSharing);
try {
return profitsharingService.createOrder(request);
return wxPayConfigFactory.createProfitsharingService(profitSharing.getTenantId()).createOrder(request);
} catch (Exception e) {
log.error("调用微信分账接口失败", e);
throw new BusinessException("分账请求失败");
@@ -225,7 +218,7 @@ public class ProfitSharingServiceImpl extends SuperServiceImpl<ProfitSharingMapp
// 2. 构建添加接收方请求
AddReceiverRequest request = new AddReceiverRequest();
request.setAppid(tencentPayProperties.getAppId());
request.setAppid(wechatConfigService.getConfig("PAY",qrCode.getTenantId()).getAppId());
// 设置接收方类型
try {
@@ -243,7 +236,7 @@ public class ProfitSharingServiceImpl extends SuperServiceImpl<ProfitSharingMapp
// 3. 调用微信接口添加接收方
try {
AddReceiverResponse response = profitsharingService.addReceiver(request);
AddReceiverResponse response = wxPayConfigFactory.createProfitsharingService(qrCode.getTenantId()).addReceiver(request);
// 4. 处理响应结果
if (response != null && response.getAccount() != null) {
@@ -469,7 +462,8 @@ public class ProfitSharingServiceImpl extends SuperServiceImpl<ProfitSharingMapp
QueryOrderRequest request = new QueryOrderRequest();
request.setOutOrderNo(outOrderNo);
request.setTransactionId(transactionId);
return profitsharingService.queryOrder(request);
ProfitSharing profitSharing = getByOrderNo(outOrderNo);
return wxPayConfigFactory.createProfitsharingService(profitSharing.getTenantId()).queryOrder(request);
} catch (Exception e) {
log.error("查询分账结果失败: outOrderNo={}, transactionId={}", outOrderNo, transactionId, e);
throw new RuntimeException("查询分账结果失败", e);
@@ -496,7 +490,7 @@ public class ProfitSharingServiceImpl extends SuperServiceImpl<ProfitSharingMapp
QueryOrderRequest request = new QueryOrderRequest();
request.setOutOrderNo(profitSharing.getOutOrderNo());
request.setTransactionId(profitSharing.getTransactionId());
response = profitsharingService.queryOrder(request);
response = wxPayConfigFactory.createProfitsharingService(profitSharing.getTenantId()).queryOrder(request);
}
// 4. 构建返回结果
@@ -636,7 +630,7 @@ public class ProfitSharingServiceImpl extends SuperServiceImpl<ProfitSharingMapp
CreateOrderRequest request = new CreateOrderRequest();
// 2. 设置基本信息
request.setAppid(tencentPayProperties.getAppId());
request.setAppid(wechatConfigService.getConfig("PAY",profitSharing.getTenantId()).getAppId());
request.setTransactionId(profitSharing.getTransactionId());
request.setOutOrderNo(generateProfitSharingNo());
@@ -1,13 +1,13 @@
package com.central.order.service.impl;
import com.central.common.exception.BusinessException;
import com.central.order.config.TencentPayProperties;
import com.central.order.config.WxMpProperties;
import com.central.order.enums.CommonStatus;
import com.central.order.model.WxMessageRecord;
import com.central.order.service.IWxMessageRecordService;
import com.central.order.service.IWxTemplateMessageService;
import com.central.order.service.IWxUserService;
import com.central.wechat.entity.WechatConfig;
import com.central.wechat.feign.WechatConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
@@ -16,6 +16,7 @@ import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
@@ -34,17 +35,19 @@ public class WxTemplateMessageServiceImpl implements IWxTemplateMessageService {
@Autowired
private WxMpService wxMpService;
@Autowired
private WxMpProperties wxMpProperties;
@Autowired
private IWxUserService wxUserService;
@Autowired
private TencentPayProperties tencentPayProperties;
private WechatConfigService wechatConfigService;
@Autowired
private IWxMessageRecordService wxMessageRecordService;
@Value("${zlt.tenant.id}")
private String defaultTenantId;
@Override
@Retryable(value = WxErrorException.class, maxAttempts = 3, backoff = @Backoff(delay = 1000, multiplier = 2))
public void sendPaymentSuccessNotice(String unionId, String orderNo, String tourismName,
@@ -60,10 +63,11 @@ public class WxTemplateMessageServiceImpl implements IWxTemplateMessageService {
try {
String openId = wxUserService.getMpOpenIdByUnionId(unionId);
log.info("获取到服务号openId={}", openId);
WechatConfig config = wechatConfigService.getConfig("PAY",defaultTenantId);
// 构建模板消息
WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
.toUser(openId)
.templateId(wxMpProperties.getTemplateId().getPaymentSuccess())
.templateId(config.getPaymentSuccessTemplateId())
.data(Arrays.asList(
new WxMpTemplateData("thing2", tourismName+"提示: 您当前排在第"+rank+"位!"),
new WxMpTemplateData("time3", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))),
@@ -71,7 +75,7 @@ public class WxTemplateMessageServiceImpl implements IWxTemplateMessageService {
// new WxMpTemplateData("amount4", "19.90")
))
.miniProgram(new WxMpTemplateMessage.MiniProgram(
tencentPayProperties.getAppId(),
config.getAppId(),
"pages/index/index",
true))
.build();
@@ -29,6 +29,7 @@ knife4j:
zlt:
#多租户配置
tenant:
id: webApp
enable: false
ignoreTables:
- edit_task
@@ -5,12 +5,7 @@ import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.central.wechat.entity.WechatConfig;
import com.central.wechat.feign.WechatConfigService;
import com.wechat.pay.java.core.Config;
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.refund.RefundService;
import com.wechat.pay.java.service.profitsharing.ProfitsharingService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
@@ -22,10 +17,6 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
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;
@Slf4j
@Configuration
@@ -74,36 +65,6 @@ public class WechatAutoConfiguration {
return new WxPayConfigFactory(configService);
}
@Bean
@ConditionalOnBean(WxPayConfigFactory.class)
public Config wxPayConfig(WxPayConfigFactory factory) {
return factory.createConfig(getCurrentTenantId());
}
@Bean
@ConditionalOnBean(WxPayConfigFactory.class)
public JsapiServiceExtension jsapiService(WxPayConfigFactory factory) {
return factory.createJsapiService(getCurrentTenantId());
}
@Bean
@ConditionalOnBean(WxPayConfigFactory.class)
public NotificationParser notificationParser(WxPayConfigFactory factory) {
return factory.createNotificationParser(getCurrentTenantId());
}
@Bean
@ConditionalOnBean(WxPayConfigFactory.class)
public RefundService refundService(WxPayConfigFactory factory) {
return factory.createRefundService(getCurrentTenantId());
}
@Bean
@ConditionalOnBean(Config.class)
public ProfitsharingService profitsharingService(Config config) {
return new ProfitsharingService.Builder().config(config).build();
}
@Bean
@ConditionalOnBean(WechatConfigService.class)
public SettleInfo settleInfo(WechatConfigService configService) {
@@ -113,25 +74,6 @@ public class WechatAutoConfiguration {
return settleInfo;
}
@Bean
@ConditionalOnBean(WechatConfigService.class)
public Executor profitSharingExecutor(WechatConfigService configService) {
log.info("profitSharingExecutor被加载,tenantId:{}", getCurrentTenantId());
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;
}
private String getCurrentTenantId() {
return "webApp";
}
@@ -8,12 +8,16 @@ 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.refund.RefundService;
import com.wechat.pay.java.service.profitsharing.ProfitsharingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import java.security.PrivateKey;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Slf4j
@Component
@@ -25,6 +29,8 @@ public class WxPayConfigFactory {
private final Map<String, JsapiServiceExtension> jsapiServiceCache = new ConcurrentHashMap<>();
private final Map<String, NotificationParser> notificationParserCache = new ConcurrentHashMap<>();
private final Map<String, RefundService> refundServiceCache = new ConcurrentHashMap<>();
private final Map<String, ProfitsharingService> profitsharingServiceCache = new ConcurrentHashMap<>();
private final Map<String, Executor> executorCache = new ConcurrentHashMap<>();
public WxPayConfigFactory(WechatConfigService configService) {
this.configService = configService;
@@ -85,6 +91,37 @@ public class WxPayConfigFactory {
return new RefundService.Builder().config(config).build();
}
public ProfitsharingService createProfitsharingService(String tenantId) {
return profitsharingServiceCache.computeIfAbsent(tenantId, this::buildProfitsharingService);
}
private ProfitsharingService buildProfitsharingService(String tenantId) {
log.info("创建微信分账服务,tenantId:{}", tenantId);
Config config = createConfig(tenantId);
return new ProfitsharingService.Builder().config(config).build();
}
public Executor createExecutor(String tenantId) {
return executorCache.computeIfAbsent(tenantId, this::buildExecutor);
}
private Executor buildExecutor(String tenantId) {
log.info("创建分账异步执行器,tenantId:{}", tenantId);
WechatConfig config = configService.getConfig("PAY", tenantId);
if (!config.getAsyncEnabled()) {
return null;
}
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(config.getAsyncPoolSize());
executor.setMaxPoolSize(config.getAsyncPoolSize());
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("profit-sharing-" + tenantId + "-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
/**
* 清除指定租户的缓存
*/
@@ -93,6 +130,8 @@ public class WxPayConfigFactory {
jsapiServiceCache.remove(tenantId);
notificationParserCache.remove(tenantId);
refundServiceCache.remove(tenantId);
profitsharingServiceCache.remove(tenantId);
executorCache.remove(tenantId);
}
/**
@@ -103,5 +142,7 @@ public class WxPayConfigFactory {
jsapiServiceCache.clear();
notificationParserCache.clear();
refundServiceCache.clear();
profitsharingServiceCache.clear();
executorCache.clear();
}
}