Uniapp implements DingTalk scan code login sample code

Uniapp implements DingTalk scan code login sample code

Since Uniapp does not have DingTalk authorization login, this article embeds DingTalk QR code login as a web page into Uniapp, and finally realizes DingTalk QR code login app

1. Use H5 to launch DingTalk and scan the QR code to log in

For more information about scanning code to log in to DingTalk on the web, please refer to the DingTalk document: Scan code to log in to third-party websites - DingTalk Open Platform (dingtalk.com)

// DingTalk scan code to log in dingLoginFn() {
      let dingData = {
        appid: OUT_LINK_CONFIG.dingAppid,
        state: "STATE",
        url: encodeURIComponent('Callback address after login: can be a page address of your H5 (href)') // This address is used for route redirection after confirming by scanning the code with DingTalk (it will carry the code value obtained by scanning the code)
      };
      let oauth = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${dingData.appid}&response_type=code&scope=snsapi_login&state=${dingData.state}&redirect_uri=${dingData.url}`;
      let goto = encodeURIComponent(oauth);
      DDLogin({
        id: "loginContainer", //Here you need to define an HTML tag in your own page and set the id, such as <div id="login_container"></div> or <span id="login_container"></span>
        goto: goto,
        style: "border:none;background-color:#FFFFFF;",
        width: "268"
      });
      let handleMessage = (event) => {
        // Determine whether it is from the ddLogin code scanning event.
        if (event.origin == "https://login.dingtalk.com" && event.data) {
          console.log("loginTmpCode", event.data);
          window.location.href = `${oauth}&loginTmpCode=${event.data}`; // After getting loginTmpCode, you can construct a jump link here to jump.}
      };
      if (typeof window.addEventListener != "undefined") {
        window.addEventListener("message", handleMessage, false);
      } else if (typeof window.attachEvent != "undefined") {
        window.attachEvent("onmessage", handleMessage);
      }
    }

2. The address used for routing redirection should not be the web address that calls the DingTalk QR code (the address in step 1)

Because in uniapp, if the two addresses are the same, the code will be returned to the login process and the QR code page will be displayed again before jumping to the login success interface. Routing redirection page (this article is built with Vue). If you want to use uni's API in H5, you need to import uni's jdk in public/index.html

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <!-- Introducing JDK for scanning code login for DingTalk -->
    <script src="https://g.alicdn.com/dingding/dinglogin/0.0.5/ddLogin.js"></script>
    <title></title>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body> <!-- Import the JDK of uni API Note: It must be imported after the body. Importing in the head may fail to obtain -->
  <script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>
</html>

Redirect page:

<template>
  <div></div>
</template>
<script>
export default {
  name: "LoginCallback",
  mounted() { // In the mounted lifecycle, listen for the parameters carried after DingTalk redirection and return them to uniapp
    document.addEventListener("plusready", () => {
      this.$nextTick(() => {
        // After the `UniAppJSBridgeReady` event is triggered, you can call the uni API. If you don't call it as soon as the page is opened, you don't need this listener document.addEventListener("UniAppJSBridgeReady", () => {
          // this.$toast("location.search:::", JSON.stringify(location.search));
          if (location.search.includes("?code")) {
            console.log("getCode:::");
            let code = location.search.split("?")[1].split("&")[0].split("=")[1]; // After getting the code here, jump back to the uniapp page through the uni API and carry the parameters (obtained in onLoad in uniapp) or pass it through uni.postMessage({data: [code]}) provided by uniapp (Note: the parameters passed through postMessage get the data in uniap as an array)
            uni.webView.navigateTo({
              url: `/pages/login/login_webview?code=$[code]`
            });
          }
        });
      });
    });
  }
};
</script>

3. In uniapp, you can use webview to host the webpage for scanning the code on DingTalk and receive the code parameters obtained after scanning the code on DingTalk

<script>
    import { dingLogin } from '@/api/login'
    import { setToken } from "@/utils/auth"
    export default {
        name: "LoginWebview",
        data() {
            return {
                url: 'http://xxxxxxx/dd_login' // The url here is the DingTalk QR code scanning webpage address written in step 1}
        },
        onLoad(options) { // This is the parameter code returned after scanning the code for login if (options.code) {
                this.login(options.code)
            }
        },
        methods: {
            async login(code) {
                uni.showLoading()
                try {
                    const res = await dingLogin(code)
                    if (res.data.code === 200) {
                        setToken(res.data.token)
                        uni.reLaunch({
                            url: '/pages/home/index'
                        })
                    }
                    uni.hideLoading()
                } catch (e) {
                    console.log('Login failed', e)
                    uni.hideLoading()
                }
            }
        }
    }
</script>

Okay, it’s done! ! !

If you need to return to uniapp from the DingTalk scan code page to switch login methods, you can jump back to uniapp through uni's API

uni.webView.navigateTo({
    url: "/pages/login/index"
});

This is the end of this article about how to implement DingTalk QR code scanning login on uniapp. For more information about how to implement DingTalk QR code scanning login on uniapp, please search previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Use UniApp to implement WeChat login function of mini program

<<:  Measured image HTTP request

>>:  Detailed explanation of the difference and usage of quotes and backticks in MySQL

Recommend

How to insert pictures into HTML pages and add map index examples

1. Image formats supported on the WEB: GIF: can s...

Vue implements three-dimensional column chart based on echarts

The three-dimensional column chart consists of th...

How a select statement is executed in MySQL

Table of contents 1. Analyzing MySQL from a macro...

How to get USB scanner data using js

This article shares the specific process of js ob...

Detailed explanation of CocosCreator project structure mechanism

Table of contents 1. Project folder structure 1. ...

Two ways to introduce svg icons in Vue

How to introduce svg icons in Vue Method 1 of int...

Zabbix configures DingTalk's alarm function with pictures

Implementation ideas: First of all, the alarm inf...

Syntax alias problem based on delete in mysql

Table of contents MySQL delete syntax alias probl...

Detailed explanation of how to use element-plus in Vue3

Table of contents 1. Installation 2. Import in ma...

Importance of background color declaration when writing styles

As the title says, otherwise when the page is revi...

Solution for Nginx installation without generating sbin directory

Error description: 1. After installing Nginx (1.1...

MySQL column to row conversion, method of merging fields (must read)

Data Sheet: Column to row: using max(case when th...

Overview and differences between html inline elements and html block-level elements

Block-level element features : •Always occupies a ...

Detailed explanation of the fish school algorithm in CocosCreator game

Preface I recently wanted to learn CocosCreator, ...