钉钉登录前端处理

可参考官网:扫码登录第三方网站 - 钉钉开放平台

方式一:网站将钉钉登录二维码内嵌到自己页面中

<script src="https://g.alicdn.com/dingding/dinglogin/0.0.5/ddLogin.js"></script>

在需要使用钉钉登录的地方实例以下JS对象

/*
* 解释一下goto参数,参考以下例子:
* var url = encodeURIComponent('http://localhost.me/index.php?test=1&aa=2');
* var goto = encodeURIComponent('https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=SuiteKey&response_type=code&scope=snsapi_login&state=STATE&redirect_uri='+url)
*/
var obj = DDLogin({
     id:"login_container",//这里需要你在自己的页面定义一个HTML标签并设置id,例如<div id="login_container"></div>或<span id="login_container"></span>
     goto: "", //请参考注释里的方式
     style: "border:none;background-color:#FFFFFF;",
     width : "365",
     height: "400"
 });

参数说明

参数

说明

goto

goto参数结构:https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=SuiteKey&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=REDIRECT_URI,并且要将goto参数urlencode编码。

style

渲染二维码的区域的样式,可以自定义去除背景颜色和边框。

width

表示显示二维码的区域的宽。

width和height不代表二维码的大小,二维码大小是固定的210px*210px。

height

表示显示二维码的区域的高。

width和height不代表二维码的大小,二维码大小是固定的210px*210px。

加载钉钉API接口以后,获取用户扫描之后将获取的loginTmpCode。通过一下方法获取

var handleMessage = function (event) {
  var origin = event.origin;
  console.log("origin", event.origin);
  if( origin == "https://login.dingtalk.com" ) { //判断是否来自ddLogin扫码事件。
    var loginTmpCode = event.data; 
    //获取到loginTmpCode后就可以在这里构造跳转链接进行跳转了
    
    console.log("loginTmpCode", loginTmpCode);
  }
};
if (typeof window.addEventListener != 'undefined') {
    window.addEventListener('message', handleMessage, false);
} else if (typeof window.attachEvent != 'undefined') {
    window.attachEvent('onmessage', handleMessage);
}

在vue项目中,可通过动态创建script标签,加载js库。如:

const loadRemoteScript = (url) => {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src = url;
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });
}


const loadRemoteimg = () => {
  loadRemoteScript('https://g.alicdn.com/dingding/dinglogin/0.0.5/ddLogin.js')
  // loadRemoteScript('https://g.alicdn.com/dingding/h5-dingtalk-login/0.21.0/ddlogin.js')
    .then(() => {
      console.log("登录");
        ddLoginInitinfo()
    })
    .catch(() => {
        console.log("外部js加载异常")
    });
}


const ddLoginInitinfo = () => {
  const url = encodeURIComponent(redirect_uri地址);
  // console.log(8888, `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${state.baseConfig.app_key}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${url}`);
    window.DDLogin(
      {
          id: "ding-login", // 装钉钉二维码的盒子
          goto: encodeURIComponent(`https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=appkey值&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${url}`),
          style: "border:none;background-color:#FFFFFF;padding-bottom: 24px",
          width: "250",
          height: "300",
      },   
    )

    var handleMessage = function (event) {
      var origin = event.origin;
      console.log("origin", event.origin);
      if( origin == "https://login.dingtalk.com" ) { //判断是否来自ddLogin扫码事件。
          var loginTmpCode = event.data;

          fetch("https://oapi.dingtalk.com/connect/oauth2/sns_authorize?response_type=code&scope=snsapi_login&state=STATE&redirect_uri=REDIRECT_URI&loginTmpCode="+loginTmpCode, {
            method: 'GET', // 默认就是GET,所以这一行可以省略
            headers: {
              'Content-Type': 'application/json',
            },
          })
          .then(response => response.json()) // 将响应解析为JSON
          .then(res => {
            console.log(5555, res)
            // 登录成功操作
          })
          .catch((error) => {
            console.log('Error:', error);
          });


        //获取到loginTmpCode后就可以在这里构造跳转链接进行跳转了

            console.log("loginTmpCode", loginTmpCode);
          }
    };
    if (typeof window.addEventListener != 'undefined') {
        window.addEventListener('message', handleMessage, false);
    } else if (typeof window.attachEvent != 'undefined') {
          window.attachEvent('onmessage', handleMessage);
    }
}

