package com.buy507.mall.portal.pay.alipay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.InputStream;

@Configuration
public class AlipayConfig {

    @Value("${alipay.appId}")
    private String appId;

    @Value("${alipay.appPrivateKey}")
    private String appPrivateKey;

    @Value("${alipay.alipayPublicKey}")
    private String alipayPublicKey;

    @Value("${alipay.serverUrl}")
    private String serverUrl;

    @Value("${alipay.format}")
    private String format;

    @Value("${alipay.charset}")
    private String charset;

    @Value("${alipay.signType}")
    private String signType;

    @Bean
    public AlipayClient alipayClient() throws AlipayApiException {
        //构造client
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
//设置网关地址
        certAlipayRequest.setServerUrl(serverUrl);
//设置应用Id
        certAlipayRequest.setAppId(appId);
//设置应用私钥
        certAlipayRequest.setPrivateKey(appPrivateKey);
//设置请求格式，固定值json
        certAlipayRequest.setFormat("json");
//设置字符集
        certAlipayRequest.setCharset(charset);
//设置签名类型
        certAlipayRequest.setSignType(signType);
//设置应用公钥证书路径
        //String ertPath = System.getProperty("user.dir") + File.separator + "alipay_cert_sn";
        //certAlipayRequest.setCertPath("D:work/cert/appCertPublicKey_2021004185651069.crt");
        certAlipayRequest.setCertContent(getCertContentByPath("appCertPublicKey_2021004185651069.crt"));
//设置支付宝公钥证书路径
        certAlipayRequest.setAlipayPublicCertContent(getCertContentByPath("alipayCertPublicKey_RSA2.crt"));
//设置支付宝根证书路径
        certAlipayRequest.setRootCertContent(getCertContentByPath("alipayRootCert.crt"));
        //return new DefaultAlipayClient(serverUrl, appId, appPrivateKey, format, charset, alipayPublicKey, signType);
        AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        return alipayClient;
    }


    public String getCertContentByPath(String name){
        InputStream inputStream = null;
        String content = null;
        try{
            inputStream = this.getClass().getClassLoader().getResourceAsStream(name);
            content = new String(FileCopyUtils.copyToByteArray(inputStream));
        }catch (Exception e){
            e.printStackTrace();
        }
        return content;
    }

}

