postman中设置全局动态sign签名脚本

时间:2024-02-16 07:12:51

进入某个collection的全局edit设置:

 

在"Pre-request Scripts"选项卡设置全局脚本:

全局脚本贴上代码:

 

function getCurrentDate() {
    var myDate=new Date();                               // 获取当前时间戳
    var year = myDate.getFullYear();                         // 获取年份
    var month = myDate.getMonth() + 1;                       // 获取月份
    month = month < 10 ? "0" + month : month;
    var days = myDate.getDate();                             // 获取日期
    days = days < 10 ? "0" + days : days;
    var hours = myDate.getHours() + 1;                       // 获取时并+1
    var min = myDate.getMinutes();                           // 获取分
    var seconds = myDate.getSeconds();                       // 获取秒 
    hours = hours < 10 ? "0" + hours : hours;
    min = min < 10 ? "0" + min : min;
    seconds = seconds < 10 ? "0" + seconds : seconds;
 
    // 定义时间格式并设置为环境变量
    return year + "-" + month + "-" + days + " " + hours +":"+ min +":"+ seconds;
}

// appkey & secret code
var secretCode = \'ctw7i3cV6eu4pNCH3n4BMzkannNJX4jQ\';
var timestamp = getCurrentDate();

// 设置全局请求域名地址,和项目上下文路径
pm.environment.set("URL", "http://127.0.0.1:8080/ecoupon-redemption-system");
pm.environment.set("timestamp", timestamp);

// console.log("全部请求参数:" + request.data);
request.data["timestamp"] = timestamp;
var keys = Object.keys(request.data).sort() //请求参数名按照ASCII码升序排序

//拼接待签名字符串
var str = []
for (var p = 0; p < keys.length; p++) { 
    if(keys[p] == "sign" || keys[p] == "signmethod" || request.data[keys[p]] === ""){ // "==" ==宽松相等,隐性类型转换,值相等,返回true; "===" 严格相等,值和类型都相等,返回true
        continue;
    }
    str.push(keys[p] + "=" + request.data[keys[p]]);
}
var signStr = str.join("&") + secretCode;
console.log("待加密字符串 signStr == " + signStr);


//MD5加密签名规格,并赋值给环境变量`sign`
pm.environment.unset("sign");
var sign = CryptoJS.MD5(signStr).toString().toUpperCase();
console.log("计算出的签名 sign == " + sign);
pm.environment.set("sign", sign);

 

在这里计算好的sign变量,在request里动态获取值: {{sign}}

 

如果在script脚本中有使用console.log打印日志的情况,可以打开console控制台查看打印出来的日志: 

macbook苹果笔记本电脑,点击View -> Show Postman Console:

 

显示console视图:

 

end.