项目中需要使用postman模拟业务请求, 每次请求需要
- header中生成6位随机字符串nonce
- header中生成时间戳timestamp
- header中生成签名x-xlx-timestamp = sha1({body}:{timestamp}:{secret}:{nonce})
- body
{ "op": "create", "data": { "data_id": dataId, // dataId = md5({timestamp}+{nonce}+{payload}) "sys_time": sysTime // 20210906 11:29:30 } }
可以使用Postman提供的Pre-request Script,通过编写js脚本,实现在请求发出前对请求数据进行处理
let nonce = CryptoJS.lib.WordArray.random(3).toString();
let timestamp = new Date().getTime();
// 13位timestimp改为10位
timestamp = Math.floor(timestamp/1000)
// 生成系统时间
let nowTime = new Date();
sysTime = nowTime.getFullYear().toString()+(nowTime.getMonth()+1).toString().padStart(2, '0')+nowTime.getDate().toString().padStart(2, '0') + ' ' + nowTime.getHours().toString().padStart(2, '0') + ':' + nowTime.getMinutes().toString().padStart(2, '0') + ':' + nowTime.getSeconds().toString().padStart(2, '0');
let payload = JSON.stringify({
sys_time: sysTime
})
let dataIdContent = timestamp + nonce + payload;
// 生成主键
let dataId = CryptoJS.MD5(dataIdContent).toString();
let body = JSON.stringify({
op: 'create',
data: {
data_id: dataId,
sys_time: sysTime
}
})
let secret = 'xxxxxxx';
let signatureContent = body + ':' + timestamp + ':' + secret + ':' + nonce;
// 生成签名
let signature = CryptoJS.SHA1(signatureContent).toString();
// 设置为全局变量
postman.setGlobalVariable("timestamp", timestamp);
postman.setGlobalVariable("nonce", nonce);
postman.setGlobalVariable("signature", signature);
postman.setGlobalVariable("body", body);
注:
- js中getMonth()获取到的月份比实际月份小1,这是因为月份从0开始计数(真奇葩),所以要获得正确的月份需要手动+1
参考:
https://stackoverflow.com/a/18624336/7151777 - js中getDate()和getDay()非常容易用乱,前者获取的是几日,而后者获取的是星期几
参考:
https://stackoverflow.com/a/13359330/7151777 - 获取的月、时、分、秒需要使用.toString().padStart(2, ‘0’)手动补前缀0
参考:
https://stackoverflow.com/a/30272803/7151777