WeChat applet implements user login module server construction

WeChat applet implements user login module server construction

I chose node.js to build the server. Friends who have not installed it can refer to my other node.js blogs.

Server installation and configuration

Initialize the project and the package.json configuration file will be automatically created.

npm init -y

Install the Express framework and the request module.

npm install express –save
npm install request --save

Install nodemon to monitor file modifications (skip this step if it is already installed).

npm install nodemon -g

Coding

After executing the above command, create the app.js file in the project directory and write the following code:

Introduce the Express framework and request module, and configure appid and secret.

const express = require('express')
const bodyParser = require('body-parser')
const request = require('request')
const app = express()
app.use(bodyParser.json())
const wx = {
  appid: '', // Need to fill in the developer's AppID
  secret: '' // Need to fill in the developer's AppSecret
}

Simulate the database. (In this case, we use an array. The database setup is rather complicated and is not shown here. You can refer to other node.js+mysql projects in my blog.)

var db = { // simulated database session: {}, // save session information of openid and session_key user: {} // save user records, such as user name, points, etc.}

Request the login interface and verify the WeChat interface URL address of the login credentials.
(The URL below is the test credential interface provided by Tencent, no need to modify)

app.post('/login', (req, res) => {
  var url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' +
  wx.appid + '&secret=' + wx.secret + '&js_code=' + req.body.code +
   '&grant_type=authorization_code'  
  request(url, (err, response, body) => {
     if(){ // The code here determines whether session.openid exists}
     }
     res.json({token: token})
  })
})

Determine the openid statement code in the session.

if (session.openid) {
      var session = JSON.parse(body)
      // Used to generate token
      var token = 'token_' + new Date().getTime()
      db.session[token] = session 
}

Set access interface 3000

app.listen(3000, () => {
  console.log('server running at http://127.0.0.1:3000')
})

I sorted it out for you

Because the appid and session_key here need to be decrypted, the WXBizDataCrypt function of WeChat is used
WXBizDataCrypt.js

var crypto = require('crypto')

function WXBizDataCrypt(appId, sessionKey) {
  this.appId = appId
  this.sessionKey = sessionKey
}

WXBizDataCrypt.prototype.decryptData = function (encryptedData, iv) {
  // base64 decode
  var sessionKey = new Buffer(this.sessionKey, 'base64')
  encryptedData = new Buffer(encryptedData, 'base64')
  iv = new Buffer(iv, 'base64')

  try {
     // Decryption var decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv)
    // Set automatic padding to true and delete the padding decipher.setAutoPadding(true)
    var decoded = decipher.update(encryptedData, 'binary', 'utf8')
    decoded += decipher.final('utf8')
    
    decoded = JSON.parse(decoded)

  } catch (err) {
    throw new Error('Illegal Buffer')
  }

  if (decoded.watermark.appid !== this.appId) {
    throw new Error('Illegal Buffer')
  }

  return decoded
}

module.exports = WXBizDataCrypt

The entire code of app.js is as follows

// Encryption and decryption const crypto = require('crypto');
const WXBizDataCrypt = require('./WXBizDataCrypt')

const express = require('express')
const bodyParser = require('body-parser')
const request = require('request')
const app = express()
app.use(bodyParser.json())

const wx = {
    appid: '',
    secret: ''
}

var db = {
    session: {},
    user: {}
}

app.post('/login', (req, res) => {
    // Note: The appid on the mini program side must use a real account. If a test account is used, a login code error will occur console.log('login code: ' + req.body.code)
    var url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + wx.appid + '&secret=' + wx.secret + '&js_code=' + req.body.code + '&grant_type=authorization_code'
    request(url, (err, response, body) => {
        console.log('session: ' + body)
        var session = JSON.parse(body)
        if(session.openid) {
            var token = 'token_' + new Date().getTime()
            db.session[token] = session
            if(!db.user[session.openid]) {
                db.user[session.openid] = {
                    credit: 100
                }
            }
        }
        res.json({
            token: token
        })
    })
})

app.get('/checklogin', (req, res) => {
    var session = db.session[req.query.token]
    console.log('checklogin: ', session)
    // Return the Boolean value of whether the user is logged in to the client res.json({
        is_login:session !== undefined
    })
})

app.get('/credit', (req, res) => {
    var session = db.session[req.query.token]
    if(session && db.user[session.openid]) {
        res.json({
            credit: db.user[session.openid].credit
        })
    } else {
        res.json({
            err: 'The user does not exist or is not logged in. '
        })
    }
})

app.post('/userinfo', (req, res) => {
    // Get the session value var session = db.session[req.query.token]
    console.log('session:' + session)
    if(session) {
        // Decrypt encryptedData using appid and session_key
        var pc = new WXBizDataCrypt(wx.appid, session.session_key)
        var data = pc.decryptData(req.body.encryptedData, req.body.iv)
        console.log('After decryption:', data)
        // Check if rawData is correct var sha1 = crypto.createHash('sha1')
        sha1.update(req.body.rawData + session.session_key)
        var signature2 = sha1.digest('hex')
        console.log(signature2)
        console.log(req.body.signature)
        res.json({
            pass: signature2 === req.body.signature
        })
    } else {
        res.json({
            err: 'The user does not exist or is not logged in. '
        })
    }
})

app.listen(3000, () => {
    console.log('server running at http://127.0.0.1:3000')
})

Start the server

Save the above code, open the console or Powershell or Linux terminal, and run the following statement to open the server's 3000 for server access.

nodemon app.js

This is the end of this article about how to build a server for the user login module of WeChat Mini Program. For more information about building a server for the login module of WeChat Mini Program, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • WeChat applet construction and solution to login failure problem
  • WeChat applet builds its own Https server
  • How to build a WeChat applet server locally
  • Tutorial on how to build a WeChat applet to access the node.js interface server

<<:  Docker learning: the specific use of Container containers

>>:  Detailed explanation of 30 SQL query optimization techniques for MySQL tens of millions of large data

Recommend

Summarize the commonly used nth-child selectors

Preface In front-end programming, we often use th...

What to do if you forget your mysql password

Forgot your MySQL password twice? At first I did ...

WeChat applet implements fixed header and list table components

Table of contents need: Function Points Rendering...

How to bypass unknown field names in MySQL

Preface This article introduces the fifth questio...

Basic security settings steps for centos7 server

Turn off ping scanning, although it doesn't h...

MySQL database operations (create, select, delete)

MySQL Create Database After logging into the MySQ...

How to use Greek letters in HTML pages

Greek letters are a very commonly used series of ...

HTML optimization speeds up web pages

Obvious HTML, hidden "public script" Th...

B2C website user experience detail design reference

Recently, when using Apple.com/Ebay.com/Amazon.co...

How to use CSS attribute selectors to splice HTML DNA

CSS attribute selectors are amazing. They can hel...