preface

In our daily work, we should be more or less exposed to wechat authentication login, access to user information related requirements. Also some friends often ask some related questions in the group, such as

  • What is the overall process of authenticated login?
  • In the whole process, what is the division of labor between the front end and the back end?
  • An authentication callback page is prepared. How do I return to the page before authentication?
  • How to test wechat webpage authorization locally?

First look at wechat official authentication process how to describe

  1. Step 1: The user agrees to authorize and gets the code
  2. Step 2: Exchange web authorization access_token with code
  3. Step 3: Refresh the access_token (if necessary)
  4. Step 4: Pull user information (scope is snsapi_userinfo)

Still ignorant, it doesn’t matter, I specially prepared a small 🌰 here, to achieve a simple version of the web page authorization + access to user information function, the whole process is probably like this

In this process, the front end does not have to do much, just need to determine whether there is user information, if not, the rest of the work to the server, and when the server is finished, it will return to the previous page with user information.

And the front end does not need to prepare a special authorization result page.

process

Step 1: Intranet mapping

Download the software

Download it at ngrok.com/download

When you unzip it, you get this thing

Terminal start

Drag the extracted file to the terminal and write HTTP 3000, which means using ngrok to open an HTTP mapping tunnel on port 3000.

If the following screen appears after startup, it indicates success.

This is the domain name we need: https://0772-183-159-254-252.ngrok.io.

Step 2: wechat test number

Logging in to the test Account

The login address: mp.weixin.qq.com/debug/cgi-b…

At present, we have got appID and AppSecret. The interface configuration information and JS interface security domain name are not concerned for the time being, and webpage authorization is not available.

Example Modify the authorization callback domain name

Page down, page service => Page account => Modify

Fill in the Intranet mapping address you got earlier without writing https://

Scan for test numbers

Because if you don’t, the test authorization will report an error

Step 3: Build the project

Here we use the Express node framework

package.json

{
  "name": "simple-wx-auth-by-express"."version": "1.0.0"."scripts": {
    "start": "node index.js"
  },
  "dependencies": {
    "axios": "^ 0.21.4"."express": "^ 4.17.1"
  },
  "devDependencies": {}}Copy the code

index.js

Note fill in the previous Intranet mapping address, wechat test number appID and AppSecret to the corresponding position.

const express = require('express');
const app = express();
const axios = require('axios');
const port = 3000; // Start port

const SERVICE_URL = 'https://0772-183-159-254-252.ngrok.io'; // Server address, enter the Intranet mapped address here
const appID = ' '; // wechat test number appID
const appsecret = ' '; // wechat test number appSecret

/ * * *@description Concatenate the full authorized address *@param {string} The address before the webUrl front end calls authorization (the address that needs to be returned after authorization ends) *@date: 2021/9/27 * /
const getAuthUrl = (webUrl) = > {
    let redirectUri = encodeURIComponent(`${SERVICE_URL}/wxBack? webUrl=${webUrl}`);
    return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appID}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo#wechat_redirect`
}

/ * * *@description Get accessToken and OpenID *@param {string} Code Indicates the authorized code *@date: 2021/9/27 * /
const getAccessTokenByCode = async (code) => {
    let {data} = await axios.get(`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appID}&secret=${appsecret}&code=${code}&grant_type=authorization_code`)
    return data
}

/ * * *@description Obtain wechat user information *@param {string} accessToken
 * @param {string} Openid User openID *@date: 2021/9/27 * /
const getUserInfo = async (accessToken, openid) => {
    let {data} = await axios.get(`https://api.weixin.qq.com/sns/userinfo?access_token=${accessToken}&openid=${openid}&lang=zh_CN`)
    return data
}

// Front-end page
app.get('/user'.(req, res) = > res.sendFile(__dirname + "/" + "user.html"));

// Step 1: Redirect to wechat
app.get('/goAuth'.(req, res) = > {
    // Get the front-end address of the call authorization
    let {webUrl} = req.query;
    // Get the full address of authentication
    let authUrl = getAuthUrl(webUrl);
    / / redirection
    res.redirect(authUrl);
})

// Step 2: wechat redirects back to the service
app.get('/wxBack'.async (req, res) => {
    // Get the code and the front-end address of the call authorization
    let {webUrl, code} = req.query;
    / / get accessToken
    let {access_token, openid} = await getAccessTokenByCode(code);
    // Get user information
    let {nickname, headimgurl} = await getUserInfo(access_token, openid);
    // Redirect back to the front end
    headimgurl = headimgurl.replace('thirdwx.qlogo.cn'.'wx.qlogo.cn');
    res.redirect(`${webUrl}? openid=${openid}&nickname=${nickname}&headimgurl=${headimgurl}`);
})

app.listen(port, () = > {
    console.log(`app listening at http://localhost:${port}`)})Copy the code

user.html

This is a page specially used for testing, because we only need to check whether we get the user information, so we just simply get the OpenID and user profile picture.

  • Check whether the URL carries openIDIf not, redirects directly to the server address to start authorization.
  • If so, justDisplay the avatars directly on the page;
  • Note: You also need to modify the Intranet mapping address
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script SRC = "https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js" > < / script > < / head > < body > < div id = "app" > < / div > < script > var SERVICE_BASE = 'https://0772-183-159-254-252.ngrok.io' // Server address of Intranet mapping // Obtain URL parameters function getQueryVariable() {var url =  location.search; // Get the "?" in the url Var theRequest = new Object(); if (url.indexOf("?" )! = -1) { var str = url.substr(1); strs = str.split("&"); for (var i = 0; i < strs.length; i++) { theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]); } } return theRequest; Function getUserInfo() {var params = getQueryVariable(); var openid = params.openid; if (! Openid) {// Start authorization window.location.href = SERVICE_BASE + '/goAuth? webUrl=' + window.location.href; <img SRC ="${params.headimgURL}"> 'let app = document.getelementById ('app'); app.innerHTML = html; } } window.addEventListener('load', function () { getUserInfo(); }) </script> </body> </html>Copy the code

Step 4: Test

Install dependencies

npm install
Copy the code

Start the project

npm run start
Copy the code

Wechat visit page

https://0772-183-159-254-252.ngrok.io/user
Copy the code

If nothing else, after visiting the page, you should be able to pop up an authorization, consent and return to the page with your avatar.

Here because I agreed to authorize, so did not pop out again ~

Git address

Address: github.com/zhuyuqian/s…

conclusion

In fact, many partners are not clear about the whole process of authorization, front-end and back-end specific division of labor is…

Especially let the front end in order to authorize a special callback page, PERSONALLY said that it is really uncomfortable to do 😣

This small 🌰 most of the core processes are in the index.js file, I hope to help you ~

Just like 👍 ~ ~ ~