验证路径token
最后更新于:2022-04-01 20:00:25
微信api地址
http://mp.weixin.qq.com/wiki/17/2d4265491f12608cd170a95559800f2d.html#.E7.AC.AC.E4.B8.80.E6.AD.A5.EF.BC.9A.E5.A1.AB.E5.86.99.E6.9C.8D.E5.8A.A1.E5.99.A8.E9.85.8D.E7.BD.AE
微信api说明
开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。
加密/校验流程如下:
1. 将token、timestamp、nonce三个参数进行字典序排序
2. 将三个参数字符串拼接成一个字符串进行sha1加密
3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
4.
代码:
~~~
/**
* Created by tangxuelong on 15-10-16.
* validateToken
* 此文件只用于TOKEN验证
*/
var http = require('http');//内置http modoule
var config = require('./http.config')//配置module
var api = require('wechat-api');//npm wx
var url = require("url");
var crypto = require("crypto");
//微信接口的哈希加密方法
function sha1(str) {
var md5sum = crypto.createHash("sha1");
md5sum.update(str);
str = md5sum.digest("hex");
return str;
}
//微信路径token验证
function validate_token(req,res){
//获取请求的qurey排序以后加密
var query = url.parse(req.url, true).query;
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;
oriArray[2] = "XXXXXX";
oriArray.sort();
var original = oriArray.join('');
var scyptoString = sha1(original);
if (signature == scyptoString) {
res.end(echostr);
console.log("Confirm and send echo back");
} else {
res.end("false");
console.log("Failed!");
}
}
//创建http服务器
http.createServer(function(req,res){
validate_token(req,res);
}).listen(config.port, config.http_ip);
console.log('http server is running');
~~~
';