uni-app WeChat applet authorization login implementation steps

uni-app WeChat applet authorization login implementation steps

insert image description here

1. Application and configuration of appID

1. How to obtain appid

Log in to WeChat public platform

Official website link: https://mp.weixin.qq.com/

For the first time, you need to click the registration button to register. If you have an account, just scan and log in.

insert image description here

Official website mini program link:

insert image description here

2. AppID configuration

Enter the WeChat applet id you applied for in manifest.json

insert image description here

2. Obtaining basic user data

Here are two APIs for you to see.

2.1. Obtaining User Information

You can use uni.getUserProfile to request user authorization to obtain user information, or you can use uni.getUserInfo to obtain

insert image description here

After successful authorization, the user information obtained is in userInfo:

insert image description here

Page Sections:

 <button class="login-btn" type="primary" @click="getUserInfo">
        WeChat users can log in with one click</button>

js part:

 methods: {
    getUserInfo() {
      uni.getUserInfo({
        provider: 'weixin',
        success: (res) => {
          console.log('getUserInfo', res);
        },
      });
    },
   }

Obtained user basic data (without openid=》WeChat user unique identifier)

insert image description here

2.2. Get user information 2

You can use uni.getUserInfo to request user authorization to obtain user information

The page is the same, the js part:

 getUserInfo() {
      uni.getUserProfile({
        desc: 'You can synchronize data after logging in',
        lang: 'zh_CN',
        success: (res) => {
          console.log('getUserProfile', res);
        },
      });
    },

Obtained user basic data (without openid=》WeChat user unique identifier)

insert image description here

Summary: The user data obtained by the two APIs uni.getUserProfile and uni.getUserInfo are basically the same, and both do not have openid=》WeChat user unique identifier.

3. Call login api

3.1. Login API

Use the uni.login method, enter 'weixin' as the provider parameter, and if errMsg = "login:ok" in the successful return value, it means success.
The WeChat applet will return a code string

insert image description here

3.2. Example Code

 uni.login({
            provider: 'weixin',
            success: (res) => {
              console.log('res-login', res);
              this.code = res.code;
              console.log('code', res.code);
              if (res.errMsg == 'login:ok') {
              //TODO Get code and call the backend interface with code parameter}

4. Obtaining unique identification information

4.1. Official website documentation

The official website document uses the obtained code to request the WeChat login interface to obtain openid and session_key

insert image description here

4.2. Interface Description

insert image description here

Request method: GET
APPID: The unique identifier of the mini program. You can find the method to obtain it above.
SECRET: The secret key that uniquely identifies the mini program. Please refer to the APPID acquisition method above. It is just below it.
JSCODE: This front-end calls uni.login to obtain

GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

insert image description here

5. Bind user to log in

After obtaining the unique ID of the WeChat user, you can bind it to the user in your own system. What I do is add the weixinId field to the user table and jump to my own user binding interface. If the user chooses to bind WeChat, the weixinId of the user data in that row will be updated. The next time the user logs in using WeChat, if a user data can be queried through openId, it means that it has been bound, and the user is logged in

5.1. Code Examples (Unpackaged)

Front-end part:

 /**
     *
     * Get user information */
    getUserInfo() {
      // Display the loading box uni.showLoading({
        title: 'Loading',
      });
      uni.getUserProfile({
        desc: 'You can synchronize data after logging in',
        success: async (obj) => {
          console.log('obj', obj);
          //Call action and request login interface // await this.login(obj);
          uni.login({
            provider: 'weixin',
            success: (res) => {
              console.log('res-login', res);
              this.code = res.code;
              console.log('code', res.code);
              if (res.errMsg == 'login:ok') {
                uni
                  .request({
                    url:
                      'http://127.0.0.1:8080/wxh5/wx/user/' +
                      'wx55822xxxx75e422' +
                      '/login/',
                    data: {
                      code: this.code,
                    },
                  })
                  .then((res) => {
                  //After getting openid and session_k, your own logic console.log('Authorized login', res[1].data);
                    console.log(res[1].data.openid);
                    console.log(res[1].data.session_key);
                    // DoSomeThing.................
                  });
                console.log('res', res);
              }
            },
          });
        },
        fail: () => {
          uni.showToast({
            title: 'Authorization canceled',
            icon: 'error',
            mask: true,
          });
        },
        complete: () => {
          //Hide loading
          uni.hideLoading();
        },
      });
    },

Backend

 @GetMapping("/login")
    public String login(@PathVariable String appid, String code) {
        if (StringUtils.isBlank(code)) {
            return "empty jscode";
        }

        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            this.logger.info(session.getSessionKey());
            this.logger.info(session.getOpenid());
            //TODO can add its own logic and associate business-related data return JsonUtils.toJson(session);
        } catch (WxErrorException e) {
            this.logger.error(e.getMessage(), e);
            return e.toString();
        }
    }

5.2. Code Examples (Packaging)

 /**
     *
     * Get user information */
    getUserInfo() {
      // Display the loading box uni.showLoading({
        title: 'Loading',
      });
      uni.getUserProfile({
        desc: 'You can synchronize data after logging in',
        success: async (obj) => {
          // this.userInfo = obj.userInfo;
          // Call action to request login interface uni.login({
            provider: 'weixin',
            success: async (res) => {
              this.code = res.code;
              // console.log('Log in to get code', res.code);
              if (res.errMsg == 'login:ok') {
                await this.loginAuth({
                  userProfile: obj,
                  appid: 'wx558xxxxxxxxxxxxxxx2',
                  code: this.code,
                });
              }
            },
          });
        },
        fail: () => {
          uni.showToast({
            title: 'Authorization canceled',
            icon: 'error',
            mask: true,
          });
        },
        complete: () => {
          //Hide loading
          uni.hideLoading();
        },
      });
    },
  },

