我这里采用前端获取免登录授权码,发给后端计算得到登录后的钉钉信息。
index.html
dd.ready(function() {
dd.runtime.permission.requestAuthCode({
corpId: "你的corpid",
onSuccess: function(info) {
code = info.code
axios.get('login.php?code='+code)
.then(function (response) {
}).catch(function (error) {
alert('something wrong')
});
},onFail : function(err) {
alert(err)
}
})
});
login.php
<?php
header('Content-type: application/json');
function request_by_curl($remote_server,$postStr) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $remote_server);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Content-Type: application/json;charset=utf-8'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
if($postStr != ''){
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postStr);
}
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$webhook = "https://oapi.dingtalk.com/gettoken?appkey=dingniusxv**********j&appsecret=xges_02fDh4gWjJABh4_7P*************gXLH8N6UL2W_1QX";
$result = request_by_curl($webhook,'');
echo $result;
$token = json_decode($result)->{'access_token'};
$code = $_GET['code'];
$postStr = "{\"code\": \"{$code}\"}";
$webhook = "https://oapi.dingtalk.com/topapi/v2/user/getuserinfo?access_token={$token}";
$result = request_by_curl($webhook,$postStr);
echo $result;
$userid = json_decode($result)->{'result'}->{'userid'};
$postStr = "{\"userid\": \"{$userid}\"}";
$webhook = "https://oapi.dingtalk.com/topapi/v2/user/get?access_token={$token}";
$result = request_by_curl($webhook,$postStr);
echo $result;
?>
这两个页面上传好,通过钉钉工作台访问内部应用后,就可以获得当前账号的信息了。
对照官方文档处理时遇到一个坑:
axios Error: Network Error
{"errcode":40078,"errmsg":"不存在的临时授权码"}
反复看了文档后,觉得没有任何问题。后来发现是前端的锅,前端只能获取免登授权码,后端进行access_token,userid,人员信息等。
参考文档: https://developers.dingtalk.com/document/app/enterprise-internal-application-logon-free?spm=ding_open_doc.document.0.0.36582f17ShLZ7v#topic-2021731 按照这四步思路做就可以。
|