- 首先钉钉官方js引入(也可以在线网址引入)用于生成二维码
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.使用参数格式
ding:{
appid: "",
agentid: "",
corpid: "",
uri: "",
redirect_uri: "",
code: "",
accesstoken: ""
}
- 函数调用(生成二维码)
codeLogin() {
//appid (钉钉申请时有的)和 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;
// 调用钉钉js文件生成二维码
DDLogin({
// 通过id与页面标签绑定
id: "login_container",
goto: encodeURIComponent(this.ding.uri),
style: "border:none;background-color:rgba(150, 150, 150, 0);",
width: "220",
height: "280"
});
// 响应扫码获取数据
if (typeof window.addEventListener != "undefined") {
window.addEventListener("message", this.hanndleMessage, false);
} else if (typeof window.attachEvent != "undefined") {
window.attachEvent("onmessage", this.hanndleMessage);
}
},
- 扫码后调用的函数
hanndleMessage(event){
let _self = this;
let origin = event.origin;
if (origin == "https://login.dingtalk.com") {
// 获取钉钉给的loginTmpCode
let loginTmpCode = event.data;
if (loginTmpCode) {
// 重新拼接 url 跳转(重定向)自己页面
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;
// 由于终端不需要跳转页面 仅需要获取页面数据,使用XMLHttpRequest获取页面数据
let xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4&& xhr.status == 200) {
// 获取数据 发送后端提供二维码登录接口即可
let data = JSON.parse(xhr.responseText)
}
};
}
}
},
网友评论