yanderong
2026-06-04 e8e076edd31310b5f00cef45a560d485d0b4e3fb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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();
    }
}