WeChat page authorization and access to user information


In many WeChat H5 applications, when users visit third-party applications, they need to conduct WeChat web page authorization, and many operations involving security must first obtain user information before proceeding. This article briefly introduces the WeChat authorization process, and simulate web page authorization by applying for WeChat test account. After the user clicks “OK” on the authorization page, the user information is obtained and displayed on the front page. The final effect is as shown below

Tools and development preparation

1. WeChat developer tool and WeChat test number

Since it is licensed by WeChat, it must be used in WeChat environment. First of all, we need to install WeChat developer tools here. Since we don’t have our own application, we also need to apply for an interface test number on the WeChat public platform, which is equivalent to our third-party application.

2. Parameter setting

After logging in the test number, you can view your AppID and AppSecret information. Modify the basic information of user authorized to obtain web page in the permission table of the experience interface to This address is the address that the user calls back after confirming authorization, namely the background processing address of our application, as shown in the figure below

Finally, take out your own WeChat scan code to pay attention to the test number, as shown in the figure below

WeChat authorization process introduction

The specific process and detailed introduction can be viewed in the technical documents of the WeChat public platform on the official website, which can be roughly divided into four steps:

  1. Guide the user to the authorization page to approve authorization, and then call the WeChat API to get the code
  2. After authorization passes, the code parameter requests the callback address
  3. The background acquires the code, and calls the WeChat interface again to exchange the access_token and openID for the authorization of the webpage
  4. Access the user’s basic information via the access_token and openID authorization on the web page (if there is a unionID, the unionID parameter will also be obtained).

The official start of the

The detailed code can be downloaded at GitHub

1. Raw code

let express = require("express"); const https = require('https'); let app = express(); //appID let appID = `wxec6fa9e9bc03d885`; //appsecret let appSerect = `4c8a0d14cff08959b4e17334cabf9cf0`; // Let redirectUrl = '/getUserInfo'; Let the host = ` `; // WeChat authorization API, the interface returns code, click authorization to redirect to the address with the code parameter let authorizeUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appID}&redirect_uri=` + `${host}${redirectUrl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect` app.get("/login", function(req, res) { res.sendFile(path.resolve(__dirname,'login.html')); }); app.get("/auth", function(req, res) { res.writeHead(302, { 'Location': authorizeUrl }); res.end(); }); app.get("/getUserInfo", function(req, res) { let code = req.query.code; let getaccess = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=` + `${appID}&secret=${appSerect}&code=${code}&grant_type=authorization_code`; Get (getAccess, (resText) => {var DDD = ""; resText.on('data', (d) => { ddd += d; }); resText.on('end', () => { // console.log(ddd); var obj = JSON.parse(ddd); var access_token = obj.access_token; var open_id = obj.openid; // Get userInfo from the access_token and open_id obtained in the previous step let getUserURL = `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${open_id}&lang=zh_CN`; https.get(getUserUrl, (resText) => { user = ""; resText.on('data', (d) => { user += d; }); resText.on('end', () => { console.log(user); var userobj = JSON.parse(user); res.send(userobj); console.log(userobj); }); })}); }).on('error', (e) => { console.error(e); }); // res.end(); }); app.listen(3000);

We need to change the AppID and AppSerect to your corresponding parameters, because our request is in a certain order, but Node sends the request asynchronously, so our request is nested three layers, the code is very ugly, so here we can use async and await of ES6 to solve the asynchronous callback Hell.

2. Improved code for async and await using ES6

Async function wxAuth(req, res) {let code = req.query.code; Let resObj = await getAccessToken(code); Access_token = resobj. access_token; let open_id = resObj.openid; Let userObj = await getUserInfo(access_token, open_id); console.log(userObj); res.render(path.resolve(__dirname,'userInfo.ejs'), {userObj: userObj}); // res.send(userObj); } function getAccessToken(code) {return new Promise((resolve,);} function getAccessToken(code) {return new Promise((resolve,); reject) => { let getAccessUrl = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=` + `${appID}&secret=${appSerect}&code=${code}&grant_type=authorization_code`; https.get(getAccessUrl, (res) => { var resText = ""; res.on('data', (d) => { resText += d; }); res.on('end', () => { var resObj = JSON.parse(resText); resolve(resObj); }); }).on('error', (e) => { console.error(e); }); }); } function getUserInfo(access_token, access_token, access_token); open_id) { return new Promise( (resolve, reject) => { let getUserUrl = `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${open_id}&lang=zh_CN`; https.get(getUserUrl, (res) => { var resText = ""; res.on('data', (d) => { resText += d; }); res.on('end', () => { var userObj = JSON.parse(resText); resolve(userObj); }); }).on('error', (e) => { console.error(e); }); }) } app.listen(8800);

After the modification, the code flow is much clearer. Finally, the obtained UserObj is rendered in the front page through the EJS template, and you can see the renderings shown at the beginning of the article.

Write in the last

Recently, I have been an intern in a company. Influenced by colleagues around me, I began to write an article to record my learning experience. This is my first time to write an article, so I may not be good at it.