Recently, I have developed an H5 project with UNI-app, in which a third-party wechat authorized login is used. It is my first time to do this, and I share the idea of implementation with you. I hope it will be helpful to you!

WeChat authorization

There are two ways of wechat authorization: silent authorization and non-silent authorization.

Silent authorization: scope=snsapi_base. There are no pop-ups, only the openID of the user can be retrieved.

Non-silent authorization: scope=snsapi_userinfo. There is a popup window, which requires the user to manually click “Agree authorization” to obtain the user’s OpenID, nickname, profile picture and gender.

Authorization process

1. Once the page is loaded, check whether there is a code (because the current page will be refreshed after the authorization is successful, check whether there is a code when the page is loaded. If there is a code, directly send it to the background server)

onLoad(e) {
    let code = this.getUrlCode('code')
    console.log(code)
    if(code ! = =null|| code ! = ="") {
        this.getOpenidAndUserinfo(code)
    }
},
Copy the code

2. Access the authorization page and obtain the code

/ / access code
    // Check whether there is code in the URL. If there is code, it indicates authorization. If there is no code, jump to wechat authorization link
    getCode () {
        if(isWechat()) {
            // Intercept the code in the address, if there is no code, go to wechat for authorization, if the code has been obtained, directly send the code to the background to obtain openId
            let code = this.getUrlCode('code')
            if (code === null || code === ' ') {
                window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+appid+'&redirect_uri=' + encodeURIComponent('http://127.0.0.1/pages/views/profile/login/login') + '&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'
                // redirect_uri is the redirect URL after the authorization is successful. Wechat will help us to redirect to this link and pass? In the form of splicing code, here you need to use encodeURIComponent for link processing.
                // If the configuration parameters match one to one, you will see the code in the address bar after the page is refreshed by calling back the address.
                / / http://127.0.0.1/pages/views/profile/login/login? code=001BWV4J1lRzz00H4J1J1vRE4J1BWV4q&state=1
            }
        }
    },
    
    getUrlCode (name) {
        return decodeURIComponent((new RegExp('[? | &]' + name + '=' + '([^ &;] +? (& # | |; | $) ').exec(location.href) || [, ' '[])1].replace(/\+/g.'% 20')) || null
    },
    
    const isWechat = (a)= > {
        return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i= = =))"micromessenger";
    }
Copy the code

Parameters that

parameter Whether must instructions
appid is The unique identifier of the public account
redirect_url is A callback link address redirected after authorization needs to be processed using encodeURIComponent for the link
response_type is Return type, please fill in code
scope is If the authorization mode is SNSAPi_BASE (the authorization page is not displayed, and only the user’s OpenID can be obtained), if the authorization mode is SNsapi_userinfo (the user needs to manually click the authorization page to obtain the user’s OpenID, nickname, profile picture, and gender).
state no After the redirect, the state parameter will be added. The developer can fill in the value of the a-zA-Z0-9 parameter, which is up to 128 bytes
#wechat_redirect is This parameter must be set when you open the page or perform page 302 redirection

Description of web page authorization callback domain name

How do I change the authorization callback domain name? — Enter the “development – Interface permissions – Web services – Access to basic user information – modification” in the official website of the public account platform.

3. Send the code to the background server through the interface

getOpenidAndUserinfo(code) {
    uni.request({
        url: 'http://127.0.0.1/api/wxLogin? code='+code+'&state=state&appid='+appid,
        success: (res) = > {
            console.log('Get openID and accessToken with code', res)
            if(res.data.code === 200) {
                // If the login succeeds, the user information and token can be saved to the cache
                uni.setStorageSync('userInfo', res.data.result.userInfo)
                uni.setStorageSync('token', res.data.result.token)
            }
        }
    })
Copy the code

4. The front end gets the data returned by the back end

The data returned is in the following format:

{
    code: 200
    message: "Login successful"
    result: {
        token: "54f663ca-45d4-4758-97a7-f727b942c09a"
        userInfo: {
            avatar: "http://thirdwx.qlogo.cn/mmopen/vi_32/MXuWgYbeVv5icyS4XBz28vpdh4iaRJAP3WYQ2uHMBUFcjvcHwykZ5wYPJG4CibJGAMv73n813vypau7Rs4 iaA1uiaIw/132".nickName: "Allen".sex: 2.openid: "oPSEKwuzvwfZ5NEHhn9FBMJrNXpM".unionid: "o_ra9t3byZL5dMG1M-p2xOBFRAyc",}}}Copy the code

Parameters that

parameter describe
avatar The last value represents the size of square head (0, 46, 64, 96, 132 are optional, 0 represents 640 x 640 square head). This parameter is null if the user does not have an image. If the user changes the profile picture, the URL of the original profile picture becomes invalid.
nickName The user nickname
sex User gender. A value of 1 is female, a value of 2 is male and a value of 0 is unknown
openid Unique identification of a user
unionid This field will only appear after the user binds the public account to the wechat open platform account

About the UnionID mechanism

Reference link: wechat Open document

Because it was the first time to contact the third-party wechat authorization function, so I also explored for a day or two, in fact, looking at the official documents, step by step to achieve, or quite simple. To my summary, there is a mistake, please each big guy correct!