AuthAlipayRequest.java 6.6 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

cly_0's avatar
还原  
cly_0 已提交
24 25
import java.net.InetSocketAddress;

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

    private AlipayClient alipayClient;

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

42
    public AuthAlipayRequest(AuthConfig config, AuthStateCache authStateCache) {
43
        super(config, AuthDefaultSource.ALIPAY, authStateCache);
cly_0's avatar
还原  
cly_0 已提交
44 45 46
        if (config.getHttpConfig() != null && config.getHttpConfig().getProxy() != null
            && config.getHttpConfig().getProxy().address() instanceof InetSocketAddress) {
            InetSocketAddress address = (InetSocketAddress) config.getHttpConfig().getProxy().address();
cly_0's avatar
1  
cly_0 已提交
47
            this.alipayClient = new DefaultAlipayClient(AuthDefaultSource.ALIPAY.accessToken(), config.getClientId(), config.getClientSecret(),
cly_0's avatar
还原  
cly_0 已提交
48
                "json", "UTF-8", config.getAlipayPublicKey(), "RSA2", address.getHostName(), address.getPort());
cly_0's avatar
cly_0 已提交
49
        } else {
cly_0's avatar
cly_0 已提交
50 51
            this.alipayClient = new DefaultAlipayClient(AuthDefaultSource.ALIPAY.accessToken(), config.getClientId(), config.getClientSecret(),
                "json", "UTF-8", config.getAlipayPublicKey(), "RSA2");
cly_0's avatar
1  
cly_0 已提交
52
        }
53 54
    }

55 56 57 58 59 60
    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);
    }

61
    @Override
62
    protected AuthToken getAccessToken(AuthCallback authCallback) {
63 64
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setGrantType("authorization_code");
智布道's avatar
智布道 已提交
65
        request.setCode(authCallback.getAuth_code());
cly_0's avatar
cly_0 已提交
66
        AlipaySystemOauthTokenResponse response;
67 68 69
        try {
            response = this.alipayClient.execute(request);
        } catch (Exception e) {
智布道's avatar
智布道 已提交
70
            throw new AuthException(e);
71 72 73 74
        }
        if (!response.isSuccess()) {
            throw new AuthException(response.getSubMsg());
        }
75
        return AuthToken.builder()
不合群的混子's avatar
不合群的混子 已提交
76 77 78 79 80
            .accessToken(response.getAccessToken())
            .uid(response.getUserId())
            .expireIn(Integer.parseInt(response.getExpiresIn()))
            .refreshToken(response.getRefreshToken())
            .build();
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 110 111 112 113
    /**
     * 刷新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();
    }

114
    @Override
115 116
    protected AuthUser getUserInfo(AuthToken authToken) {
        String accessToken = authToken.getAccessToken();
117 118 119 120 121 122 123 124 125 126
        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
智布道 已提交
127

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

131
        return AuthUser.builder()
132
            .rawUserInfo(JSONObject.parseObject(JSONObject.toJSONString(response)))
不合群的混子's avatar
不合群的混子 已提交
133 134 135 136 137 138 139
            .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)
140
            .source(source.toString())
不合群的混子's avatar
不合群的混子 已提交
141 142 143 144
            .build();
    }

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