vue element admin 实现钉钉登录

发布时间 2023-09-13 15:07:15作者: 刘国微

lender提了个需求,要求实现钉钉扫码登录,分pc端(扫码)及手机端(直接跳转)

准备工作

根据开发者后台文档获取appId并设置对应的回调url。
为了方便演示回调url我们暂定为:https://test.com/ding

登录跳转代码

PC扫码跳转

window.location.href = `https://oapi.dingtalk.com/connect/qrconnect?appid=${你的appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=https://test.com/ding`

手机内部跳转

window.location.href = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${你的appid}&response_type=code&scope=snsapi_auth&state=STATE&redirect_uri=https://test.com/ding`

成功回调处理

获取token并重定向,代码位置一般在permission.js里

// 路由拦截事件
router.beforeEach(async(to, from, next) => {
  // getToken是你的获取token方式
  const hasToken = getToken()
  if (hasToken) {
    // token存在的情况下
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      // 其他权限类处理……
    }
  } else {
      // 钉钉登录处理 location = https://test.com/ding
    switch (location.pathname) {
      case '/ding':
        var data = {}
        // 处理code等数据
        location.search.substring(1).split('&').forEach((text) => {
          var array = text.split('=')
          data[array[0]] = array[1]
        })
        // 调用后台写的钉钉登录接口,在dispatch将token存入
        store.dispatch('user/dingLogin', data).then(() => {
          setTimeout(() => {
            // 获取到token后重定向到首页
            location.href = location.origin + '/index'
          }, 0)
        }).catch((logError) => {
          Message.error('钉钉登录失败')
          next(`/login?redirect=${to.path}`)
        })
        return
    }
    next(`/login?redirect=${to.path}`)
  }
})