第三方管理系统接入钉钉扫码登录

效果图如下:

具体步骤如下:

1.  首先新建一个dd-login.vue的页面。

 2. dd-login.vue页面内容如下。

<style lang="less">
  @import '../../../styles/common.less';
</style>

<template>
  <div id="dd_QRcode_login"></div>
</template>

<script>
import fetch from '@/libs/fetch'
export default {
name: 'dd_QRcode_login',
  data () {
    return {
      opacity:0.8
    }
  },
  props: {
    qr: Object,
    redirectUrl:Object
  },
  methods: {
    
    getLoginUrl(){
      fetch({
        url: '/finance-zrwb-service/user/ddAuthUrl?redirectUrl='+encodeURIComponent(this.redirectUrl.replace('#','@')),
        method: 'GET'
      }).then(resp=>{
        this.initDDQRCode(encodeURIComponent(resp.result.authUrl),resp.result.redirect);
      })
    },
    initDDQRCode(url,redirect){
      var obj = DDLogin({
        id:"dd_QRcode_login",//这里需要你在自己的页面定义一个HTML标签并设置id,例如<div id="login_container"></div>或<span id="login_container"></span>
        goto:  url, //请参考注释里的方式
        style: "border:none;background-color:#FFFFFF;overflow: hidden;",
        width : "270",
        height: "300"
      })
      var handleMessage = function (event) {
        var origin = event.origin
          console.log("origin+++++", event) // code

        if( origin == "https://login.dingtalk.com" ) { //判断是否来自ddLogin扫码事件。
          var loginTmpCode = event.data;
          console.log("loginTmpCode", loginTmpCode); // code
          if(redirect){
              redirect=decodeURIComponent(url)
            if(redirect.indexOf("?")==-1){
                redirect  +="?loginTmpCode="+loginTmpCode;
            }else{
                redirect +="&loginTmpCode="+loginTmpCode;
            }
          }
          location.href = redirect
        }
      }
      if (typeof window.addEventListener != 'undefined') {
        window.addEventListener('message', handleMessage, false)
      } else if (typeof window.attachEvent != 'undefined') {
        window.attachEvent('onmessage', handleMessage)
      }
    }
  },
  mounted () {
    this.getLoginUrl()
    function d(a) {
      var e, c = document.createElement("iframe"),
      d = "https://login.dingtalk.com/login/qrcode.htm?goto=" + a.goto;
      d += a.style ? "&style=" + encodeURIComponent(a.style) : "",
      d += a.href ? "&href=" + a.href : "",
      c.src = d,
      c.frameBorder = "0",
      c.allowTransparency = "true",
      c.scrolling = "no",
      c.width = a.width ? a.width + 'px' : "365px",
      c.height = a.height ? a.height + 'px' : "400px",
      e = document.getElementById(a.id),
      e.innerHTML = "",
      e.appendChild(c)
    }
    window.DDLogin = d
  }
}
</script>

3.  引入的common.less 文件如下。