方式二:使用钉钉提供扫码登录页

// 相对上面一种方式  更换引入的js库
// https://g.alicdn.com/dingding/h5-dingtalk-login/0.21.0/ddlogin.js'


const loadRemoteimg = () => {
 loadRemoteScript('https://g.alicdn.com/dingding/h5-dingtalk-login/0.21.0/ddlogin.js')
    .then(() => {
      console.log("登录");
        ddLoginInitinfo()
    })
    .catch(() => {
        console.log("外部js加载异常")
    });
}



const ddLoginInitinfo = () => {
    window.DTFrameLogin(
        {
            id: "ding-login", // 装钉钉二维码的盒子
            width: 250,
            height: 270,
        },
        {
            redirect_uri: encodeURIComponent(redirect_uri地址),
            client_id: app_key地址,
            scope: "openid",
            response_type: "code",
            prompt: "consent",
            state: "ddd",
        },
        (loginResult) => {
             console.log("loginResult===", loginResult);
             const { redirectUrl, authCode, state } = loginResult;
            baseService.get("接口地址").then((res) => {console.log("测试接口", res);});
            if (res.code === 0) {
               //成功反馈
            }
        },
        (errorMsg) => {
            console.log("errorMsg : " + errorMsg);
        }
    )

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现扫描二维码登录,需要进行以下步骤: 1. 在开放平台注册应用,并获取到应用的 `AppId` 和 `AppSecret`。 2. 在前端页面上实现扫描二维码的功能,可以使用提供的 `DingTalkPC.runtime.permission.requestAuthCode` 方法,该方法会弹出扫描二维码的界面,用户扫描二维码后会返回一个 `code` 值。 3. 前端将 `code` 值发送到后端,后端拿到 `code` 值以及 `AppId` 和 `AppSecret`,调用开放平台提供的接口获取用户的身份信息。 4. 后端将获取到的用户身份信息返回给前端前端根据身份信息进行相应的页面跳转或者其他操作。 下面是一个简单的实现示例: 前端代码: ``` html <!-- 扫描二维码的按钮 --> <button @click="requestAuthCode">扫描二维码登录</button> <script> export default { methods: { requestAuthCode() { // 调用DingTalkPC.runtime.permission.requestAuthCode方法 DingTalkPC.runtime.permission.requestAuthCode({ corpId: '应用的CorpId', onSuccess: function(result) { // result.code为获取到的code值 // 将code值发送到后端进行身份验证 }, onFail: function(err) { console.log(err) } }); } } } </script> ``` 后端代码: ``` javascript const axios = require('axios'); // 获取用户身份信息的接口 const API_URL = 'https://oapi.dingtalk.com/sns/getuserinfo_bycode'; async function getUserInfo(code, appId, appSecret) { const url = `${API_URL}?accessKey=${appId}&accessSecret=${appSecret}&code=${code}`; const response = await axios.get(url); return response.data; } // 在路由中处理扫描二维码的请求 app.get('/dingtalk/login', async (req, res) => { const { code } = req.query; const appId = '你的应用AppId'; const appSecret = '你的应用AppSecret'; try { const userInfo = await getUserInfo(code, appId, appSecret); // 将获取到的用户身份信息返回给前端 res.send(userInfo); } catch (err) { console.log(err); res.status(500).send('获取用户信息失败'); } }); ``` 需要注意的是,以上代码仅为参考示例,实际应用中还需要考虑一些安全性和错误处理的问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值