fix:支付和通知相关模块代码恢复

This commit is contained in:
2025-06-03 12:01:16 +08:00
parent 57968ae2e8
commit ce896c158f
21 changed files with 548 additions and 413 deletions
@@ -2,9 +2,12 @@ package com.central.order;
import com.central.common.lb.annotation.EnableFeignInterceptor;
import com.central.search.annotation.EnableSearchClient;
import com.zlt.wechat.config.WechatAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Import;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
@@ -15,6 +18,8 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
@EnableFeignInterceptor
@SpringBootApplication
@EnableFeignClients(basePackages = {"com.central"})
@Import(WechatAutoConfiguration.class)
public class OrderCenterApp {
public static void main(String[] args) {
SpringApplication.run(OrderCenterApp.class, args);
@@ -1,145 +1,145 @@
//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;
//
///**
// * 支付配置类
// *
// * @author lsl
// * @date 2025-01-14
// *
// */
//@Getter
//@Setter
//@Configuration
//@ConfigurationProperties(prefix = "tencent")
//@EnableConfigurationProperties(ProfitSharingProperties.class)
//public class TencentPayConfiguration {
//
// private String merchantId;
//
// private String merchantSerialNumber;
//
// private String apiV3Key;
//
// private String privateKeyPath;
//
// private String appId;
//
// private String appSecret;
//
// private String notifyUrl;
//
// /**
// * jsapi支付方式 支持小程序公众号支付
// * @return
// */
// @Bean
// public JsapiServiceExtension initialJsapiServiceExtension() {
// // 构建service
// return new JsapiServiceExtension.Builder().config(getConfig()).build();
// }
//
// @Bean
// public RefundService initialRefundService() {
// // 构建service
// return new RefundService.Builder().config(getConfig()).build();
// }
//
// /**
// * 微信支付配置获取
// * @return
// */
// public Config getConfig() {
// return new RSAAutoCertificateConfig.Builder()
// .merchantId(merchantId)
// .privateKeyFromPath(privateKeyPath)
// .merchantSerialNumber(merchantSerialNumber)
// .apiV3Key(apiV3Key)
// .build();
// }
//
//
// @Bean
// public NotificationConfig initialNotificationConfig() {
// // . 如果你仍在使用微信支付平台证书,则使用 RSAAutoCertificateConfig
// return new RSAAutoCertificateConfig.Builder()
// .merchantId(merchantId)
// .privateKeyFromPath(privateKeyPath)
// .merchantSerialNumber(merchantSerialNumber)
// .apiV3Key(apiV3Key)
// .build();
// }
//
// @Bean
// public TencentPayProperties initTencentPayProperties() {
// TencentPayProperties tencentPayProperties = new TencentPayProperties();
// tencentPayProperties.setApiV3Key(apiV3Key);
// tencentPayProperties.setMerchantId(merchantId);
// tencentPayProperties.setMerchantSerialNumber(merchantSerialNumber);
// tencentPayProperties.setAppId(appId);
// tencentPayProperties.setAppSecret(appSecret);
// 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;
// }
//}
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.Qualifier;
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 java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 支付配置类
*
* @author lsl
* @date 2025-01-14
*
*/
@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "tencent")
@EnableConfigurationProperties(ProfitSharingProperties.class)
public class TencentPayConfiguration {
private String merchantId;
private String merchantSerialNumber;
private String apiV3Key;
private String privateKeyPath;
private String appId;
private String appSecret;
private String notifyUrl;
/**
* jsapi支付方式 支持小程序公众号支付
* @return
*/
@Bean
public JsapiServiceExtension initialJsapiServiceExtension() {
// 构建service
return new JsapiServiceExtension.Builder().config(getConfig()).build();
}
@Bean
public RefundService initialRefundService() {
// 构建service
return new RefundService.Builder().config(getConfig()).build();
}
/**
* 微信支付配置获取
* @return
*/
public Config getConfig() {
return new RSAAutoCertificateConfig.Builder()
.merchantId(merchantId)
.privateKeyFromPath(privateKeyPath)
.merchantSerialNumber(merchantSerialNumber)
.apiV3Key(apiV3Key)
.build();
}
@Bean
public NotificationConfig initialNotificationConfig() {
// . 如果你仍在使用微信支付平台证书,则使用 RSAAutoCertificateConfig
return new RSAAutoCertificateConfig.Builder()
.merchantId(merchantId)
.privateKeyFromPath(privateKeyPath)
.merchantSerialNumber(merchantSerialNumber)
.apiV3Key(apiV3Key)
.build();
}
@Bean
public TencentPayProperties initTencentPayProperties() {
TencentPayProperties tencentPayProperties = new TencentPayProperties();
tencentPayProperties.setApiV3Key(apiV3Key);
tencentPayProperties.setMerchantId(merchantId);
tencentPayProperties.setMerchantSerialNumber(merchantSerialNumber);
tencentPayProperties.setAppId(appId);
tencentPayProperties.setAppSecret(appSecret);
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;
}
}
@@ -1,25 +1,25 @@
//package com.central.order.config;
//
//
//import lombok.Getter;
//import lombok.Setter;
//
//@Getter
//@Setter
//public class TencentPayProperties {
//
// private String merchantId;
//
// private String merchantSerialNumber;
//
// private String apiV3Key;
//
// private String privateKeyPath;
//
// private String appId;
//
// private String appSecret;
//
// private String notifyUrl;
//
//}
package com.central.order.config;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class TencentPayProperties {
private String merchantId;
private String merchantSerialNumber;
private String apiV3Key;
private String privateKeyPath;
private String appId;
private String appSecret;
private String notifyUrl;
}
@@ -1,9 +1,9 @@
//package com.central.order.config;
//
//import lombok.Data;
//
//@Data
//public class WxMaProperties {
// private String appId;
// private String secret;
//}
package com.central.order.config;
import lombok.Data;
@Data
public class WxMaProperties {
private String appId;
private String secret;
}
@@ -1,68 +1,68 @@
//package com.central.order.config;
//
//import cn.binarywang.wx.miniapp.api.WxMaService;
//import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
//import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
//import com.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
//public class WxMpConfiguration {
//
// @Bean
// @ConfigurationProperties(prefix = "wx.mp")
// public WxMpProperties wxMpProperties() {
// return new WxMpProperties();
// }
//
// @Bean
// public WxMpService wxMpService(WxMpProperties wxMpProperties) {
// WxMpService service = new WxMpServiceImpl();
// WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
//
// config.setAppId(wxMpProperties.getAppId());
// config.setSecret(wxMpProperties.getSecret());
//
// service.setWxMpConfigStorage(config);
// return service;
// }
//
// @Bean
// public RestTemplate restTemplate() {
// RestTemplate restTemplate = new RestTemplate();
// restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
// return restTemplate;
// }
//
// @Bean
// public ObjectMapper objectMapper() {
// return new ObjectMapper();
// }
//
// @Bean
// @ConfigurationProperties(prefix = "wx.mini")
// public WxMaProperties wxMaProperties() {
// return new WxMaProperties();
// }
//
// @Bean
// public WxMaService wxMaService(WxMaProperties wxMaProperties) {
// WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
// config.setAppid(wxMaProperties.getAppId());
// config.setSecret(wxMaProperties.getSecret());
// WxMaService service = new WxMaServiceImpl();
// service.setWxMaConfig(config);
// return service;
// }
//}
package com.central.order.config;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.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
public class WxMpConfiguration {
@Bean
@ConfigurationProperties(prefix = "wx.mp")
public WxMpProperties wxMpProperties() {
return new WxMpProperties();
}
@Bean
public WxMpService wxMpService(WxMpProperties wxMpProperties) {
WxMpService service = new WxMpServiceImpl();
WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
config.setAppId(wxMpProperties.getAppId());
config.setSecret(wxMpProperties.getSecret());
service.setWxMpConfigStorage(config);
return service;
}
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate;
}
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
@Bean
@ConfigurationProperties(prefix = "wx.mini")
public WxMaProperties wxMaProperties() {
return new WxMaProperties();
}
@Bean
public WxMaService wxMaService(WxMaProperties wxMaProperties) {
WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
config.setAppid(wxMaProperties.getAppId());
config.setSecret(wxMaProperties.getSecret());
WxMaService service = new WxMaServiceImpl();
service.setWxMaConfig(config);
return service;
}
}
@@ -1,54 +1,54 @@
//package com.central.order.config;
//
//import lombok.Data;
//
//@Data
//public class WxMpProperties {
// /**
// * 设置微信公众号的appid
// */
// private String appId;
//
// /**
// * 设置微信公众号的app secret
// */
// private String secret;
//
// /**
// * 设置云托管环境ID
// */
// private String cloudEnv;
//
// /**
// * 设置服务基础URL
// */
// private String baseUrl;
//
// /**
// * 模板ID配置
// */
// private TemplateConfig templateId = new TemplateConfig();
//
// @Data
// public static class TemplateConfig {
// /**
// * 支付成功通知模板ID
// * 模板内容:
// * 服务名称:{{thing2.DATA}}
// * 出行时间:{{time3.DATA}}
// * 订单号:{{character_string1.DATA}}
// * 支付金额:{{amount4.DATA}}
// */
// private String paymentSuccess;
//
// /**
// * 视频处理完成通知模板ID
// */
// private String videoComplete;
//
// /**
// * 视频处理失败通知模板ID
// */
// private String videoFail;
// }
//}
package com.central.order.config;
import lombok.Data;
@Data
public class WxMpProperties {
/**
* 设置微信公众号的appid
*/
private String appId;
/**
* 设置微信公众号的app secret
*/
private String secret;
/**
* 设置云托管环境ID
*/
private String cloudEnv;
/**
* 设置服务基础URL
*/
private String baseUrl;
/**
* 模板ID配置
*/
private TemplateConfig templateId = new TemplateConfig();
@Data
public static class TemplateConfig {
/**
* 支付成功通知模板ID
* 模板内容:
* 服务名称:{{thing2.DATA}}
* 出行时间:{{time3.DATA}}
* 订单号:{{character_string1.DATA}}
* 支付金额:{{amount4.DATA}}
*/
private String paymentSuccess;
/**
* 视频处理完成通知模板ID
*/
private String videoComplete;
/**
* 视频处理失败通知模板ID
*/
private String videoFail;
}
}
@@ -7,7 +7,9 @@ import com.central.common.context.TenantContextHolder;
import com.central.common.model.LoginAppUser;
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;
@@ -15,7 +17,8 @@ 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.model.PrepayWithRequestPaymentResponse;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
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;
@@ -68,9 +71,15 @@ public class OrderController {
@Autowired
private FileCenterService fileCenterService;
@Autowired
private JsapiServiceExtension service;
@Autowired
private IQrCodeService qrCodeService;
@Autowired
private TencentPayProperties tencentPayProperties;
@Value("${file.oss-url}")
private String cdnOssUrl;
@@ -88,9 +97,6 @@ public class OrderController {
@Autowired
private IProfitSharingService profitSharingService;
@Autowired
private PaymentService paymentService;
/**
* 列表
*/
@@ -221,12 +227,59 @@ public class OrderController {
* @param orderId 微信公众号对应微信付款用户的唯一标识
* @return 返回jsapi所需参数
*/
@Operation(summary = "生成预支付订单")
@PutMapping("/{orderId}/pay")
public Result<PrepayWithRequestPaymentResponse> payOrder(@PathVariable("orderId") Long orderId) {
try {
PrepayWithRequestPaymentResponse response = paymentService.createPayment(orderId);
// 1. 获取用户和订单信息
SysUser user = userCenterService.findUserById(LoginUserContextHolder.getUser().getId());
Order order = orderService.getById(orderId);
if (order == null) {
return Result.failed("订单数据不存在");
}
// 检查是否需要开启分账
QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId());
if (qrCode == 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();
if (isEnableProfit(qrCode)) {
settleInfo.setProfitSharing(true);
request.setSettleInfo(settleInfo);
// 创建分账记录
ProfitSharing profitSharing = profitSharingService.createProfitSharing(order,qrCode);
} else {
settleInfo.setProfitSharing(false);
request.setSettleInfo(settleInfo);
}
// 5. 调用支付接口
PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request);
// 6. 返回结果
return Result.succeed(response, order.getOrderNo());
} catch (Exception e) {
log.error("创建预支付订单失败", e);
@@ -239,11 +292,11 @@ public class OrderController {
*/
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; // 确保有分润比例
Integer.valueOf(1).equals(qrCode.getEnableProfit()) &&
qrCode.getPayeeStatus() != null &&
qrCode.getPayeeStatus() == 1 && // 确保分账账号已验证
qrCode.getPayeeAccount() != null && // 确保有收款账号
qrCode.getProfitRate() != null; // 确保有分润比例
}
@Operation(summary = "获取排队总览信息")
@@ -390,8 +443,8 @@ public class OrderController {
Order order = orderService.getOrderByNumber(payload.get("orderNo").toString());
Assert.notNull(order,"订单数据不能为空");
if (order.getOrderStatus().equals(OrderStatus.DOING.getId())
|| order.getOrderStatus().equals(OrderStatus.UPLOADED.getId())
|| order.getOrderStatus().equals(OrderStatus.UPLOADING.getId())){
|| order.getOrderStatus().equals(OrderStatus.UPLOADED.getId())
|| order.getOrderStatus().equals(OrderStatus.UPLOADING.getId())){
order.setOrderStatus(OrderStatus.COMPLETE.getId());
if (orderService.updateOrder(order)){
return Result.succeed("更新成功");
@@ -16,7 +16,6 @@ import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
@@ -28,7 +27,7 @@ import java.util.Map;
@RequestMapping("/refund")
public class RefundController {
@Qualifier
@Autowired
private RefundService service;
@Autowired
@@ -20,7 +20,6 @@ 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.Qualifier;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
@@ -45,7 +44,7 @@ public class WxPayController {
@Autowired
private IProfitSharingService profitSharingService;
@Qualifier
@Autowired
private NotificationConfig config;
@PostMapping("/pay/notify")
@@ -27,8 +27,8 @@ public class WxTestController {
// 发送消息
// templateMessageService.sendPaymentSuccessNotice(
// openId, orderNo, serviceName, rank);
templateMessageService.sendPaymentSuccessNotice(
openId, orderNo, serviceName, rank);
return Result.succeed("发送成功");
} catch (Exception e) {
@@ -6,6 +6,7 @@ import com.central.order.service.IWxTemplateMessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;
@@ -17,7 +18,7 @@ import java.time.LocalDateTime;
@RequiredArgsConstructor
public class WxMessageHandler {
// private final WxMpService wxMpService;
private final WxMpService wxMpService;
private final IWxTemplateMessageService templateMessageService;
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage) {
@@ -13,25 +13,25 @@ import com.wechat.pay.java.service.payments.jsapi.model.*;
import com.zlt.wechat.config.WxPayConfigFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class PaymentService {
@Qualifier
private WxPayConfigFactory wxPayConfigFactory;
@Autowired
private WxPayConfigFactory wxPayConfigFactory;
@Autowired
private UserCenterService userCenterService;
@Autowired
private IOrderService orderService;
@Autowired
private IQrCodeService qrCodeService;
@Autowired
private IProfitSharingService profitSharingService;
@Autowired
private WechatConfigService configService;
@Autowired
private UserCenterService userCenterService;
@Autowired
private IOrderService orderService;
@Autowired
private IQrCodeService qrCodeService;
@Autowired
private IProfitSharingService profitSharingService;
@Autowired
private WechatConfigService configService;
public PrepayWithRequestPaymentResponse createPayment(Long orderId) {
// 1. 获取用户和订单信息
@@ -6,6 +6,7 @@ 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;
@@ -23,7 +24,6 @@ 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.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@@ -43,7 +43,10 @@ import java.util.stream.Collectors;
@Service
public class ProfitSharingServiceImpl extends SuperServiceImpl<ProfitSharingMapper, ProfitSharing> implements IProfitSharingService {
@Qualifier
@Autowired
private TencentPayProperties tencentPayProperties;
@Autowired
private ProfitsharingService profitsharingService;
@Autowired
@@ -52,7 +55,7 @@ public class ProfitSharingServiceImpl extends SuperServiceImpl<ProfitSharingMapp
@Autowired
private ProfitSharingProperties profitSharingProperties;
@Qualifier
@Autowired(required = false)
private Executor profitSharingExecutor;
@Value("${wechat.pay.platform-rate:0.30}")
@@ -222,8 +225,7 @@ public class ProfitSharingServiceImpl extends SuperServiceImpl<ProfitSharingMapp
// 2. 构建添加接收方请求
AddReceiverRequest request = new AddReceiverRequest();
//@TODO 动态获取appId
// request.setAppid(tencentPayProperties.getAppId());
request.setAppid(tencentPayProperties.getAppId());
// 设置接收方类型
try {
@@ -314,16 +316,16 @@ public class ProfitSharingServiceImpl extends SuperServiceImpl<ProfitSharingMapp
private boolean canRetry(ProfitSharing profitSharing) {
return profitSharing.getStatus() == ProfitSharingStatusEnum.FAILED.getCode()
&& (profitSharing.getRetryTimes() == null
&& (profitSharing.getRetryTimes() == null
|| profitSharing.getRetryTimes() < profitSharingProperties.getMaxRetryTimes())
&& (profitSharing.getLastRetryTime() == null
&& (profitSharing.getLastRetryTime() == null
|| System.currentTimeMillis() - profitSharing.getLastRetryTime().getTime()
> profitSharingProperties.getRetryInterval());
> profitSharingProperties.getRetryInterval());
}
private void updateRetryInfo(ProfitSharing profitSharing) {
profitSharing.setRetryTimes(
(profitSharing.getRetryTimes() == null ? 0 : profitSharing.getRetryTimes()) + 1
(profitSharing.getRetryTimes() == null ? 0 : profitSharing.getRetryTimes()) + 1
);
profitSharing.setLastRetryTime(new Date());
updateById(profitSharing);
@@ -574,8 +576,8 @@ public class ProfitSharingServiceImpl extends SuperServiceImpl<ProfitSharingMapp
private boolean shouldRetry(ProfitSharing profitSharing) {
return profitSharingProperties.isEnabled()
&& profitSharing.canRetry()
&& !isSystemError(profitSharing.getFailReason());
&& profitSharing.canRetry()
&& !isSystemError(profitSharing.getFailReason());
}
private boolean isSystemError(String failReason) {
@@ -584,8 +586,8 @@ public class ProfitSharingServiceImpl extends SuperServiceImpl<ProfitSharingMapp
return false;
}
return failReason.contains("PARAM_ERROR")
|| failReason.contains("SIGN_ERROR")
|| failReason.contains("INVALID_REQUEST");
|| failReason.contains("SIGN_ERROR")
|| failReason.contains("INVALID_REQUEST");
}
@Async
@@ -609,11 +611,11 @@ public class ProfitSharingServiceImpl extends SuperServiceImpl<ProfitSharingMapp
// 4. 写入告警日志
String alertMessage = String.format(
"分账失败告警\n订单号:%s\n失败原因:%s\n重试次数:%d\n异常信息:%s",
profitSharing.getOrderNo(),
profitSharing.getFailReason(),
profitSharing.getRetryTimes(),
e.getMessage()
"分账失败告警\n订单号:%s\n失败原因:%s\n重试次数:%d\n异常信息:%s",
profitSharing.getOrderNo(),
profitSharing.getFailReason(),
profitSharing.getRetryTimes(),
e.getMessage()
);
log.warn(alertMessage);
@@ -633,8 +635,8 @@ public class ProfitSharingServiceImpl extends SuperServiceImpl<ProfitSharingMapp
// 1. 创建分账请求对象
CreateOrderRequest request = new CreateOrderRequest();
// 2. 设置基本信息 //@TODO 动态获取appId
// request.setAppid(tencentPayProperties.getAppId());
// 2. 设置基本信息
request.setAppid(tencentPayProperties.getAppId());
request.setTransactionId(profitSharing.getTransactionId());
request.setOutOrderNo(generateProfitSharingNo());
@@ -759,8 +761,8 @@ public class ProfitSharingServiceImpl extends SuperServiceImpl<ProfitSharingMapp
*/
private boolean isEnableProfit(QrCode qrCode) {
return qrCode != null &&
Integer.valueOf(1).equals(qrCode.getEnableProfit()) &&
qrCode.getPayeeStatus() != null &&
qrCode.getPayeeStatus() == 1;
Integer.valueOf(1).equals(qrCode.getEnableProfit()) &&
qrCode.getPayeeStatus() != null &&
qrCode.getPayeeStatus() == 1;
}
}
@@ -8,7 +8,6 @@ import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
@@ -24,7 +23,7 @@ import java.util.concurrent.TimeUnit;
@RequiredArgsConstructor
public class WxAccessTokenServiceImpl implements IWxAccessTokenService {
@Qualifier
@Autowired
private WxMpService wxMpService;
@Autowired
private StringRedisTemplate redisTemplate;
@@ -4,7 +4,8 @@ import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import com.central.order.service.WxMiniSubscribeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
@@ -15,13 +16,13 @@ import java.util.List;
@Service
public class WxMiniSubscribeServiceImpl implements WxMiniSubscribeService {
// @Value("${wx.mini.template.pay-success}")
// private String templateId;
//
// @Value("${wx.mini.template.service-process}")
// private String serviceProcessTemplateId;
@Value("${wx.mini.template.pay-success}")
private String templateId;
@Qualifier
@Value("${wx.mini.template.service-process}")
private String serviceProcessTemplateId;
@Autowired
private WxMaService wxMaService;
@Override
@@ -29,7 +30,7 @@ public class WxMiniSubscribeServiceImpl implements WxMiniSubscribeService {
try {
WxMaSubscribeMessage msg = new WxMaSubscribeMessage();
msg.setToUser(openId);
msg.setTemplateId("templateId");
msg.setTemplateId(templateId);
msg.setPage("pages/task/task"); // 可选跳转页面
List<WxMaSubscribeMessage.MsgData> dataList = new ArrayList<>();
@@ -62,7 +63,7 @@ public class WxMiniSubscribeServiceImpl implements WxMiniSubscribeService {
try {
WxMaSubscribeMessage msg = new WxMaSubscribeMessage();
msg.setToUser(openId);
msg.setTemplateId("serviceProcessTemplateId");
msg.setTemplateId(serviceProcessTemplateId);
msg.setPage(pageUrl); // 可选跳转页面 "pages/task/task"
List<WxMaSubscribeMessage.MsgData> dataList = new ArrayList<>();
@@ -1,6 +1,9 @@
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;
@@ -9,10 +12,10 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
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.Qualifier;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
@@ -22,18 +25,23 @@ import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
@Slf4j
@Service
@RequiredArgsConstructor
public class WxTemplateMessageServiceImpl implements IWxTemplateMessageService {
@Qualifier
@Autowired
private WxMpService wxMpService;
@Autowired
private WxMpProperties wxMpProperties;
@Autowired
private IWxUserService wxUserService;
@Autowired
private TencentPayProperties tencentPayProperties;
@Autowired
private IWxMessageRecordService wxMessageRecordService;
@@ -49,33 +57,41 @@ public class WxTemplateMessageServiceImpl implements IWxTemplateMessageService {
throw new BusinessException("参数不能为空");
}
String openId = wxUserService.getMpOpenIdByUnionId(unionId);
log.info("获取到服务号openId={}", openId);
// 构建模板消息
// WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
// .toUser(openId)
//// .templateId(wxMpProperties.getTemplateId().getPaymentSuccess())
// .data(Arrays.asList(
// new WxMpTemplateData("thing2", tourismName+"提示: 您当前排在第"+rank+"位!"),
// new WxMpTemplateData("time3", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))),
// new WxMpTemplateData("character_string1", orderNo)
//// new WxMpTemplateData("amount4", "19.90")
// ))
// .miniProgram(new WxMpTemplateMessage.MiniProgram(
// tencentPayProperties.getAppId(),
// "pages/index/index",
// true))
// .build();
try {
String openId = wxUserService.getMpOpenIdByUnionId(unionId);
log.info("获取到服务号openId={}", openId);
// 构建模板消息
WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
.toUser(openId)
.templateId(wxMpProperties.getTemplateId().getPaymentSuccess())
.data(Arrays.asList(
new WxMpTemplateData("thing2", tourismName+"提示: 您当前排在第"+rank+"位!"),
new WxMpTemplateData("time3", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))),
new WxMpTemplateData("character_string1", orderNo)
// new WxMpTemplateData("amount4", "19.90")
))
.miniProgram(new WxMpTemplateMessage.MiniProgram(
tencentPayProperties.getAppId(),
"pages/index/index",
true))
.build();
// 发送消息并获取消息ID
// String msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
// 发送消息并获取消息ID
String msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
// 记录发送结果
// log.info("模板消息发送成功: openId={}, orderNo={}, msgId={}", openId, orderNo, msgId);
// 记录发送结果
log.info("模板消息发送成功: openId={}, orderNo={}, msgId={}", openId, orderNo, msgId);
// 保存发送记录
// 保存发送记录
saveMessageRecord(openId, msgId, templateMessage,CommonStatus.ENABLE.getId());
} catch (WxErrorException e) {
log.error("发送模板消息失败: unionId={}, orderNo={}, errorCode={}, errorMsg={}",
unionId, orderNo, e.getError().getErrorCode(), e.getError().getErrorMsg());
// 保存发送记录 @TODO
// saveMessageRecord(openId, msgId, templateMessage,CommonStatus.ENABLE.getId());
throw new BusinessException("发送失败:" + e.getError().getErrorMsg());
}
}
private String formatDateTime(LocalDateTime dateTime) {
@@ -128,19 +144,19 @@ public class WxTemplateMessageServiceImpl implements IWxTemplateMessageService {
// 提取小程序信息
if (templateMessage.getMiniProgram() != null) {
content.append("小程序信息:")
.append("appid=").append(templateMessage.getMiniProgram().getAppid())
.append(", path=").append(templateMessage.getMiniProgram().getPagePath())
.append("\n");
.append("appid=").append(templateMessage.getMiniProgram().getAppid())
.append(", path=").append(templateMessage.getMiniProgram().getPagePath())
.append("\n");
}
// 提取模板数据
if (templateMessage.getData() != null) {
content.append("模板数据:\n");
templateMessage.getData().forEach(data ->
content.append(data.getName())
.append("=")
.append(data.getValue())
.append("\n")
content.append(data.getName())
.append("=")
.append(data.getValue())
.append("\n")
);
}
@@ -155,9 +171,9 @@ public class WxTemplateMessageServiceImpl implements IWxTemplateMessageService {
@Recover
public void recover(WxErrorException e, String openId, String orderNo,
String serviceName, BigDecimal amount, LocalDateTime tourTime) {
String serviceName, BigDecimal amount, LocalDateTime tourTime) {
log.error("发送模板消息重试耗尽: openId={}, orderNo={}, error={}",
openId, orderNo, e.getMessage());
openId, orderNo, e.getMessage());
// TODO: 实现失败处理逻辑
}
}
@@ -7,7 +7,7 @@ import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpUserService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
@@ -17,7 +17,7 @@ import org.springframework.stereotype.Service;
@Service
public class WxUserServiceImpl implements IWxUserService {
@Qualifier
@Autowired
private WxMpService wxMpService;
@Override
@@ -4,10 +4,10 @@ server:
spring:
application:
name: order-center
cloud:
nacos:
discovery:
ip: 81.70.164.178
# cloud:
# nacos:
# discovery:
# ip: 81.70.164.178
# cloud:
# nacos:
# discovery:
@@ -0,0 +1,39 @@
package com.central.wechat.wechat.config;
import com.central.wechat.wechat.entity.WechatConfig;
import com.central.wechat.wechat.feign.PrivateKeyService;
import com.central.wechat.wechat.feign.WechatConfigService;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class WxPayConfigFactory {
private final WechatConfigService configService;
private final PrivateKeyService privateKeyService;
public WxPayConfigFactory(WechatConfigService configService, PrivateKeyService privateKeyService) {
this.configService = configService;
this.privateKeyService = privateKeyService;
}
public Config createConfig(String tenantId) {
log.info("创建微信支付配置,tenantId:{}", tenantId);
WechatConfig config = configService.getConfig("PAY", tenantId);
String privateKey = privateKeyService.getPrivateKey(tenantId, "PAY");
return new RSAAutoCertificateConfig.Builder()
.merchantId(config.getMerchantId())
.privateKey(privateKey)
.merchantSerialNumber(config.getMchSerialNo())
.apiV3Key(config.getApiV3Key())
.build();
}
public JsapiServiceExtension createJsapiService(String tenantId) {
Config config = createConfig(tenantId);
return new JsapiServiceExtension.Builder().config(config).build();
}
}
@@ -4,6 +4,7 @@ import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.central.common.context.TenantContextHolder;
import com.central.wechat.wechat.config.WechatProperties;
import com.central.wechat.wechat.entity.WechatConfig;
import com.central.wechat.wechat.feign.PrivateKeyService;
import com.central.wechat.wechat.feign.WechatConfigService;
@@ -11,6 +12,7 @@ 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 lombok.extern.slf4j.Slf4j;
@@ -19,6 +21,7 @@ import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@@ -28,6 +31,7 @@ import java.util.concurrent.ThreadPoolExecutor;
@Slf4j
@Configuration
@EnableConfigurationProperties(WechatProperties.class)
public class WechatAutoConfiguration {
@Bean
@@ -75,12 +79,26 @@ public class WechatAutoConfiguration {
}
@Bean
@ConditionalOnBean({WechatConfigService.class, PrivateKeyService.class})
public WxPayConfigFactory wxPayConfigFactory(
WechatConfigService configService,
PrivateKeyService privateKeyService) {
log.info("WxPayConfigFactory被加载,tenantId:{}", getCurrentTenantId());
return new WxPayConfigFactory(configService, privateKeyService);
}
@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
@ConditionalOnMissingBean
@ConditionalOnBean(WechatConfigService.class)
@@ -7,19 +7,21 @@ import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Slf4j
@Component
@Configuration
public class WxPayConfigFactory {
private final WechatConfigService configService;
private final PrivateKeyService privateKeyService;
public WxPayConfigFactory(WechatConfigService configService, PrivateKeyService privateKeyService) {
this.configService = configService;
this.privateKeyService = privateKeyService;
}
@Bean
public Config createConfig(String tenantId) {
log.info("创建微信支付配置,tenantId:{}", tenantId);
WechatConfig config = configService.getConfig("PAY", tenantId);
@@ -31,9 +33,10 @@ public class WxPayConfigFactory {
.apiV3Key(config.getApiV3Key())
.build();
}
@Bean
public JsapiServiceExtension createJsapiService(String tenantId) {
Config config = createConfig(tenantId);
return new JsapiServiceExtension.Builder().config(config).build();
}
}
}