- 首先釘釘官方j(luò)s引入(也可以在線網(wǎng)址引入)用于生成二維碼
function d(a) {
var e, c = document.createElement("iframe"),
d = "https://login.dingtalk.com/login/qrcode.htm?goto=" + a.goto ;
d += a.style ? "&style=" + encodeURIComponent(a.style) : "",
d += a.href ? "&href=" + a.href : "",
c.src = d,
c.frameBorder = "0",
c.allowTransparency = "true",
c.scrolling = "no",
c.width = a.width ? a.width + 'px' : "365px",
c.height = a.height ? a.height + 'px' : "400px",
e = document.getElementById(a.id),
e.innerHTML = "",
e.appendChild(c)
}
window.DDLogin = d
}(window, document);
2.使用參數(shù)格式
ding:{
appid: "",
agentid: "",
corpid: "",
uri: "",
redirect_uri: "",
code: "",
accesstoken: ""
}
- 函數(shù)調(diào)用(生成二維碼)
codeLogin() {
//appid (釘釘申請時(shí)有的)和 redirect_uri (掃碼后去往的頁面路徑)由后端提供
this.ding.appid = "xxxxxxxxx";
this.ding.redirect_uri = "xxxxxxxxxxx";
//拼接掃碼所獲取的頁面路徑
this.ding.uri =
"https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=" +
this.ding.appid +
"&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=" +
this.ding.redirect_uri;
// 調(diào)用釘釘js文件生成二維碼
DDLogin({
// 通過id與頁面標(biāo)簽綁定
id: "login_container",
goto: encodeURIComponent(this.ding.uri),
style: "border:none;background-color:rgba(150, 150, 150, 0);",
width: "220",
height: "280"
});
// 響應(yīng)掃碼獲取數(shù)據(jù)
if (typeof window.addEventListener != "undefined") {
window.addEventListener("message", this.hanndleMessage, false);
} else if (typeof window.attachEvent != "undefined") {
window.attachEvent("onmessage", this.hanndleMessage);
}
},
- 掃碼后調(diào)用的函數(shù)
hanndleMessage(event){
let _self = this;
let origin = event.origin;
if (origin == "https://login.dingtalk.com") {
// 獲取釘釘給的loginTmpCode
let loginTmpCode = event.data;
if (loginTmpCode) {
// 重新拼接 url 跳轉(zhuǎn)(重定向)自己頁面
let url =
"https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=" +
_self.ding.appid +
"&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=" +
_self.ding.redirect_uri +
"&loginTmpCode=" +
loginTmpCode;
// 由于終端不需要跳轉(zhuǎn)頁面 僅需要獲取頁面數(shù)據(jù),使用XMLHttpRequest獲取頁面數(shù)據(jù)
let xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4&& xhr.status == 200) {
// 獲取數(shù)據(jù) 發(fā)送后端提供二維碼登錄接口即可
let data = JSON.parse(xhr.responseText)
}
};
}
}
},