package com.stylefeng.guns.config.pay; import com.stylefeng.guns.config.properties.WxPayProperties; import com.wechat.pay.java.core.Config; import com.wechat.pay.java.core.RSAAutoCertificateConfig; import com.wechat.pay.java.service.payments.app.AppService; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.util.StreamUtils; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; /** * 微信支付配置 * * @author Lux * @version 1.0.0 * @since 2026/6/3 14:23 */ @Configuration @RequiredArgsConstructor public class WechatPayConfig { private final WxPayProperties properties; private final ResourceLoader resourceLoader; @Bean public Config wxPayConfig() throws IOException { // 1. 读取 classpath 下的私钥文件内容(兼容 classpath: 前缀) Resource resource = resourceLoader.getResource(properties.getPrivateKeyPath()); String privateKey; try (InputStream inputStream = resource.getInputStream()) { // 使用 Spring 的 StreamUtils 将 InputStream 所有字节读取到 byte[],兼容 Java 8 byte[] keyBytes = StreamUtils.copyToByteArray(inputStream); privateKey = new String(keyBytes, StandardCharsets.UTF_8); } // 使用自动更新平台证书的RSA配置(从classpath读取私钥文件) return new RSAAutoCertificateConfig.Builder() .merchantId(properties.getMchId()) .privateKey(privateKey) .merchantSerialNumber(properties.getMerchantSerialNumber()) .apiV3Key(properties.getApiV3Key()) .build(); } @Bean public AppService appService(Config wxPayConfig) { return new AppService.Builder() .config(wxPayConfig) .build(); } }