AuthElemeRequest.java 6.9 KB
Newer Older
1 2 3
package me.zhyd.oauth.request;

import com.alibaba.fastjson.JSONObject;
智布道's avatar
智布道 已提交
4
import me.zhyd.oauth.utils.HttpUtils;
5 6
import com.xkcoding.http.constants.Constants;
import com.xkcoding.http.support.HttpHeader;
7 8
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
9
import me.zhyd.oauth.config.AuthDefaultSource;
10 11 12 13 14 15 16
import me.zhyd.oauth.enums.AuthResponseStatus;
import me.zhyd.oauth.enums.AuthUserGender;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
17 18
import me.zhyd.oauth.utils.Base64Utils;
import me.zhyd.oauth.utils.GlobalAuthUtils;
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
import me.zhyd.oauth.utils.UrlBuilder;
import me.zhyd.oauth.utils.UuidUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 饿了么
 * <p>
 * 注:集成的是正式环境,非沙箱环境
 *
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
 * @since 1.12.0
 */
public class AuthElemeRequest extends AuthDefaultRequest {

35 36 37
    private static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded;charset=UTF-8";
    private static final String CONTENT_TYPE_JSON = "application/json; charset=utf-8";

38
    public AuthElemeRequest(AuthConfig config) {
39
        super(config, AuthDefaultSource.ELEME);
40 41 42
    }

    public AuthElemeRequest(AuthConfig config, AuthStateCache authStateCache) {
43
        super(config, AuthDefaultSource.ELEME, authStateCache);
44 45 46 47
    }

    @Override
    protected AuthToken getAccessToken(AuthCallback authCallback) {
48
        Map<String, String> form = new HashMap<>(7);
49 50 51 52
        form.put("client_id", config.getClientId());
        form.put("redirect_uri", config.getRedirectUri());
        form.put("code", authCallback.getCode());
        form.put("grant_type", "authorization_code");
53

54
        HttpHeader httpHeader = this.buildHeader(CONTENT_TYPE_FORM, this.getRequestId(), true);
55
        String response = new HttpUtils(config.getHttpConfig()).post(source.accessToken(), form, httpHeader, false).getBody();
56
        JSONObject object = JSONObject.parseObject(response);
57 58 59 60 61 62 63 64 65 66 67 68 69

        this.checkResponse(object);

        return AuthToken.builder()
            .accessToken(object.getString("access_token"))
            .refreshToken(object.getString("refresh_token"))
            .tokenType(object.getString("token_type"))
            .expireIn(object.getIntValue("expires_in"))
            .build();
    }

    @Override
    protected AuthUser getUserInfo(AuthToken authToken) {
70
        Map<String, Object> parameters = new HashMap<>(4);
71 72 73 74 75
        // 获取商户账号信息的API接口名称
        String action = "eleme.user.getUser";
        // 时间戳,单位秒。API服务端允许客户端请求最大时间误差为正负5分钟。
        final long timestamp = System.currentTimeMillis();
        // 公共参数
76
        Map<String, Object> metasHashMap = new HashMap<>(4);
77 78
        metasHashMap.put("app_key", config.getClientId());
        metasHashMap.put("timestamp", timestamp);
79 80
        String signature = GlobalAuthUtils.generateElemeSignature(config.getClientId(), config.getClientSecret(), timestamp, action, authToken
            .getAccessToken(), parameters);
81

智布道's avatar
智布道 已提交
82 83 84 85 86 87 88 89 90 91 92
        String requestId = this.getRequestId();

        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("nop", "1.0.0");
        paramsMap.put("id", requestId);
        paramsMap.put("action", action);
        paramsMap.put("token", authToken.getAccessToken());
        paramsMap.put("metas", metasHashMap);
        paramsMap.put("params", parameters);
        paramsMap.put("signature", signature);

93
        HttpHeader httpHeader = this.buildHeader(CONTENT_TYPE_JSON, requestId, false);
94
        String response = new HttpUtils(config.getHttpConfig()).post(source.userInfo(), JSONObject.toJSONString(paramsMap), httpHeader).getBody();
95

96
        JSONObject object = JSONObject.parseObject(response);
97 98

        // 校验请求
智布道's avatar
智布道 已提交
99 100 101 102
        if (object.containsKey("name")) {
            throw new AuthException(object.getString("message"));
        }
        if (object.containsKey("error") && null != object.get("error")) {
103 104 105 106 107 108
            throw new AuthException(object.getJSONObject("error").getString("message"));
        }

        JSONObject result = object.getJSONObject("result");

        return AuthUser.builder()
109
            .rawUserInfo(result)
110 111 112 113 114
            .uuid(result.getString("userId"))
            .username(result.getString("userName"))
            .nickname(result.getString("userName"))
            .gender(AuthUserGender.UNKNOWN)
            .token(authToken)
115
            .source(source.toString())
116 117 118 119 120
            .build();
    }

    @Override
    public AuthResponse refresh(AuthToken oldToken) {
121
        Map<String, String> form = new HashMap<>(4);
122 123
        form.put("refresh_token", oldToken.getRefreshToken());
        form.put("grant_type", "refresh_token");
124

125
        HttpHeader httpHeader = this.buildHeader(CONTENT_TYPE_FORM, this.getRequestId(), true);
126
        String response = new HttpUtils(config.getHttpConfig()).post(source.refresh(), form, httpHeader, false).getBody();
127

128
        JSONObject object = JSONObject.parseObject(response);
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144

        this.checkResponse(object);

        return AuthResponse.builder()
            .code(AuthResponseStatus.SUCCESS.getCode())
            .data(AuthToken.builder()
                .accessToken(object.getString("access_token"))
                .refreshToken(object.getString("refresh_token"))
                .tokenType(object.getString("token_type"))
                .expireIn(object.getIntValue("expires_in"))
                .build())
            .build();
    }

    @Override
    public String authorize(String state) {
145
        return UrlBuilder.fromBaseUrl(super.authorize(state)).queryParam("scope", "all").build();
146 147 148 149
    }

    private String getBasic(String appKey, String appSecret) {
        StringBuilder sb = new StringBuilder();
150
        String encodeToString = Base64Utils.encode((appKey + ":" + appSecret).getBytes());
151 152 153 154
        sb.append("Basic").append(" ").append(encodeToString);
        return sb.toString();
    }

155 156 157 158 159 160 161 162 163 164 165
    private HttpHeader buildHeader(String contentType, String requestId, boolean auth) {
        HttpHeader httpHeader = new HttpHeader();
        httpHeader.add("Accept", "text/xml,text/javascript,text/html");
        httpHeader.add(Constants.CONTENT_TYPE, contentType);
        httpHeader.add("Accept-Encoding", "gzip");
        httpHeader.add("User-Agent", "eleme-openapi-java-sdk");
        httpHeader.add("x-eleme-requestid", requestId);
        if (auth) {
            httpHeader.add("Authorization", this.getBasic(config.getClientId(), config.getClientSecret()));
        }
        return httpHeader;
166 167 168
    }

    private String getRequestId() {
智布道's avatar
智布道 已提交
169
        return (UuidUtils.getUUID() + "|" + System.currentTimeMillis()).toUpperCase();
170 171 172 173 174 175 176 177 178
    }

    private void checkResponse(JSONObject object) {
        if (object.containsKey("error")) {
            throw new AuthException(object.getString("error_description"));
        }
    }

}