package com.zcloud.common.wxpay;

import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;

/**
 * @author fangjiakai
 * @date 2023/12/13 10:21
 */
@Component
public class WxBeanUtils {
    @Resource
    private WxPayBean wxPayBean;

    public CloseableHttpClient initHttpClient() {
        CloseableHttpClient httpClient;
        AutoUpdateCertificatesVerifier verifier;
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(wxPayBean.getPrivateKey());

        verifier = new AutoUpdateCertificatesVerifier(
                new WechatPay2Credentials(wxPayBean.getMchId(), new PrivateKeySigner(wxPayBean.getMchSerialNo(), merchantPrivateKey)),
                wxPayBean.getApiv3Key().getBytes(StandardCharsets.UTF_8));

        httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(wxPayBean.getMchId(), wxPayBean.getMchSerialNo(), merchantPrivateKey )
                .withValidator(new WechatPay2Validator(verifier))
                .build();
        return httpClient;
    }
}
