1.需求:開發釘釘微應用,需要實現釘釘的免登陸功能。
#.其實釘釘的文檔中心還是很詳細的,只是剛開始接觸會一頭霧水,所以花費了挺多時間.......
?什么是釘釘免登功能。
?釘釘免登前端demo。
#.這里借用釘釘官方的流程圖,前端在這個過程中的工作,其實是從我標注的部分開始的~~~
#.也就是說,后端的同學需要把相應的參數都返回給前端,前端依照demo上的例子,利用jsapi進行驗證~
#.本次開發我們使用的前后端分離的方式,通過ajax請求數據
說明:
(1)該代碼是基於PC端的(如果是移動端需要更換jsapi,DingTalkPC.config 更為 dd.config)
(2)data:{url:“。。。”}是當前請求地址(這里我用的是絕對地址,換成相對地址試了錯誤~)
(3)后端返回給我數據是這樣的,所需要的數據在data.dataList中,我將其保存在_config中,方便下面使用。
代碼:
1 var _config; 2 $.ajax({ 3 url:"/????/dingtalk/config", 4 type:"GET", 5 async:false, 6 data:{ 7 url:"http://???.html" 8 }, 9 dataType:"json", 10 error:function(errorThrown){ 11 console.log("發生錯誤:" + errorThrown); 12 }, 13 success:function(data){ 14 console.log(data); 15 _config = data.dataList; 16 } 17 }); 18 DingTalkPC.config({ //實現驗證 19 agentId: _config.agentId, 20 corpId: _config.corpId, 21 timeStamp: _config.timeStamp, 22 nonceStr: _config.nonceStr, 23 signature: _config.signature, 24 jsApiList: [ 25 'runtime.info', 26 'device.notification.prompt', 27 'biz.chat.pickConversation', 28 'device.notification.confirm', 29 'device.notification.alert', 30 'device.notification.prompt', 31 'biz.chat.open', 32 'biz.util.open', 33 'biz.user.get', 34 'biz.contact.choose', 35 'biz.telephone.call', 36 'biz.ding.post'] 37 });
(4)如果驗證成功,會自動執行 DingTalkPC.ready 函數,然后通過 DingTalkPC.runtime.permission.requestAuthCode 獲取 code,再將 code 給后端,后端就可以獲取到用戶詳細信息了,然后再返回給前端使用。
代碼:
1 DingTalkPC.ready(function() {//驗證成功 2 DingTalkPC.runtime.permission.requestAuthCode({ 3 corpId: _config.corpId, //企業id 4 onSuccess: function (info) { 5 // console.log(info); 6 console.log('authcode: ' + info.code); 7 $.ajax({ 8 url: '?????', 9 type:"GET", 10 data: {"event":"get_userinfo","code":info.code}, 11 dataType:'json', 12 timeout: 900, 13 // async:false, 14 success: function (data, status, xhr) { 15 // console.log(data); 16 userId = data.userid; 17 deptId = data.department[0]; 18 $('#user_id').val(data.jobnumber);//工號 19 $('#user_name').val(data.name);//姓名 20 $('#position').val(data.position);//崗位 21 }, 22 error: function (xhr, errorType, error) { 23 console.log(errorType + ', ' + error); 24 } 25 }); 26 }, 27 onFail: function (err) { 28 console.log('requestAuthCode fail: ' + JSON.stringify(err)); 29 } 30 }); 31 });
(5)驗證失敗,會自動執行 DingTalkPC.error 函數
代碼:
DingTalkPC.error(function(err) { console.log('DingTalkPC error: ' + JSON.stringify(err)); });
注意:
開發時的所有測試都是在釘釘環境下的,即需要將你的微應用接入到釘釘中,一邊開發一邊進行測試,因為釘釘的 jsapi ,只有在釘釘app環境下才有dd對象,在釘釘pc端的環境下才有 DingTalkPC對象。如果直接在瀏覽器中進行測試可能是沒有反應的~
?如何測試。