user.js

 /**
 * WeChat user authorized login, carrying appid and code parameters, calling the backend interface to obtain Openid
 */
export function loginAuth(data) {
  return request({
    url: '/wx/user/' + data.appid + '/login/',
    data: {
      code: data.code,
    },
  });
}

vuex user module (user.js)

 // WeChat user authorized login, carrying appid and code parameters, calling the backend interface to obtain Openid
    async loginAuth(context, data) {
      console.log('data', data);
      const userInfo = data.userProfile;
      const { content: res } = await loginAuth({
        appid: data.appid,
        code: data.code,
      });

      // Parse the JSON object sent by the backend const userAuthInfo = JSON.parse(res);
      const openid = userAuthInfo.openid;
      // console.log('sessionKey', userAuthInfo.sessionKey);
      console.log('openid', openid);

      // Save to vuex and commit
      this.commit('user/setOpenid', userAuthInfo.openid);
      this.commit('user/setUserInfo', JSON.parse(userInfo.rawData));
    },

insert image description here

insert image description here

6. Project open source address

6.1. Frontend

applet-chock-in

6.2. Backend

weixin-java-miniapp

This is the end of this article about uni-app WeChat applet authorized login. For more relevant uni-app WeChat applet authorized login content, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Use uni-app to generate WeChat applet pitfall records
  • WeChat Mini Programs are shared globally via uni-app
  • Implementation of login authorization for uni-app WeChat applet
  • Example of how to convert a WeChat applet into a uni-app project
  • uni-app develops WeChat applet positioning function

<<:  Introduction to container data volumes in Docker

>>:  Example of how to achieve semi-transparent background image and opaque content in CSS3

Recommend

MYSQL 5.6 Deployment and monitoring of slave replication

MYSQL 5.6 Deployment and monitoring of slave repl...

Tutorial on installing AutoFs mount service under Linux

Whether it is Samba service or NFS service, the m...

A brief analysis of the usage of USING and HAVING in MySQL

This article uses examples to illustrate the usag...

...

Mobile web screen adaptation (rem)

Preface I recently sorted out my previous notes o...

Implementation of react routing guard (routing interception)

React is different from Vue. It implements route ...

How to import Tomcat source code into idea

Table of contents 1. Download the tomcat code 2. ...

MySQL 8.0.24 installation and configuration method graphic tutorial

This article shares the installation tutorial of ...

Example of using JS to determine whether an element is an array

Here are the types of data that can be verified l...

The difference between z-index: 0 and z-index: auto in CSS

I've been learning about stacking contexts re...

How to implement Mysql scheduled tasks under Linux

Assumption: The stored procedure is executed ever...

How to recover files accidentally deleted by rm in Linux environment

Table of contents Preface Is there any hope after...