.margin-top-8{
    margin-top: 8px;
}
.margin-top-10{
    margin-top: 10px;
}
.margin-top-20{
    margin-top: 20px;
}
.margin-left-10{
    margin-left: 10px;
}
.margin-bottom-10{
    margin-bottom: 10px;
}
.margin-bottom-100{
    margin-bottom: 100px;
}
.margin-right-10{
    margin-right: 10px;
}
.padding-left-6{
    padding-left: 6px;
}
.padding-left-8{
    padding-left: 5px;
}
.padding-left-10{
    padding-left: 10px;
}
.padding-left-20{
    padding-left: 20px;
}
.height-100{
    height: 100%;
}
.height-120px{
    height: 100px;
}
.height-200px{
    height: 200px;
}
.height-492px{
    height: 492px;
}
.height-460px{
    height: 460px;
}
.line-gray{
    height: 0;
    border-bottom: 2px solid #dcdcdc;
}
.notwrap{
    word-break:keep-all; 
    white-space:nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.padding-left-5{
    padding-left: 10px;
}
[v-cloak]{
    display: none;
}

4. 然后在登录页  login.vue 页面  引入进来,就像在父组件里引用子组件一样。

  import DDlogin from "@/views/fast/nailingLogin/dd-login.vue"
  import waterMark from "@/libs/waterMark" // 水印
  export default {
    components:{  DDlogin },  // 钉钉扫码
    data() {
       return { 
          redirectUrl:location.protocol+'//'+location.hostname+'/#/home', 
          // 路由重定向地址
       }
    }
}

5. 然后在页面上引用。

<!-- 钉钉扫码登录 -->
<Card class="DD_box" v-if="true">
  <p class="p1"><strong>钉钉登录</strong></p>
  <div id="dd_QRcode_login" class="arrangement">
    <DDlogin :redirectUrl="redirectUrl"/>
  </div>
</Card>

注意:这里必须要给一个div标签且id必须是dd_QRcode_login。

因为在dd-login.vue页面定义的id名称就为dd_QRcode_login.

   initDDQRCode(url,redirect){
      var obj = DDLogin({
        id:"dd_QRcode_login",
// 这里需要你在自己的页面定义一个HTML标签并设置id,例如<div id="login_container"></div>
// 或<span id="login_container"></span>
        goto:  url, //请参考注释里的方式
        style: "border:none;background-color:#FFFFFF;overflow: hidden;",
        width : "270",
        height: "300"
      })
}

6. 在dd-login.vue有个调用接口的地方,必须跟换成后端服务接口的地址。*号就是接口地址

url: '*********?redirectUrl='+encodeURIComponent(this.redirectUrl.replace('#','@')),

7. 注意上面有一个waterMark.js的文件,这个文件是加水印的:姓名+时间。

8. waterMark.js文件 内容如下。

import DomSize from 'wd-domsize-monitor';
import ApiLogin from "../api/login";
import { router } from '@/router/index';
var id = 'shuiyinDiv'
var isInit = false

let callback = function (ele) {
    DomSize.bind(ele, function () {
        //水印被删除
        DomSize.remove(ele);
        waterMark(callback)
        // my codding....
    })
}
var waterMark = function (callback) {
    let old = document.getElementById(id)
    if (old) {
        old.remove()
        // id = id + "1"
    }
    function textBecomeImg(text, fontsize, fontcolor) {
        var canvas = document.createElement('canvas');
        let $buHeight = 0;
        if (fontsize <= 32) { $buHeight = 99; }
        else if (fontsize > 32 && fontsize <= 60) { $buHeight = 2; }
        else if (fontsize > 60 && fontsize <= 80) { $buHeight = 4; }
        else if (fontsize > 80 && fontsize <= 100) { $buHeight = 6; }
        else if (fontsize > 100) { $buHeight = 10; }
        canvas.height = fontsize + $buHeight;
        canvas.padding = 30;
        var context = canvas.getContext('2d');
        context.clearRect(0, 0, canvas.width * 2, canvas.height);
        context.fillStyle = fontcolor;
        context.font = fontsize + "px Arial";
        context.textAlign = "center";
        context.textBaseline = 'middle';
        context.fillText(text, 0, fontsize / 2);
        var canvasWidth = canvas.width / 99;
        canvasWidth = context.measureText(text).width;
        canvas.width = 330;
        canvas.height = 120;
        context.fillStyle = fontcolor;
        context.font = fontsize + "px Arial";
        context.textBaseline = 'middle';
        context.fillText(text, 0, fontsize / 2);
        var dataUrl = canvas.toDataURL('image/png');
        return dataUrl;
    }

    var createEle = function () {
        var user = localStorage.getItem('userInfo')
        userInfo = JSON.parse(user)
        if(!user){

        }else {
          var phone = userInfo.loginName ? userInfo.loginName.substr(userInfo.loginName.length - 4, 4) : ""
          var text = userInfo.name + "-" + phone + " " + userInfo.lastLoginTime;
          var shuiyinEle = document.createElement('div');
          shuiyinEle.id = id
          var style = shuiyinEle.style;
          style.position = 'fixed';
          style.left = '-50%';
          style.top = '-50%';
          style.width = '200%';
          style.height = '200%';
          style.opacity = '0.1';
          style.background = "url(" + textBecomeImg(text, 16, "#666666") + ")";
          style.zIndex = 9999999991;
          style.transform = "rotate(-30deg)";
          style.pointerEvents = "none";
          document.body.appendChild(shuiyinEle);
          callback(shuiyinEle)
          // waterMark();
          // select the target node
          var target = document.getElementById(id);
          // create an observer instance
          var observer = new MutationObserver(function (mutations) {
              mutations.forEach(function (mutation) {
                  observer.disconnect();
                  reset()
              });
          });
          // configuration of the observer:
          var config = { attributes: true, childList: true, characterData: true };
          // pass in the target node, as well as the observer options
          observer.observe(target, config);
          // later, you can stop observing
          // observer.disconnect();
          // t();
        }
    }


    if (router.history.current.name!=='login'){
      var userInfo = localStorage.getItem('userInfo')
      //userInfo = JSON.parse(userInfo)
      if (!userInfo || !userInfo.name) {
        ApiLogin.info()
          .then(response => {
            console.log("---------------------输出info接口参数:",response)
            userInfo = response.result;
            localStorage.setItem("userInfo",JSON.stringify(userInfo))
            localStorage.setItem("mobilePhone",userInfo.mobilePhone)
            console.log("=========后执行==========",response.result !== null)
            if(response.result !== null){
              this.$router.push({ name:"home_index" })
              console.log("执行了")
            }
            createEle()
          }).catch(err => {
          isInit = false
        })
      } else {
        createEle()
      }
    }





      // var userInfo = localStorage.getItem('userInfo')
      // userInfo = JSON.parse(userInfo)
      // ApiLogin.info().then(response => {
      //     userInfo = response.result;
      //     console.log("*******水印调用info************:",response)
      //     localStorage.setItem("userInfo",JSON.stringify(userInfo))
      //     createEle()
      // }).catch(err => {
      //     isInit = false
      // })

    // var userInfo = localStorage.getItem('userInfo')
    // userInfo = JSON.parse(userInfo)
    // if (!userInfo || !userInfo.name) {
    //     ApiLogin.info().then(response => {
    //         userInfo = response.result;
    //         createEle()
    //     }).catch(err => {
    //         isInit = false
    //     })
    // } else {
    //     createEle()
    // }
}
var reset = function () {
    waterMark(callback)
}
var init = function () {
    // if (isInit) {
    //     return
    // }
    // isInit = true
    waterMark(callback)
}

export default init;

9.  这个 waterMark.js还需要在app.vue引入一下。   app.vue文件如下

<template>
   <div id="main" class="app-main">
        <router-view></router-view>
    </div>
</template>

<script>
import waterMark from "@/libs/waterMark"
export default {
  data() {
    return {
      theme: this.$store.state.app.themeColor
    };
  },
  mounted() {
    waterMark()
  },
  beforeDestroy() {},
  methods: {},
};
</script>

<style>
.app-main {
  width: 100%;
  height: 100%;
  background: #f0f0f0;
}
</style>

10. 同样的在login.vue页面也得引入这个waterMark.js。 

因为要在这个文件里去发请求拿个人信息。

拿不到个人信息的话是登录不了的,会被一下拦在登录页。

 import waterMark from "@/libs/waterMark" // 水印

11. 最后 需要后端在  添加配置服务配置了。

Guess you like

Origin blog.csdn.net/weixin_48674314/article/details/121056346