文章目录
前言
PC
端的钉钉
中工作台
,增加第三方应用,实现点击后自动授权登录逻辑。
准备
1、创建钉钉应用,并开放网页应用
2、配置网页应用各项参数
https://ip:port/#/midPageDingTalk?apiParams=
$CORPID$
发布版本
前端改造
参考官方文档requestAuthCode
当点击站内的应用后,钉钉会按照配置页面地址,自动进入到配置的前端页面中。此时前端页面中增加一些逻辑,用来获取随机码AuthCode
。
dd.requestAuthCode({
corpId: 'corpid',
clientId: 'clientid',
onSuccess: function (result) {
/*{
code: 'hYLK98jkf0m' //string authCode
}*/
},
onFail: function (err) {},
});
返回数据样例:
{ "code": "fea65576013237fba6ca6c5b16a85ff5" }
后端逻辑
主体逻辑可以参考官方文档中给出的demo,但有坑,已自己踩过。
1、获取应用免登录 Access_token
官方给出的这个案例中,不存在对应的GetTokenRequest
对象,但整体逻辑可以使用下面这个做替换。
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import lombok.extern.slf4j.Slf4j;
/**
* https://open.dingtalk.com/document/orgapp/obtain-the-access_token-of-an-internal-app
*/
@Slf4j
public class GetAccessTokenDemo {
/**
* 使用 Token 初始化账号Client
* @return Client
* @throws Exception
*/
public static com.aliyun.dingtalkoauth2_1_0.Client createClient() throws Exception {
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
config.protocol = "https";
config.regionId = "central";
return new com.aliyun.dingtalkoauth2_1_0.Client(config);
}
public static void main(String[] args) throws Exception {
com.aliyun.dingtalkoauth2_1_0.Client client = createClient();
com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest getAccessTokenRequest = new com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest()
.setAppKey("应用clientId")
.setAppSecret("应用 Client Secret ");
GetAccessTokenResponse accessToken = client.getAccessToken(getAccessTokenRequest);
log.info("请求回执信息:{}", JSONObject.toJSONString(accessToken.getBody()));
// {"accessToken":"6315e4d453583c69b1fb89ae455ba772","expireIn":7200}
System.out.println(accessToken.getBody().accessToken);
}
}
2、通过免登录 Access_token 和 Auth_Code 获取对应登录人信息
官方文档:通过免登码获取用户信息
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiV2UserGetuserinfoRequest;
import com.dingtalk.api.response.OapiV2UserGetuserinfoResponse;
import com.taobao.api.ApiException;
public class GetUserInfo {
public static void main(String[] args) throws ApiException {
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo");
OapiV2UserGetuserinfoRequest req = new OapiV2UserGetuserinfoRequest();
req.setCode("钉钉返回给出的 authcode 值");
OapiV2UserGetuserinfoResponse rsp = client.execute(req, "获取到的 access_token 值");
System.out.println(rsp.getBody());
}
}
返回数据案例:
{
"errcode": 0,
"result": {
"associated_unionid": "N2o5U3axxxx",
"unionid": "gliiW0piiii02zBUjUxxxx",
"device_id": "12drtfxxxxx",
"sys_level": 1,
"name": "张xx",
"sys": true,
"userid": "userid123"
},
"errmsg": "ok"
}
注意事项
钉钉开发中心中配置项,配置完成后想要钉钉工作台中出现指定的入口,必须进行发布
操作。只有发布成功后才会生效。