第三方pc实现钉钉扫码登录 前端

348 阅读1分钟
 data(){
   appid: "ding3bllyb9vdvdvddshncvdvvvdsnxlx", //钉钉APiID(自己申请的id)
   redirectUrl: "http://221.7.157577.18:122/login", //回调地址,当前登陆页面地址
   apiUrl: "http://localhost:8080/dingTalk/user/dingTalkLogin", //请求后端地址  二维码设置参数
 },
 mounted() {
    //code为传给后端的
  const { code } = this.$route.query
   if (code) {
    this.goDdLogin(code)
    } else { //钉钉二维码
    this.ddLoginInit()
    } 
  },
 methods: {
ddLoginInit(){
   let url = encodeURIComponent(this.redirectUrl);
   let appid = this.appid
   let goto = encodeURIComponent(`https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${url}`)
   let obj = DDLogin({
       id:"login_container",
       goto: goto,
       style: "border:none;background-color:#FFFFFF;",
       width : "100%",
       height: "300"
   }); 
   let handleMessage =  (event) =>{
     let origin = event.origin;
     console.log('event.data',event.data)
     if( origin == "https://login.dingtalk.com" ) { //判断是否来自ddLogin扫码事件。
      console.log('event.data',event.data)
       let loginTmpCode = event.data; 
       window.location.href = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${url}&loginTmpCode=${loginTmpCode}`
     }
   };
   if (typeof window.addEventListener != 'undefined') {
            window.addEventListener('message', handleMessage, false);
        } else if (typeof window.attachEvent != 'undefined') {
            window.attachEvent('onmessage', handleMessage);
        }
 },
 goDdLogin(code){
  console.log('code',code)
  // 写自己的登录后的逻辑
},
}