一、在public/index.html引入钉钉js
//需注意如果报错DDLogin未定义,需要将此代码放入head中或者body中,放在body-html标签之间有些项目会报错。
<script src="https://g.alicdn.com/dingding/dinglogin/0.0.5/ddLogin.js"></script>
二、页面使用
<!-- dd登录 -->
<template>
<div id="login_container">
</div>
</template>
<script>
export default {
name: "App",
components: {},
data() {
return {
appid: requstUrl.ddAppid,//自己申请的appid
appsecret: requstUrl.ddAppsecret,//自己申请的appsecret
redirectUrl: requstUrl.redirectUrl,//这里是扫码成功后跳转的回调地址
dingCodeConfig: {
id: "login_container",//匹配到设置的html的id
style: "border:none;background-color:#FFFFFF;",
width: "400",
height: "400",
},//生成二维码样式的配置
};
},
computed: {
getRedirectUrl() {
return encodeURIComponent(this.redirectUrl);
},
getAuthUrl() {
return `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${this.appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${this.getRedirectUrl}`;
},
getGoto() {
return encodeURIComponent(this.getAuthUrl);
},
},
mounted() {
const { code } = this.$route.query
if(code){
this.handleCodeLogin(this.$route.query)
this.ddLoginInit()
}else{
this.ddLoginInit()
};
},
methods: {
//生成钉钉二维码
ddLoginInit() {
//钉钉扫码流程:扫码成功登录后会自动跳到这个url页面,url路径会携带code,你拿到这个code,调用登录接口成功就跳转。
let that = this;
//你的项目页面
let url = that.getRedirectUrl;
let obj = DDLogin({
id: "login_container",//这里需要你在自己的页面定义一个HTML标签并设置id,例如<div id="login_container"></div>或<span id="login_container"></span>
goto: that.getGoto, //请参考注释里的方式
style: "border:none;background-color:#FFFFFF;",
width: "400",//官方参数 365
height: "400"//官方参数 400
});
let handleMessage = (event) => {
let origin = event.origin;
console.log("origin", event.origin);
if (origin == "https://login.dingtalk.com") { //判断是否来自ddLogin扫码事件。
let loginTmpCode = event.data;
//获取到loginTmpCode后就可以在这里构造跳转链接进行跳转了
console.log("loginTmpCode", loginTmpCode);
//此步拿到临时loginTmpCode换取正式code
window.location.href = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${that.appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${url}&loginTmpCode=${loginTmpCode}`
}
};
if (typeof window.addEventListener != 'undefined') {
window.addEventListener('message', handleMessage, false);
} else if (typeof window.attachEvent != 'undefined') {
window.attachEvent('onmessage', handleMessage);
}
},
// 扫码回调登录
handleCodeLogin(data) {
console.log(data)
//获取临时授权code后给后台,获取用户信息
},
}
};
</script>
<style lang='less' scoped>
#login_container{
width: 300px;
height: 400px;
margin-top: -15px;
}
</style>
三、扫码确认后,重定向的跳转路径后会带上code码
这个code既是临时授权码,根据这个临时码让后台接口去获取永久授权码,再根据永久授权码获取用户的钉钉信息......
详见钉钉官方文档 --> 扫码登录第三方网站 - 钉钉开放平台