Tips_钉钉免登前端实现

时间:2021-09-22 21:04:40

1.需求:开发钉钉微应用,需要实现钉钉的免登陆功能。

#.其实钉钉的文档中心还是很详细的,只是刚开始接触会一头雾水,所以花费了挺多时间.......

?什么是钉钉免登功能

企业应用免登开发授权流程

?钉钉免登前端demo

jsapi

Tips_钉钉免登前端实现

#.这里借用钉钉官方的流程图,前端在这个过程中的工作,其实是从我标注的部分开始的~~~

Tips_钉钉免登前端实现

#.也就是说,后端的同学需要把相应的参数都返回给前端,前端依照demo上的例子,利用jsapi进行验证~

#.本次开发我们使用的前后端分离的方式,通过ajax请求数据

  说明:

(1)该代码是基于PC端的(如果是移动端需要更换jsapi,DingTalkPC.config 更为 dd.config)

(2)data:{url:“。。。”}是当前请求地址(这里我用的是绝对地址,换成相对地址试了错误~)

(3)后端返回给我数据是这样的,所需要的数据在data.dataList中,我将其保存在_config中,方便下面使用。

Tips_钉钉免登前端实现

 代码:

 var _config;
$.ajax({
url:"/????/dingtalk/config",
type:"GET",
async:false,
data:{
url:"http://???.html"
},
dataType:"json",
error:function(errorThrown){
console.log("发生错误:" + errorThrown);
},
success:function(data){
console.log(data);
_config = data.dataList;
}
});
DingTalkPC.config({ //实现验证
agentId: _config.agentId,
corpId: _config.corpId,
timeStamp: _config.timeStamp,
nonceStr: _config.nonceStr,
signature: _config.signature,
jsApiList: [
'runtime.info',
'device.notification.prompt',
'biz.chat.pickConversation',
'device.notification.confirm',
'device.notification.alert',
'device.notification.prompt',
'biz.chat.open',
'biz.util.open',
'biz.user.get',
'biz.contact.choose',
'biz.telephone.call',
'biz.ding.post']
});

(4)如果验证成功,会自动执行 DingTalkPC.ready 函数,然后通过 DingTalkPC.runtime.permission.requestAuthCode 获取 code,再将 code 给后端,后端就可以获取到用户详细信息了,然后再返回给前端使用。

代码:

 DingTalkPC.ready(function() {//验证成功
DingTalkPC.runtime.permission.requestAuthCode({
corpId: _config.corpId, //企业id
onSuccess: function (info) {
// console.log(info);
console.log('authcode: ' + info.code);
$.ajax({
url: '?????',
type:"GET",
data: {"event":"get_userinfo","code":info.code},
dataType:'json',
timeout: 900,
// async:false,
success: function (data, status, xhr) {
// console.log(data);
userId = data.userid;
deptId = data.department[0];
$('#user_id').val(data.jobnumber);//工号
$('#user_name').val(data.name);//姓名
$('#position').val(data.position);//岗位
},
error: function (xhr, errorType, error) {
console.log(errorType + ', ' + error);
}
});
},
onFail: function (err) {
console.log('requestAuthCode fail: ' + JSON.stringify(err));
}
});
});

(5)验证失败,会自动执行 DingTalkPC.error 函数

代码:

 DingTalkPC.error(function(err) {
console.log('DingTalkPC error: ' + JSON.stringify(err));
});

注意:

  开发时的所有测试都是在钉钉环境下的,即需要将你的微应用接入到钉钉中,一边开发一边进行测试,因为钉钉的 jsapi  ,只有在钉钉app环境下才有dd对象,在钉钉pc端的环境下才有 DingTalkPC对象。如果直接在浏览器中进行测试可能是没有反应的~

如何测试