手寫一個仿微信登錄的Nodejs程序
前言
首先,我們看一下微信開放文檔中的一張圖:
上面的一幅圖中清楚地介紹了微信登錄整個過程,下面對圖上所示進行總結:
一、二維碼的獲得
- 用戶打開登錄網頁后,登錄網頁后臺根據(jù)微信OAuth2.0協(xié)議向微信開發(fā)平臺請求授權登錄,并傳遞事先在微信開發(fā)平臺中審核通過的AppID和AppSecrect等參數(shù);
- 微信開發(fā)平臺對AppID等參數(shù)進行驗證,并向登錄網頁后臺返回二維碼;
- 登錄網頁后臺將二維碼傳送至前臺進行顯示;
二、微信客戶端授權登錄
- 用戶使用微信客戶端掃描二維碼并授權登錄;
- 微信客戶端將二維碼特定的uid與微信賬號綁定,傳送至微信開發(fā)平臺;
- 微信開發(fā)平臺驗證綁定數(shù)據(jù),調用登錄網頁后臺的回調接口,發(fā)送授權臨時票據(jù)code;
三、網頁后臺請求數(shù)據(jù)
- 登錄網頁后臺接收到code,表明微信開發(fā)平臺同意數(shù)據(jù)請求;
- 登錄網頁后臺根據(jù)code參數(shù),再加上AppID和AppSecret請求微信開發(fā)平臺換取access_token;
- 微信開發(fā)平臺驗證參數(shù),并返回access_token;
- 登錄網頁后臺收到access_token后即可進行參數(shù)分析獲得用戶賬號數(shù)據(jù)。
實現(xiàn)
了解了大致原理之后,我們就開始簡單實現(xiàn)這個邏輯。因為沒有直接調用微信開發(fā)平臺,所以這里只是演示效果。你也可以通過訪問:
- https://www.maomin.club/qrcodelogin/
這個我的線上網址體驗一下。以下代碼是主要邏輯,結合線上網址體驗更容易理解。
- 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"));
- /*
- * Description: 讀取網頁文件,用于替換關鍵字,相當于簡易模板
- * Params:
- * sessionID - 生成的uid
- * req - 網頁請求
- * res - 網頁應答
- * fileName - 網頁文件所在路徑
- */
- 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: 寫入JSON文件
- * Params:
- * fileName - JSON文件所在路徑
- * uid - 生成的uid
- * writeData - 需要寫入的JSON格式數(shù)據(jù)
- *
- */
- 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.");
- }
- // 同步寫入文件
- let writeJSON = JSON.stringify(users);
- fs.writeFileSync(fileName, writeJSON);
- };
- /*
- * Description: 讀取JSON文件(要返回數(shù)據(jù),選擇同步讀取)
- * Params:
- * fileName - JSON文件所在路徑
- * uid - 生成的uid
- *
- */
- getJSONValue = function (fileName, uid) {
- let readData = null;
- // 同步讀取文件
- 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;
- };
- // 顯示網站首頁
- app.get("/", function (req, res) {
- // 生成唯一的ID
- let uid = UUID.create();
- console.log("uid: '" + uid + "' generated.");
- // 替換網頁模板內的UID關鍵字
- generateHTML(uid, req, res, path.join(__dirname, "/views/main.html"));
- });
- // 生成二維碼圖片并顯示
- app.get("/qrcode", function (req, res, next) {
- let uid = url.parse(req.url, true).query.uid;
- try {
- if (typeof uid !== "undefined") {
- // 寫入二維碼內的網址,微信掃描后自動跳轉。下面的網址是我的網址,https://www.maomin.club/qrcodelogin ,你可以換成自己的線上網址或者本地服務器。加上后面的"/scanned?uid="
- let jumpURL = "https://www.maomin.club/qrcodelogin/scanned?uid=" + uid;
- // 生成二維碼(size:圖片大小, margin: 邊框留白)
- 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>");
- }
- });
- // 顯示手機掃描后的確認界面
- app.get("/scanned", function (req, res) {
- let uid = url.parse(req.url, true).query.uid;
- if (typeof uid !== "undefined") {
- generateHTML(uid, req, res, path.join(__dirname, "/views/confirm.html"));
- console.log("uid: '" + uid + "' scanned.");
- // 獲取JSON文件內對應uid的數(shù)據(jù),更改其數(shù)據(jù)狀態(tài)
- 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";
- }
- // 寫入JSON文件
- 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>");
- }
- });
- // 在確認界面操作的響應
- 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 (typeof uid !== "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("<h1 style='textAlign:center;'>登錄成功!</h1>");
- } else {
- res.writeHead(200, { "Content-Type": "text/html" });
- res.end("<h1 style='textAlign:center;'>Canceled!</h1>");
- }
- } else {
- res.writeHead(414, { "Content-Type": "text/html" });
- res.end("<h1 style='textAlign:center;'>414 Request-URI Too Large</h1>");
- }
- });
- // 響應主頁不斷的AJAX請求
- app.get("/verified", function (req, res) {
- let uid = url.parse(req.url, true).query.uid;
- // normal - 沒有任何觸發(fā)
- // scanned - 已掃描
- // canceled - 已取消
- // verified - 已驗證
- let dataStatus = {
- cmd: "normal",
- user: "",
- };
- console.log("uid: '" + uid + "' query ...");
- if (typeof uid !== "undefined") {
- let userData = getJSONValue(path.join(__dirname, "/bin/data.json"), uid);
- // 返回JSON數(shù)據(jù)用于首頁AJAX操作
- 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
- );
看到這里,你是不是覺得代碼不夠全,咋就給了一個主要邏輯代碼,別著急,代碼滿漢全席馬上奉上,代碼解釋可以看注釋哦!以下是github網址,如果覺得對自己有用,歡迎star~
- https://github.com/maomincoding/qrcodelogin.git
結語
看到這里了,你可能直接拉取代碼,發(fā)現(xiàn)項目咋運行不了呢?效果也不跟線上網址那樣。是這樣的,如果你有線上服務器,可以把它部署到云端。如果沒有線上服務器,你可以自己搭建一個本地局域網服務器。一定要保證手機跟電腦網頁在一個IP網段上。
效果圖如下:
登錄網頁

登錄授權頁
