最近因项目要求要在登录页增加第三方登录,微信/钉钉。微信扫码登录想必大家都做过,钉钉之前也没接触过。找到开发者文档挨个看,首先我们的需求属于企业内部应用下的H5微应用 ,在开发者后台创建H5微应用,创建时让管理员给设置下权限,不然后面没办法操作。
如上图 点击创建应用,输入应用的信息就可以了。然后在凭证与基础信息页面,复制应用的AppKey和AppSecret备用
。
然后点击 添加应用能力,这里我选择的是网页应用,添加成功后点击配置按钮 配置开发的信息
这里必须要让管理员给开通权限,不然没办法添加。然后点击权限管理,根据自身的需求设置权限,这里我只选择了两个
在分享设置中添加回调域名,这里添加登录页地址就行
以上便是自己实操过的一些配置流程,可能不是特别详细,大家看不明白的可以看下钉钉开放平台文档 钉钉开放平台
钉钉扫码登录分为两种,第一种是钉钉二维码单独跳转页面进行扫码登录,第二种是将钉钉登录二维码内嵌到自己页面上。这里我采用的是第二种方式。对应文档
接下来就开始构造登录页面了,在public文件下的index.html中先引入如下JS文件(支持HTTPS)
<script src="https://g.alicdn.com/dingding/h5-dingtalk-login/0.21.0/ddlogin.js"></script>
在登录页定义一个二维码的容器
<!-- 钉钉登录 -->
<div class="login-form" v-show="ddShow">
<div class="title-container">
<h3 class="title md-title">钉钉扫码登录</h3>
</div>
<div id="dd_login" style="margin: 0 auto;width: 250px; height: 250px;"></div>
<p class="login-alt">请使用钉钉扫描二维码登录</p>
</div>
初始化
<script>
import axios from "axios";
import * as dd from "dingtalk-jsapi";
import { getCode, logoSendCode } from '@/api/user.js'
export default {
name: 'Login',
data() {
return {
appKey: "xxxxx",//在凭证与基础信息页面中查看对应的appkey
dingRedirectUrl: encodeURIComponent("http://192.168.1.123:9527/srp/Admin/#/login"),//对应的是回调域名
}
},
mounted() {
//钉钉登录
const { code, authCode, state } = this.$route.query;
this.ddLogin();
},
methods:{
//调起钉钉内嵌二维码
ddLogin() {
let url = this.dingRedirectUrl
window.DTFrameLogin(
{
id: 'dd_login',
width: 280,
height: 280,
},
{
redirect_uri: url,
client_id: this.appKey,
scope: 'openid',
response_type: 'code',
state: this.randomString(10),
prompt: 'consent',
},
(loginResult) => {
const { redirectUrl, authCode} = loginResult;
// 根据后端提供的接口,向后端传递临时授权码使,用code进行授权
axios.get(`http://192.168.1.56:8080/auth/validate/getUserInfo?authCode=${authCode}`)
.then(response => {
localStorage.setItem("token", JSON.stringify(response.data))
let params = {
grant_type: 'dingTalk_id',
scope: 'admin',
openId : response.data.data
}
//调用接口 通过后端返回的openId进行登录
mobileLogin(params).then(res => {
if(res.status === 200){
this.$message({
message: "扫码成功",
type: "success",
});
this.$store.dispatch('user/login', params).then(() => {
this.$router.push({
path: 'index'
})
})
}else{
this.$message.error({
message: "钉钉没有绑定账号,请使用手机号登录后进入设置中绑定",
type: "success",
})
}
})
})
.catch(error => {
this.$message({
message: "登录失败",
type: "error",
});
console.log('请求失败', error)
})
}
)
},
randomString(len) {
len = len || 10;
let $chars = "ABCDEFGHIJKMNOPQRSTUVWXYZ"; // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
let maxPos = $chars.length;
let pwd = "";
for (var i = 0; i < len; i++) {
pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
}
return pwd;
}
}
}
</script>
接下来本地运行下,就能看到钉钉二维码了,可以使用钉钉进行扫码登录了