package com.hys.app.pay.ali;

import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

@Service
public class AliPayService {
    @Resource
    private AliConfig alipayConfig1;

    public String pay(PayOrder payOrder) {
        try {
            AlipayConfig alipayConfig = new AlipayConfig();
            alipayConfig.setServerUrl(alipayConfig1.getServerUrl());
            alipayConfig.setAppId(alipayConfig1.getAppId());
            alipayConfig.setPrivateKey(alipayConfig1.getAppPrivateKey());
            alipayConfig.setFormat(alipayConfig1.getFormat());
            alipayConfig.setAlipayPublicKey(alipayConfig1.getAlipayPublicKey());
            alipayConfig.setCharset(alipayConfig1.getCharset());
            alipayConfig.setSignType(alipayConfig1.getSignType());

            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
            AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
            AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
            model.setOutTradeNo(payOrder.getTraceNo());
            model.setTotalAmount(payOrder.getTotalAmount().toString());
            model.setSubject(payOrder.getSubject());
            request.setBizModel(model);
            request.setNotifyUrl(alipayConfig1.getNotifyUrl());
            AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "GET");
            // 如果需要返回GET请求，请使用
            // AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "GET");
            String pageRedirectionData = response.getBody();
            System.out.println(pageRedirectionData);





            if (response.isSuccess()) {
                return response.getBody();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

        public Boolean checkReturnParam (Map < String, String > map){
            try {
                return AlipaySignature.rsaCheckV1(map, alipayConfig1.getAlipayPublicKey(), alipayConfig1.getCharset(), alipayConfig1.getSignType());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }

}