token

微信 token 验证源码, 基于 express web框架实现

Examples

app.js

//导入 express 模块
var express = require('express');
//获取 post 参数
var bodyParser = require('body-parser');
//实例化
var app = express();
//处理 post 请求
app.use(bodyparser.urlencoded({
	extended: true
}));
//封装 请求参数
app.use(function(req, res, next){
	req.getdata = function(){
		var data = url.parse(req.url,true).query,
			body = req.body || {},
			params = req.params || {};
		for(var key in body){
			data[key] = body[key];
		}
		for(var key in params){
			data[key] = params[key];
		}
		return data;
	};
	next();
});

//加载 token 模块
require("./token")(app);


var server = require('http').Server(app);
server.listen(9088, "0.0.0.0", function () {
	var _host  = server.address().address;
  	var _port  = server.address().port;
  	console.log('Example app listening at http://%s:%s', _host, _port);
});

token.js

//字符串加密处理
var crypto = require("crypto");
//个心信息配置
var config = require("./config.js")();

//字符串加密
function sha1(str){
  var md5sum = crypto.createHash("sha1");
  md5sum.update(str);
  str = md5sum.digest("hex");
  return str;
}

function main(app) {
	app.use('/wechat/svonme', function(req, res, next){
		// url 
	   	var query = req.getdata();
		var signature = query.signature;
		var echostr = query.echostr;
		var timestamp = query['timestamp'];
		var nonce = query.nonce;
		var oriArray = new Array();
		oriArray[0] = nonce;
		oriArray[1] = timestamp;
		//这里是你在微信开发者中心页面里填的token
		oriArray[2] = config.token;
		oriArray.sort(); // ASCII 排序
		var original = oriArray.join('');
		console.log("Original str : " + original);
		console.log("Signature : " + signature );

		var scyptoString = sha1(original);

		if(signature == scyptoString){
			res.send(echostr);
			console.log("Confirm and send echo back");
		}else {
			res.send(false);
			console.log("Failed!");
		}
	});
}
module.exports = main;

config.js

/**
 * 微信认证后的 app 信息
 * 如果有需要可以将这些信息放到数据库中读取方便以更增加
 * 注:测试时请替换您真实的数据
 */
module.exports = function(){
	return {
		//AppID(应用ID)
		appid: '',
		//AppSecret(应用密钥)
		appsecret: '',
		//Token(令牌)
		token: ''
	};
};