AuthTaobaoRequest.java 2.4 KB
Newer Older
1 2 3 4 5 6
package me.zhyd.oauth.request;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.config.AuthConfig;
7
import me.zhyd.oauth.config.AuthSource;
8
import me.zhyd.oauth.exception.AuthException;
9
import me.zhyd.oauth.model.AuthCallback;
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.model.AuthUserGender;
import me.zhyd.oauth.utils.GlobalAuthUtil;
import me.zhyd.oauth.utils.UrlBuilder;

/**
 * 淘宝登录
 *
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
 * @version 1.0
 * @since 1.8
 */
public class AuthTaobaoRequest extends BaseAuthRequest {

    public AuthTaobaoRequest(AuthConfig config) {
        super(config, AuthSource.TAOBAO);
    }

    @Override
30 31
    protected AuthToken getAccessToken(AuthCallback authCallback) {
        return AuthToken.builder().accessCode(authCallback.getCode()).build();
32 33 34 35 36
    }

    @Override
    protected AuthUser getUserInfo(AuthToken authToken) {
        String accessCode = authToken.getAccessCode();
37 38
        HttpResponse response = HttpRequest.post(UrlBuilder.getTaobaoAccessTokenUrl(this.config.getClientId(), this.config
                .getClientSecret(), accessCode, this.config.getRedirectUri())).execute();
39 40 41 42 43 44 45 46 47 48 49 50
        JSONObject object = JSONObject.parseObject(response.body());
        if (object.containsKey("error")) {
            throw new AuthException(ResponseStatus.FAILURE + ":" + object.getString("error_description"));
        }
        authToken.setAccessToken(object.getString("access_token"));
        authToken.setRefreshToken(object.getString("refresh_token"));
        authToken.setExpireIn(object.getIntValue("expires_in"));
        authToken.setUid(object.getString("taobao_user_id"));
        authToken.setOpenId(object.getString("taobao_open_uid"));

        String nick = GlobalAuthUtil.urlDecode(object.getString("taobao_user_nick"));
        return AuthUser.builder()
智布道's avatar
智布道 已提交
51
                .uuid(object.getString("taobao_user_id"))
52 53 54 55 56 57 58
                .username(nick)
                .nickname(nick)
                .gender(AuthUserGender.UNKNOW)
                .token(authToken)
                .source(AuthSource.TAOBAO)
                .build();
    }
59 60 61 62 63 64 65 66 67 68

    /**
     * 返回认证url,可自行跳转页面
     *
     * @return 返回授权地址
     */
    @Override
    public String authorize() {
        return UrlBuilder.getTaobaoAuthorizeUrl(config.getClientId(), config.getRedirectUri());
    }
69
}