package org.jeecg.modules.pay.paytest;

import com.alibaba.fastjson2.JSONObject;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.http.*;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;

@Slf4j
public class WxPayUtils {

    /**
     * 下载证书
     */
    public void downLoadCertificates() {
        OkHttpClient okHttpClient = new OkHttpClient();
        HttpClient httpClient = new DefaultHttpClientBuilder()
                .config(rsaAutoCertificateConfig())
                .okHttpClient(okHttpClient)
                .build();
        HttpHeaders headers = new HttpHeaders();
        headers.addHeader("Accept", MediaType.APPLICATION_JSON.getValue());
        HttpRequest executeSendGetHttpRequest = new HttpRequest.Builder()
                .httpMethod(HttpMethod.GET)
                .url("https://api.mch.weixin.qq.com/v3/certificates")
                .headers(headers)
                .build();
        try {
            HttpResponse<JSONObject> execute = httpClient.execute(executeSendGetHttpRequest, JSONObject.class);
            JSONObject responseBody = execute.getServiceResponse();
            log.info("下载平台证书返回:{}", responseBody.toString());
        } catch (Exception e) {
            log.error("下载平台证书异常", e);
        }
    }

    /**
     * API安全加密配置
     */
    private RSAAutoCertificateConfig rsaAutoCertificateConfig() {
        return new RSAAutoCertificateConfig.Builder()
                // 商户号
                .merchantId("xxxxxxxxxxx")
                // 商户API证书私钥的存放路径
                .privateKeyFromPath("v3/apiclient_key.pem")
                // 商户API证书序列号
                .merchantSerialNumber("xxxxxxxxxxx")
                // APIv3密钥
                .apiV3Key("xxxxxxxxxxx")
                .build();
    }
}
