fix:支付流程调试通过

This commit is contained in:
2025-06-04 10:49:23 +08:00
parent 45b6afcbff
commit 91dcb0b99e
9 changed files with 109 additions and 31 deletions
@@ -1,5 +1,6 @@
package com.central.order.controller; package com.central.order.controller;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.central.order.constants.ProfitSharingConstants; import com.central.order.constants.ProfitSharingConstants;
import com.central.order.enums.OrderStatus; import com.central.order.enums.OrderStatus;
import com.central.order.enums.RefundState; import com.central.order.enums.RefundState;
@@ -11,6 +12,8 @@ import com.central.order.service.IProfitSharingService;
import com.central.order.service.IQrCodeService; import com.central.order.service.IQrCodeService;
import com.central.order.service.IRefundService; import com.central.order.service.IRefundService;
import com.central.wechat.config.WxPayConfigFactory; import com.central.wechat.config.WxPayConfigFactory;
import com.central.wechat.entity.WechatConfig;
import com.central.wechat.feign.WechatConfigService;
import com.wechat.pay.java.core.notification.NotificationParser; import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam; import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.model.Transaction; import com.wechat.pay.java.service.payments.model.Transaction;
@@ -20,6 +23,7 @@ import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data; import lombok.Data;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@@ -47,12 +51,19 @@ public class WxPayController {
@Autowired @Autowired
private WxPayConfigFactory wxPayConfigFactory; private WxPayConfigFactory wxPayConfigFactory;
@Autowired
private WechatConfigService wechatConfigService;
@Value("${zlt.tenant.id}")
private String defaultTenantId;
@PostMapping("/pay/notify") @PostMapping("/pay/notify")
public String handleCallback(@RequestHeader("Wechatpay-Signature") String signature, public String handleCallback(@RequestHeader("Wechatpay-Signature") String signature,
@RequestHeader("Wechatpay-Timestamp") String timestamp, @RequestHeader("Wechatpay-Timestamp") String timestamp,
@RequestHeader("Wechatpay-Nonce") String nonce, @RequestHeader("Wechatpay-Nonce") String nonce,
@RequestHeader("Wechatpay-Serial") String serial, @RequestHeader("Wechatpay-Serial") String serial,
@RequestBody String body) { @RequestBody String body) {
try { try {
// 构建请求参数 // 构建请求参数
RequestParam requestParam = new RequestParam RequestParam requestParam = new RequestParam
@@ -63,9 +74,15 @@ public class WxPayController {
.serialNumber(serial) .serialNumber(serial)
.timestamp(timestamp) .timestamp(timestamp)
.build(); .build();
log.info("------收到微信支付成功回调通知------");
log.info(requestParam.toString());
WechatConfig config = wechatConfigService.getConfigBySerialNumber(serial);
String tenantId = config.getTenantId();
if (StringUtil.isBlank(tenantId)) {
tenantId = defaultTenantId;
}
NotificationParser notificationParser = wxPayConfigFactory.createNotificationParser(tenantId);
NotificationParser notificationParser = wxPayConfigFactory.createNotificationParser("");
// 解析通知 // 解析通知
Transaction transaction = notificationParser.parse(requestParam,Transaction.class); Transaction transaction = notificationParser.parse(requestParam,Transaction.class);
@@ -183,7 +200,13 @@ public class WxPayController {
.timestamp(timestamp) .timestamp(timestamp)
.build(); .build();
NotificationParser notificationParser = wxPayConfigFactory.createNotificationParser(""); WechatConfig config = wechatConfigService.getConfigBySerialNumber(serial);
String tenantId = config.getTenantId();
if (StringUtil.isBlank(tenantId)) {
tenantId = defaultTenantId;
}
NotificationParser notificationParser = wxPayConfigFactory.createNotificationParser(tenantId);
// 解析通知 // 解析通知
RefundNotification notification = notificationParser.parse(requestParam, RefundNotification.class); RefundNotification notification = notificationParser.parse(requestParam, RefundNotification.class);
@@ -51,6 +51,12 @@ public class SysWechatConfigController {
return wechatConfigService.getConfig(appId); return wechatConfigService.getConfig(appId);
} }
@GetMapping(value = "/serial/{serialNumber}")
WechatConfig getConfigBySerialNumber(@PathVariable("serialNumber") String serialNumber) {
return wechatConfigService.getConfigBySerialNumber(serialNumber);
}
@Operation(summary = "保存微信配置") @Operation(summary = "保存微信配置")
@PostMapping @PostMapping
public Result<Boolean> saveConfig(@RequestBody WechatConfig config) { public Result<Boolean> saveConfig(@RequestBody WechatConfig config) {
@@ -32,6 +32,14 @@ public interface WechatConfigService extends IService<WechatConfig> {
*/ */
WechatConfig getConfig(String appId); WechatConfig getConfig(String appId);
/**
* 获取微信配置
*
* @param serialNumber 商户序列号
* @return 微信配置
*/
WechatConfig getConfigBySerialNumber(String serialNumber);
/** /**
* 保存微信配置 * 保存微信配置
* *
@@ -10,7 +10,6 @@ import com.central.wechat.entity.WechatConfig;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.MapUtils; import org.apache.commons.collections4.MapUtils;
import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List; import java.util.List;
@@ -31,7 +30,7 @@ public class WechatConfigServiceImpl extends ServiceImpl<WechatConfigMapper, Wec
} }
@Override @Override
@Cacheable(value = CACHE_NAME, key = CACHE_KEY_PATTERN, unless = "#result == null") // @Cacheable(value = CACHE_NAME, key = CACHE_KEY_PATTERN, unless = "#result == null")
public WechatConfig getConfig(String type, String tenantId) { public WechatConfig getConfig(String type, String tenantId) {
return getOne(new LambdaQueryWrapper<WechatConfig>() return getOne(new LambdaQueryWrapper<WechatConfig>()
.eq(WechatConfig::getType, type) .eq(WechatConfig::getType, type)
@@ -46,6 +45,13 @@ public class WechatConfigServiceImpl extends ServiceImpl<WechatConfigMapper, Wec
.eq(WechatConfig::getStatus, 1)); .eq(WechatConfig::getStatus, 1));
} }
@Override
public WechatConfig getConfigBySerialNumber(String serialNumber) {
return getOne(new LambdaQueryWrapper<WechatConfig>()
.eq(WechatConfig::getMchSerialNo, serialNumber)
.eq(WechatConfig::getStatus, 1));
}
@Override @Override
@CacheEvict(value = CACHE_NAME, key = CACHE_KEY_PATTERN) @CacheEvict(value = CACHE_NAME, key = CACHE_KEY_PATTERN)
public boolean saveConfig(WechatConfig config) { public boolean saveConfig(WechatConfig config) {
@@ -21,19 +21,12 @@ public interface WechatConfigService {
* @return * @return
*/ */
@GetMapping(value = "/wechat/config/{type}") @GetMapping(value = "/wechat/config/{type}")
WechatConfig getConfig(@PathVariable("type") String type,String tenantId); WechatConfig getConfig(@PathVariable("type") String type,@RequestParam("tenantId") String tenantId);
@GetMapping(value = "/wechat/config/app/{id}") @GetMapping(value = "/wechat/config/app/{id}")
WechatConfig getConfigByAppId(@PathVariable("id") String appId); WechatConfig getConfigByAppId(@PathVariable("id") String appId);
/** @GetMapping(value = "/wechat/config/serial/{serialNumber}")
* feign rpc访问远程/wechat/config/{type}接口 WechatConfig getConfigBySerialNumber(@PathVariable("serialNumber") String serialNumber);
* 查询微信配置对象WechatConfig
*
* @param type
* @return
*/
@GetMapping(value = "/wechat/config/{type}")
String getPrivateKey(@PathVariable("type") String type, @RequestParam("tenantId") String tenantId);
} }
@@ -28,8 +28,8 @@ public class WechatConfigServiceFallbackFactory implements FallbackFactory<Wecha
} }
@Override @Override
public String getPrivateKey(String type, String tenantId) { public WechatConfig getConfigBySerialNumber(String serialNumber) {
return ""; return null;
} }
@@ -4,6 +4,9 @@ import lombok.extern.slf4j.Slf4j;
import java.security.KeyFactory; import java.security.KeyFactory;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64; import java.util.Base64;
@@ -16,19 +19,59 @@ import java.util.Base64;
public class PrivateKeyUtils { public class PrivateKeyUtils {
public static PrivateKey getPrivateKey(String privateKeyStr) { public static PrivateKey getPrivateKey(String privateKeyStr) {
if (privateKeyStr == null || privateKeyStr.trim().isEmpty()) {
throw new IllegalArgumentException("私钥字符串不能为空");
}
// 检查是否是证书而不是私钥
if (privateKeyStr.contains("-----BEGIN CERTIFICATE-----")) {
throw new IllegalArgumentException("输入的是证书而不是私钥,请提供正确的私钥");
}
try { try {
// 移除所有可能的头部和尾部标记
String privateKeyPEM = privateKeyStr String privateKeyPEM = privateKeyStr
.replace("-----BEGIN PRIVATE KEY-----", "") .replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "") .replace("-----END PRIVATE KEY-----", "")
// 移除所有空白字符(包括换行符、制表符等)
.replaceAll("\\s+", ""); .replaceAll("\\s+", "");
byte[] decoded = Base64.getDecoder().decode(privateKeyPEM); byte[] decoded = Base64.getDecoder().decode(privateKeyPEM);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decoded); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decoded);
KeyFactory keyFactory = KeyFactory.getInstance("RSA"); KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePrivate(keySpec); return keyFactory.generatePrivate(keySpec);
} catch (IllegalArgumentException e) {
log.error("私钥格式错误: {}", e.getMessage());
throw new IllegalArgumentException("私钥格式错误: " + e.getMessage(), e);
} catch (Exception e) { } catch (Exception e) {
log.error("解析私钥失败", e); log.error("解析私钥失败,原始私钥字符串: {}", privateKeyStr, e);
throw new RuntimeException("解析私钥失败", e); throw new RuntimeException("解析私钥失败: " + e.getMessage(), e);
}
}
public static X509Certificate getCertificate(String certificateStr) {
if (certificateStr == null || certificateStr.trim().isEmpty()) {
throw new IllegalArgumentException("证书字符串不能为空");
}
// 检查是否是私钥而不是证书
if (certificateStr.contains("-----BEGIN PRIVATE KEY-----") ||
certificateStr.contains("-----BEGIN RSA PRIVATE KEY-----")) {
throw new IllegalArgumentException("输入的是私钥而不是证书,请提供正确的证书");
}
try {
String certificatePEM = certificateStr
.replace("-----BEGIN CERTIFICATE-----", "")
.replace("-----END CERTIFICATE-----", "")
.replaceAll("\\s+", "");
byte[] decoded = Base64.getDecoder().decode(certificatePEM);
CertificateFactory factory = CertificateFactory.getInstance("X.509");
return (X509Certificate) factory.generateCertificate(new java.io.ByteArrayInputStream(decoded));
} catch (CertificateException e) {
log.error("解析证书失败,原始证书字符串: {}", certificateStr, e);
throw new RuntimeException("解析证书失败: " + e.getMessage(), e);
} }
} }
} }
@@ -49,7 +49,7 @@ public class WechatAutoConfiguration {
return new WxMaServiceImpl() { return new WxMaServiceImpl() {
@Override @Override
public WxMaDefaultConfigImpl getWxMaConfig() { public WxMaDefaultConfigImpl getWxMaConfig() {
WechatConfig config = configService.getConfig("MINI", getCurrentTenantId()); WechatConfig config = configService.getConfig("PAY", getCurrentTenantId());
WxMaDefaultConfigImpl wxConfig = new WxMaDefaultConfigImpl(); WxMaDefaultConfigImpl wxConfig = new WxMaDefaultConfigImpl();
wxConfig.setAppid(config.getAppId()); wxConfig.setAppid(config.getAppId());
wxConfig.setSecret(config.getAppSecret()); wxConfig.setSecret(config.getAppSecret());
@@ -60,9 +60,9 @@ public class WechatAutoConfiguration {
@Bean @Bean
@ConditionalOnBean({WechatConfigService.class}) @ConditionalOnBean({WechatConfigService.class})
public WxPayConfigFactory wxPayConfigFactory(WechatConfigService configService) { public WxPayConfigFactory wxPayConfigFactory() {
log.info("WxPayConfigFactory被加载,tenantId:{}", getCurrentTenantId()); log.info("WxPayConfigFactory被加载,tenantId:{}", getCurrentTenantId());
return new WxPayConfigFactory(configService); return new WxPayConfigFactory();
} }
@Bean @Bean
@@ -7,9 +7,10 @@ import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.NotificationConfig; import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser; 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.JsapiServiceExtension;
import com.wechat.pay.java.service.refund.RefundService;
import com.wechat.pay.java.service.profitsharing.ProfitsharingService; import com.wechat.pay.java.service.profitsharing.ProfitsharingService;
import com.wechat.pay.java.service.refund.RefundService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -22,7 +23,8 @@ import java.util.concurrent.ThreadPoolExecutor;
@Slf4j @Slf4j
@Component @Component
public class WxPayConfigFactory { public class WxPayConfigFactory {
private final WechatConfigService configService; @Autowired
private WechatConfigService configService;
// 缓存各个服务的实例 // 缓存各个服务的实例
private final Map<String, Config> configCache = new ConcurrentHashMap<>(); private final Map<String, Config> configCache = new ConcurrentHashMap<>();
@@ -32,9 +34,6 @@ public class WxPayConfigFactory {
private final Map<String, ProfitsharingService> profitsharingServiceCache = new ConcurrentHashMap<>(); private final Map<String, ProfitsharingService> profitsharingServiceCache = new ConcurrentHashMap<>();
private final Map<String, Executor> executorCache = new ConcurrentHashMap<>(); private final Map<String, Executor> executorCache = new ConcurrentHashMap<>();
public WxPayConfigFactory(WechatConfigService configService) {
this.configService = configService;
}
public Config createConfig(String tenantId) { public Config createConfig(String tenantId) {
return configCache.computeIfAbsent(tenantId, this::buildConfig); return configCache.computeIfAbsent(tenantId, this::buildConfig);