preface
First, let’s take a look at a picture from wechat’s open document:The whole process of wechat login is clearly introduced in the picture above. The following is a summary as shown in the picture:
First, the two-dimensional code
- After the user opens the login page, the login page background according to wechat
OAuth2.0
The agreement requests authorized login to the wechat development platform, and delivers the approved login information in advanceAppID
andAppSecrect
Parameters such as; - Wechat development platform yes
AppID
And return the TWO-DIMENSIONAL code to the background of the login page; - Login webpage background will be sent to the two-dimensional code display;
2. Authorized login of wechat client
- The user uses the wechat client to scan the QR code and authorize login;
- Wechat client will qr code specific
uid
Bind with wechat account and send to wechat development platform; - Wechat development platform to verify binding data,Invoke the callback interface of the login page backgroundTo send the authorized provisional note
code
;
Third, webpage background request data
- Received after logging in to the web page
code
, indicating that the wechat development platform agrees to the data request; - Login page background based on
code
Parameter, plusAppID
andAppSecret
Request wechat development platform for exchangeaccess_token
; - The wechat development platform verifies the parameters and returns
access_token
; - Login page background received
access_token
Then the user account data can be obtained by parameter analysis.
implementation
Now that we know the basics, we can implement the logic simply. Because there is no direct call wechat development platform, so here is just a demonstration effect. You can also visit https://www.maomin.club/qrcodelogin/ my online site experience. The following code is the main logic, easier to understand with the online experience.
let http = require("http");
let express = require("express");
let qrcode = require("qr-image");
let app = express();
let path = require("path");
let server = http.createServer(app);
let url = require("url");
let fs = require("fs");
let UUID = require("uuid-js");
let generateHTML = null;
app.use(express.static("./public"));
/* * Params: /* * Params: /* * Params: * sessionID - generated UID * req - Webpage request * res - webpage reply * fileName - webpage file path */
generateHTML = function (sessionID, req, res, fileName) {
fs.readFile(fileName, "UTF-8".function (err, data) {
if(! err) { data = data.replace(/SESSION_UID/g, sessionID);
res.writeHead(200, {
"Content-Type": "text/html; charset=UTF-8"}); res.end(data); }else {
console.log(err);
res.writeHead(404, {
"Content-Type": "text/html; charset=UTF-8"}); res.end(); }}); };/* * Description: Write JSON file * Params: * fileName - JSON file path * uid - Generated UID * writeData - JSON data to be written * */
let setJSONValue = function (fileName, uid, writeData) {
let data = fs.readFileSync(fileName);
let users = JSON.parse(data.toString());
let addFlag = true;
let delFlag = writeData === null;
for (let i = 0; i < users.data.length; i++) {
if (users.data[i].uid === uid) {
addFlag = false;
if (delFlag) {
users.data.splice(i, 1);
} else {
users.data[i].status = writeData.status;
console.log(
"writeJSON: " + JSON.stringify(users.data[i]) + " modified."); }}}if (addFlag) {
users.data.push(writeData);
console.log("writeJSON: " + JSON.stringify(writeData) + " inserted.");
}
// Write files synchronously
let writeJSON = JSON.stringify(users);
fs.writeFileSync(fileName, writeJSON);
};
* Params: * fileName - JSON file path * uid - generated UID * */
getJSONValue = function (fileName, uid) {
let readData = null;
// Read files synchronously
let data = fs.readFileSync(fileName);
let users = JSON.parse(data.toString());
for (let i = 0; i < users.data.length; i++) {
if (users.data[i].uid === uid) {
readData = JSON.stringify(users.data[i]);
break; }}return readData;
};
// Display the homepage of the website
app.get("/".function (req, res) {
// Generate a unique ID
let uid = UUID.create();
console.log("uid: '" + uid + "' generated.");
// Replace the UID keyword in the web page template
generateHTML(uid, req, res, path.join(__dirname, "/views/main.html"));
});
// Generate a qr code picture and display it
app.get("/qrcode".function (req, res, next) {
let uid = url.parse(req.url, true).query.uid;
try {
if (typeofuid ! = ="undefined") {
// Write the url in the TWO-DIMENSIONAL code, wechat will automatically jump after scanning. The following website is my web site, https://www.maomin.club/qrcodelogin, you can switch to your own online website or the local server. Plus the following "/scanned? uid="
let jumpURL = "https://www.maomin.club/qrcodelogin/scanned?uid=" + uid;
// Generate qr code (size: image size, margin: blank)
let img = qrcode.image(jumpURL, { size: 6.margin: 2 });
res.writeHead(200, { "Content-Type": "image/png" });
img.pipe(res);
} else {
res.writeHead(414, { "Content-Type": "text/html" });
res.end("<h1>414 Request-URI Too Large</h1>"); }}catch (e) {
res.writeHead(414, { "Content-Type": "text/html" });
res.end("<h1>414 Request-URI Too Large</h1>"); }});// Display the confirmation interface after the mobile phone scan
app.get("/scanned".function (req, res) {
let uid = url.parse(req.url, true).query.uid;
if (typeofuid ! = ="undefined") {
generateHTML(uid, req, res, path.join(__dirname, "/views/confirm.html"));
console.log("uid: '" + uid + "' scanned.");
// Get the data corresponding to the UID in the JSON file and change its data state
let jsonData = getJSONValue(path.join(__dirname, "/bin/data.json"), uid);
if (jsonData === null) {
jsonData = {
uid: uid,
status: "scanned".name: "USER"}; }else {
jsonData = JSON.parse(jsonData);
jsonData.status = "scanned";
}
// Write a JSON file
setJSONValue(path.join(__dirname, "/bin/data.json"), uid, jsonData);
} else {
res.writeHead(414, { "Content-Type": "text/html" });
res.end("<h1>414 Request-URI Too Large</h1>"); }});// The response of the operation in the confirmation screen
app.get("/confirmed".function (req, res) {
let uid = url.parse(req.url, true).query.uid;
let operate = url.parse(req.url, true).query.operate;
if (typeofuid ! = ="undefined") {
console.log("uid: '" + uid + "'" + operate);
let jsonData = getJSONValue(path.join(__dirname, "/bin/data.json"), uid);
let status = operate === "confirm" ? "verified" : "canceled";
if (jsonData === null) {
jsonData = {
uid: uid,
status: status,
name: "USER"}; }else {
jsonData = JSON.parse(jsonData);
jsonData.status = status;
}
setJSONValue(path.join(__dirname, "/bin/data.json"), uid, jsonData);
if (status === "verified") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end(" Login successful!
");
} else {
res.writeHead(200, { "Content-Type": "text/html" });
res.end("Canceled!
"); }}else {
res.writeHead(414, { "Content-Type": "text/html" });
res.end("414 Request-URI Too Large
"); }});// Respond to the home page's constant AJAX requests
app.get("/verified".function (req, res) {
let uid = url.parse(req.url, true).query.uid;
// normal - There is no trigger
// Scanned - Scanned
Canceled - Canceled
// Verified - Verified
let dataStatus = {
cmd: "normal".user: ""};console.log("uid: '" + uid + "' query ...");
if (typeofuid ! = ="undefined") {
let userData = getJSONValue(path.join(__dirname, "/bin/data.json"), uid);
// Returns JSON data for home page AJAX operations
if(userData ! = =null) {
userData = JSON.parse(userData);
dataStatus.cmd = userData.status;
dataStatus.user = userData.name;
}
}
res.end(JSON.stringify(dataStatus));
});
server.listen(4000);
console.log(
"Express server listening on port %d in %s mode",
server.address().port,
app.settings.env
);
Copy the code
See here, you do not feel that the code is not complete, I gave a main logic code, don’t worry, the code is full han full table immediately provided, code explanation can see the comments oh! The following is the github website, if you find it useful, welcome star~
https://github.com/maomincoding/qrcodelogin.git
Copy the code
conclusion
So if you look at this, you might just pull the code and see why the project doesn’t work. It’s not as effective as an online address. Well, if you get your server wired, you can deploy it to the cloud. If you don’t have an online server, you can set up your own local area network server. Make sure your phone is on the same IP segment as your computer’s web page.
- Welcome to pay attention to my public number front end experience robbed road
- Reply keywords e-books, you can get 12 front-end popular e-books.
- Reply keywords little Red Book 4th edition, you can get the latest “JavaScript advanced Programming” (4th edition) ebook.
- After following the official account, click the menu below to add my wechat. I have attracted many IT bigwigs and created a technical exchange and article sharing group. I look forward to your joining.