AuthAlipayRequest.java 5.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 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 42
        super(config, AuthDefaultSource.ALIPAY, authStateCache);
        this.alipayClient = new DefaultAlipayClient(AuthDefaultSource.ALIPAY.accessToken(), config.getClientId(), config.getClientSecret(), "json", "UTF-8", config
43 44 45
            .getAlipayPublicKey(), "RSA2");
    }

46
    @Override
47
    protected AuthToken getAccessToken(AuthCallback authCallback) {
48 49
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setGrantType("authorization_code");
智布道's avatar
智布道 已提交
50
        request.setCode(authCallback.getAuth_code());
51 52 53 54
        AlipaySystemOauthTokenResponse response = null;
        try {
            response = this.alipayClient.execute(request);
        } catch (Exception e) {
智布道's avatar
智布道 已提交
55
            throw new AuthException(e);
56 57 58 59
        }
        if (!response.isSuccess()) {
            throw new AuthException(response.getSubMsg());
        }
60
        return AuthToken.builder()
不合群的混子's avatar
不合群的混子 已提交
61 62 63 64 65
            .accessToken(response.getAccessToken())
            .uid(response.getUserId())
            .expireIn(Integer.parseInt(response.getExpiresIn()))
            .refreshToken(response.getRefreshToken())
            .build();
66 67
    }

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
    /**
     * 刷新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();
    }

99
    @Override
100 101
    protected AuthUser getUserInfo(AuthToken authToken) {
        String accessToken = authToken.getAccessToken();
102 103 104 105 106 107 108 109 110 111
        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
智布道 已提交
112

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

116
        return AuthUser.builder()
117
            .rawUserInfo(JSONObject.parseObject(JSONObject.toJSONString(response)))
不合群的混子's avatar
不合群的混子 已提交
118 119 120 121 122 123 124
            .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)
125
            .source(source.toString())
不合群的混子's avatar
不合群的混子 已提交
126 127 128 129
            .build();
    }

    /**
130
     * 返回带{@code state}参数的授权url,授权回调时会带上这个{@code state}
不合群的混子's avatar
不合群的混子 已提交
131
     *
132
     * @param state state 验证授权流程的参数,可以防止csrf
不合群的混子's avatar
不合群的混子 已提交
133
     * @return 返回授权地址
智布道's avatar
智布道 已提交
134
     * @since 1.9.3
不合群的混子's avatar
不合群的混子 已提交
135 136
     */
    @Override
137
    public String authorize(String state) {
不合群的混子's avatar
不合群的混子 已提交
138 139 140 141
        return UrlBuilder.fromBaseUrl(source.authorize())
            .queryParam("app_id", config.getClientId())
            .queryParam("scope", "auth_user")
            .queryParam("redirect_uri", config.getRedirectUri())
142
            .queryParam("state", getRealState(state))
不合群的混子's avatar
不合群的混子 已提交
143
            .build();
144 145
    }
}