钉钉登录
说明:目前使用的钉钉后台还在更新中,可能和文章展示的不同
1. 准备工作,首先需要有自己管理的部门
1. 进入开发者后台扫码登陆,如果是组织的管理者就直接选择进入

2. 不是组织管理者
首先注册 
创建团队

创建成功

进入手机APP查看

3. 如果是管理者
- 扫码登陆选择组织
 - 创建的个人团队目前只演示企业内部开发,创建应用为H5微应用或者小程序都可以
  - 返回首页
 - 选择进入,添加回调域名,这里使用的是开发环境,所以添加了当前项目运行的地址和端口号
  - 进入工作台


4.前端开发过程,不管是扫码登录还是使用钉钉的账号密码登录,都需要导入一个js 官方说明地址
- 在
index.html 中添加,window 就会挂载一个DDLogin 实例<script src="https://g.alicdn.com/dingding/dinglogin/0.0.5/ddLogin.js"></script>

- 初始化钉钉登录,
appid 是在工作台配置登录的时候生成的,url 中的回调地址也是在工作台中配置的,id 对应的html 中的标签 
<template>
<div class="dd-scan-login">
<div id="dd-login"></div>
</div>
</template>
<script>
const appid = 'dingoapbicykzzeqxpelxy'
const url = encodeURIComponent('http://127.0.0.1:9527/login')
const goto = encodeURIComponent(`https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${url}`)
export default {
name: 'DDScanLogin',
data() {
return {}
},
created() {},
mounted() {
this.ddInit()
},
methods: {
ddInit() {
window.DDLogin({
id: 'dd-login',
goto,
style: 'border:none;background-color:#FFFFFF;',
width: '365',
height: '400'
})
}
}
}
</script>
页面的效果  手机端扫描之后 
- 获取临时授权码
loginTmpCode ,使用监听message ,这里获取到临时授权码之后,可以将loginTmpCode 传递给后台,后台处理之后,将数据返回
created() {
window.addEventListener('message', this.DDMessage, false)
},
methods: {
DDMessage(event) {
const origin = event.origin
if (origin === 'https://login.dingtalk.com') {
const loginTmpCode = event.data
console.log('loginTmpCode', loginTmpCode)
}
}
},
beforeDestroy() {
window.removeEventListener('message', this.DDMessage, false)
}
3. 钉钉账号密码登录
- 为了不让页面刷新,使用
iframe 标签,sandbox="allow-scripts allow-same-origin allow-popups" 可以阻止页面跳转
<iframe
:src="iframeSrc"
frameborder="0"
id="dd-account-iframe"
sandbox="allow-scripts allow-same-origin allow-popups"
></iframe>
<script>
const appid = 'dingoapbicykzzeqxpelxy'
const url = encodeURIComponent('http://127.0.0.1:9527/login')
export default {
data() {
return {}
},
computed: {
iframeSrc() {
return `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${url}`
}
},
created() {},
mounted() {},
methods: {}
}
</script>
- 使用
onload ,获取
mounted() {
this.ddLoginInit()
},
methods: {
ddLoginInit () {
const that = this
document.getElementById('dd-account-iframe').onload = async function () {
try {
const getParams = this.contentWindow.location.href
const getIndex = getParams.indexOf('code=')
if (getIndex !== -1) {
const getCode = getParams.split('=')[1].split('&')[0]
console.log(getCode, 'getCode')
}
} catch (error) {
console.log(error)
} finally {
}
}
}
}

|