AuthAlipayRequest.java 6.4 KB
Newer Older
1 2
package me.zhyd.oauth.request;

3
import com.alibaba.fastjson.JSONObject;
4 5 6 7 8 9 10
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.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
11
import me.zhyd.oauth.cache.AuthStateCache;
12
import me.zhyd.oauth.config.AuthConfig;
13
import me.zhyd.oauth.config.AuthDefaultSource;
14
import me.zhyd.oauth.enums.AuthResponseStatus;
智布道's avatar
智布道 已提交
15
import me.zhyd.oauth.enums.AuthUserGender;
16
import me.zhyd.oauth.exception.AuthException;
17
import me.zhyd.oauth.model.AuthCallback;
18
import me.zhyd.oauth.model.AuthResponse;
19
import me.zhyd.oauth.model.AuthToken;
20 21
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.utils.StringUtils;
不合群的混子's avatar
不合群的混子 已提交
22
import me.zhyd.oauth.utils.UrlBuilder;
23 24

/**
25 26
 * 支付宝登录
 *
27
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
智布道's avatar
智布道 已提交
28
 * @since 1.0.1
29
 */
智布道's avatar
智布道 已提交
30
public class AuthAlipayRequest extends AuthDefaultRequest {
31 32 33 34

    private AlipayClient alipayClient;

    public AuthAlipayRequest(AuthConfig config) {
35 36
        super(config, AuthDefaultSource.ALIPAY);
        this.alipayClient = new DefaultAlipayClient(AuthDefaultSource.ALIPAY.accessToken(), config.getClientId(), config.getClientSecret(), "json", "UTF-8", config
不合群的混子's avatar
不合群的混子 已提交
37
            .getAlipayPublicKey(), "RSA2");
38 39
    }

40
    public AuthAlipayRequest(AuthConfig config, AuthStateCache authStateCache) {
41
        super(config, AuthDefaultSource.ALIPAY, authStateCache);
cly_0's avatar
1  
cly_0 已提交
42 43 44 45 46 47 48
        if(StringUtils.isNotEmpty(config.getProxyHost()) && config.getProxyPort()!=null){
            this.alipayClient = new DefaultAlipayClient(AuthDefaultSource.ALIPAY.accessToken(), config.getClientId(), config.getClientSecret(),
                "json", "UTF-8", config.getAlipayPublicKey(), "RSA2", config.getProxyHost(), config.getProxyPort());
        }else{
            this.alipayClient = new DefaultAlipayClient(AuthDefaultSource.ALIPAY.accessToken(), config.getClientId(), config.getClientSecret(), "json", "UTF-8", config
                .getAlipayPublicKey(), "RSA2");
        }
49 50
    }

51 52 53 54 55 56
    public AuthAlipayRequest(AuthConfig config, AuthStateCache authStateCache, String proxyHost, Integer proxyPort) {
        super(config, AuthDefaultSource.ALIPAY, authStateCache);
        this.alipayClient = new DefaultAlipayClient(AuthDefaultSource.ALIPAY.accessToken(), config.getClientId(), config.getClientSecret(),
            "json", "UTF-8", config.getAlipayPublicKey(), "RSA2", proxyHost, proxyPort);
    }

57
    @Override
58
    protected AuthToken getAccessToken(AuthCallback authCallback) {
59 60
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setGrantType("authorization_code");
智布道's avatar
智布道 已提交
61
        request.setCode(authCallback.getAuth_code());
62 63 64 65
        AlipaySystemOauthTokenResponse response = null;
        try {
            response = this.alipayClient.execute(request);
        } catch (Exception e) {
智布道's avatar
智布道 已提交
66
            throw new AuthException(e);
67 68 69 70
        }
        if (!response.isSuccess()) {
            throw new AuthException(response.getSubMsg());
        }
71
        return AuthToken.builder()
不合群的混子's avatar
不合群的混子 已提交
72 73 74 75 76
            .accessToken(response.getAccessToken())
            .uid(response.getUserId())
            .expireIn(Integer.parseInt(response.getExpiresIn()))
            .refreshToken(response.getRefreshToken())
            .build();
77 78
    }

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
    /**
     * 刷新access token (续期)
     *
     * @param authToken 登录成功后返回的Token信息
     * @return AuthResponse
     */
    @Override
    public AuthResponse refresh(AuthToken authToken) {
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setGrantType("refresh_token");
        request.setRefreshToken(authToken.getRefreshToken());
        AlipaySystemOauthTokenResponse response = null;
        try {
            response = this.alipayClient.execute(request);
        } catch (Exception e) {
            throw new AuthException(e);
        }
        if (!response.isSuccess()) {
            throw new AuthException(response.getSubMsg());
        }
        return AuthResponse.builder()
            .code(AuthResponseStatus.SUCCESS.getCode())
            .data(AuthToken.builder()
                .accessToken(response.getAccessToken())
                .uid(response.getUserId())
                .expireIn(Integer.parseInt(response.getExpiresIn()))
                .refreshToken(response.getRefreshToken())
                .build())
            .build();
    }

110
    @Override
111 112
    protected AuthUser getUserInfo(AuthToken authToken) {
        String accessToken = authToken.getAccessToken();
113 114 115 116 117 118 119 120 121 122
        AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
        AlipayUserInfoShareResponse response = null;
        try {
            response = this.alipayClient.execute(request, accessToken);
        } catch (AlipayApiException e) {
            throw new AuthException(e.getErrMsg(), e);
        }
        if (!response.isSuccess()) {
            throw new AuthException(response.getSubMsg());
        }
智布道's avatar
智布道 已提交
123

不合群的混子's avatar
不合群的混子 已提交
124
        String province = response.getProvince(), city = response.getCity();
智布道's avatar
智布道 已提交
125 126
        String location = String.format("%s %s", StringUtils.isEmpty(province) ? "" : province, StringUtils.isEmpty(city) ? "" : city);

127
        return AuthUser.builder()
128
            .rawUserInfo(JSONObject.parseObject(JSONObject.toJSONString(response)))
不合群的混子's avatar
不合群的混子 已提交
129 130 131 132 133 134 135
            .uuid(response.getUserId())
            .username(StringUtils.isEmpty(response.getUserName()) ? response.getNickName() : response.getUserName())
            .nickname(response.getNickName())
            .avatar(response.getAvatar())
            .location(location)
            .gender(AuthUserGender.getRealGender(response.getGender()))
            .token(authToken)
136
            .source(source.toString())
不合群的混子's avatar
不合群的混子 已提交
137 138 139 140
            .build();
    }

    /**
141
     * 返回带{@code state}参数的授权url,授权回调时会带上这个{@code state}
不合群的混子's avatar
不合群的混子 已提交
142
     *
143
     * @param state state 验证授权流程的参数,可以防止csrf
不合群的混子's avatar
不合群的混子 已提交
144
     * @return 返回授权地址
智布道's avatar
智布道 已提交
145
     * @since 1.9.3
不合群的混子's avatar
不合群的混子 已提交
146 147
     */
    @Override
148
    public String authorize(String state) {
不合群的混子's avatar
不合群的混子 已提交
149 150 151 152
        return UrlBuilder.fromBaseUrl(source.authorize())
            .queryParam("app_id", config.getClientId())
            .queryParam("scope", "auth_user")
            .queryParam("redirect_uri", config.getRedirectUri())
153
            .queryParam("state", getRealState(state))
不合群的混子's avatar
不合群的混子 已提交
154
            .build();
155 156
    }
}