background

Using NodeJS for wechat public account development, first need to respond to the Token verification sent by wechat, official documents

Filling in the Server Configuration

Log in to wechat public platform and open this page in basic configuration under development.

Fill in the URL of the interface, customize the Token, click Random Generation to generate EncodingAESKey, set the message encryption mode to plaintext mode, and click submit to verify the Token of the server.

Token verification sent in response to wechat

The project was developed using Express, and the middleware wechatAuth is as follows:

var app = express();



const crypto = require('crypto');

const url = require('url');



// Perform sha1 encryption

function sha1(str) {

let shasum = crypto.createHash("sha1");

return shasum.update(str,'utf-8').digest("hex");

}



function wechatAuth(req, res) {

let signature = req.query.signature;

let echostr = req.query.echostr;

let timestamp = req.query.timestamp;

let nonce = req.query.nonce;



let reqArray = [nonce, timestamp, process.env.WX_TOKEN]; // process.env.WX_TOKEN Corresponds to the Token specified in the server configuration



reqArray.sort(); // Sort the array lexicographically

let sortStr = reqArray.join(''); // Join the array

let sha1Str = sha1(sortStr.toString().replace(/,/g,""));

if (signature === sha1Str) {

res.end(echostr);

} else {

res.end("false");

Console. log(" Authorization failed!" );

}

}



app.use('/wx/token',wechatAuth); // Enter the URL in the server configuration

Copy the code

After the server is online, click Basic Configuration to open the submit page