Administrator
2024-02-26 b5b296cc01699f96029b07073fe9d0078bedd445
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.dy.pipirrWebChat.config;
 
import com.dy.pipirrWebChat.payment.PayInfo;
import okhttp3.OkHttpClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
 
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
 
/**
 * @author ZhuBaoMin
 * @date 2024-02-23 19:18
 * @LastEditTime 2024-02-23 19:18
 * @Description
 */
 
@Configuration
public class RestTemplateWechatCertConfig {
    String mchid = PayInfo.mchid;
 
    @Bean
    @ConfigurationProperties(prefix = "org.liurb.core.rest-template.config.connection")
    public ClientHttpRequestFactory wechatHttpRequestFactory() throws Exception {
 
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        //InputStream cp = this.getClass().getResourceAsStream("apiclient_cert.p12");
        FileInputStream instream = new FileInputStream(new File("C:\\webchat\\apiclient_cert.p12"));
        keyStore.load(instream, mchid.toCharArray());
 
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, mchid.toCharArray());
 
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), null, null);
 
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .sslSocketFactory(context.getSocketFactory(), getDefaultX509TrustManager())
                .build();
 
        return new OkHttp3ClientHttpRequestFactory(okHttpClient);
    }
 
    private static X509TrustManager getDefaultX509TrustManager() throws Exception {
        TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        factory.init((KeyStore) null);
        return (X509TrustManager) factory.getTrustManagers()[0];
    }
}