package cn.pluss.platform.util;

import cn.pluss.platform.exception.MsgException;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;

import java.util.HashMap;
import java.util.Map;

/**
 *
 *@description:支付宝工具类
 *@author: bzg
 *@time: 2021/10/8 17:41
 */

public class AliUtil {


//    public static Map<String, Object> getAliUserId(String auth_code,String priKey,String pubKey,String appId) {
//        Map<String, Object> result = new HashMap<>(2);
//        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId,
//                priKey, "json", "GBK", pubKey, "RSA2");
//        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
//        request.setCode(auth_code);
//        request.setGrantType("authorization_code");
//        try {
//            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
//            result.put("aliUserId", oauthTokenResponse.getUserId());
//            result.put("accessToken", oauthTokenResponse.getAccessToken());
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//        }
//        return result;
//    }

    public static AlipaySystemOauthTokenResponse getAliUserIdV2(String auth_code,String priKey,String pubKey,String appId) {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId,
                priKey, "json", "GBK", pubKey, "RSA2");
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setCode(auth_code);
        request.setGrantType("authorization_code");
        try {
            AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
            if(!response.isSuccess()){
                MsgException.throwException("支付宝授权失败");
            }
            return response;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            MsgException.throwException("支付宝授权异常");
            return null;
        }
    }
}
