package cn.hanghui.outapi.platform.alipay.api;

import cn.hanghui.outapi.platform.common.exception.CommonException;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayOpenAuthTokenAppRequest;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipayOpenAuthTokenAppResponse;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@AllArgsConstructor(onConstructor_ = @Autowired)
@Slf4j
public class AlipayCommonApi {

    /**
     * 用户授权码换取accessToken
     *
     * @param alipayClient AlipayClient
     * @param authCode     授权码
     * @return AccessToken
     */
    public String getAccessToken(AlipayClient alipayClient, String authCode, String thirdAppAuthToken) {
        try {
            AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
            request.setGrantType("authorization_code");
            request.setCode(authCode);
            AlipaySystemOauthTokenResponse response = alipayClient.execute(request, null, thirdAppAuthToken);
            if (!response.isSuccess()) {
                throw new CommonException("获取支付宝AccessToken失败：" + response.getMsg() + "," + response.getSubMsg());
            }
            return response.getAccessToken();
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonException("调用支付宝服务异常", e);
        }
    }

    /**
     * alipay.open.auth.token.app(换取应用授权令牌)
     *
     * @param alipayClient
     * @param appAuthCode
     * @return
     */
    public String getOpenAuthToken(AlipayClient alipayClient, String appAuthCode) {
        try {
            AlipayOpenAuthTokenAppRequest request = new AlipayOpenAuthTokenAppRequest();
            JSONObject obj = new JSONObject();
            obj.put("grant_type", "authorization_code");
            obj.put("code", appAuthCode);
            request.setBizContent(obj.toJSONString());
            AlipayOpenAuthTokenAppResponse response = alipayClient.execute(request);
            log.info("--->换取应用授权令牌响应参数:{}", JSONObject.toJSONString(response));
            if (!response.isSuccess()) {
                throw new CommonException("换取应用授权令牌失败：" + response.getMsg() + "," + response.getSubMsg());
            }
            return response.getAppAuthToken();
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonException("换取应用授权令牌服务异常", e);
        }
    }


}
