AuthDingTalkRequest.java 2.0 KB
Newer Older
智布道's avatar
智布道 已提交
1 2 3 4 5 6
package me.zhyd.oauth.request;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import me.zhyd.oauth.config.AuthConfig;
7 8
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthDingTalkErrorCode;
智布道's avatar
智布道 已提交
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthSource;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.utils.DingTalkSignatureUtil;
import me.zhyd.oauth.utils.UrlBuilder;

import java.util.Objects;

/**
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
 * @version 1.0
 * @website https://www.zhyd.me
 * @date 2019/2/18 18:43
 * @since 1.8
 */
public class AuthDingTalkRequest extends BaseAuthRequest {

    public AuthDingTalkRequest(AuthConfig config) {
27
        super(config, AuthSource.DINGTALK);
智布道's avatar
智布道 已提交
28 29 30
    }

    @Override
31
    protected AuthUser getUserInfo(String code) {
智布道's avatar
智布道 已提交
32 33 34 35 36 37 38 39
        // 根据timestamp, appSecret计算签名值
        String stringToSign = System.currentTimeMillis() + "";
        String urlEncodeSignature = DingTalkSignatureUtil.computeSignature(config.getClientSecret(), stringToSign);
        HttpResponse response = HttpRequest.post(UrlBuilder.getDingTalkUserInfoUrl(urlEncodeSignature, stringToSign, config.getClientId()))
                .body(Objects.requireNonNull(new JSONObject().put("tmp_auth_code", code)))
                .execute();
        String userInfo = response.body();
        JSONObject object = new JSONObject(userInfo);
40 41 42
        AuthDingTalkErrorCode errorCode = AuthDingTalkErrorCode.getErrorCode(object.getInt("errcode"));
        if (!AuthDingTalkErrorCode.EC0.equals(errorCode)) {
            throw new AuthException(errorCode.getDesc());
智布道's avatar
智布道 已提交
43 44
        }
        object = object.getJSONObject("user_info");
45 46 47 48 49 50 51 52
        return AuthUser.builder()
                .nickname(object.getStr("nick"))
                .source(AuthSource.DINGTALK)
                .build();
    }

    @Override
    public AuthResponse login(String code) {
智布道's avatar
智布道 已提交
53
        return AuthResponse.builder()
54
                .data(this.getUserInfo(code))
智布道's avatar
智布道 已提交
55 56 57
                .build();
    }
}