package com.yami.shop.config;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import com.alipay.api.*;
import com.yami.shop.common.bean.Alipay;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Component
@AllArgsConstructor
public class AliPayConfig {

    private final ShopConfig shopConfig;

    public AlipayClient getAlipayClient() throws AlipayApiException {

        Alipay alipay = shopConfig.getAlipay();

        //构造client
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        //设置网关地址
        certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
        //设置应用Id
        certAlipayRequest.setAppId(alipay.getAppId());
        //设置应用私钥
        certAlipayRequest.setPrivateKey(alipay.getAppPrivateKey());
        //设置请求格式，固定值json
        certAlipayRequest.setFormat("json");
        //设置字符集
        certAlipayRequest.setCharset(CharsetUtil.UTF_8);
        //设置签名类型
        certAlipayRequest.setSignType(AlipayConstants.SIGN_TYPE_RSA2);

        //设置应用公钥证书路径
        certAlipayRequest.setCertPath(FileUtil.getAbsolutePath(alipay.getAppCertPath()));
        //设置支付宝公钥证书路径
        certAlipayRequest.setAlipayPublicCertPath(FileUtil.getAbsolutePath(alipay.getAlipayCertPath()));
        //设置支付宝根证书路径
        certAlipayRequest.setRootCertPath(FileUtil.getAbsolutePath(alipay.getAlipayRootCertPath()));
        //构造client
        return new DefaultAlipayClient(certAlipayRequest);
    }
}
