apifox 生成签名-编写签名脚本

时间:2024-06-09 08:24:44

签名说明

  • appId=1xxxxxxxxxxxxx4。常量
  • appSecret=Exxxxxxxxxxxxxxxxxm。常量
  • date=当前日期,日期格式为yyyy-MM-dd。例: 2024-04-21
  • bizId=业务单据ID。例:1xxxxxxxxxxxxxxx3
  • signStr = appId+bizId+date+secretKey
  • sign=MD5(signStr)
  • 将签名(sigh)通过form data传递,参数名sign

mysql实现示例:

select md5(concat('1xxxxxxxxxxxxx4','1xxxxxxxxxxxxxxx3','2024-04-21','Exxxxxxxxxxxxxxxxxm')); 

捋清思路

  1. 获取签名所需的参数
  2. 生成签名
  3. 将签名放到合适的位置

编码

获取签名所需的参数

/* 获取签名所需参数 */
let appId = ""; /*从环境变量中获取*/
let appSecret = ""; /*从环境变量中获取*/
let date = moment().format("YYYY-MM-DD");/*当前日期,自动生成*/
let bizId = "" /*从header中获取*/

/* 部分签名所需参数在环境变量中,从环境变量中获取 */
appId = pm.environment.get('appId');
appSecret = pm.environment.get('appSecret');

/* 部分签名所需参数在header中,从header中获取 */
var headers = pm.request.headers;
if (headers) {
  bizId = headers.get("bizId");
}

生成签名

/* 打印签名所需参数 */
console.log("打印签名所需参数:");
console.log("appId is : " + appId);
console.log("bizId is : " + bizId);
console.log("date is : " + date);
console.log("appSecret is : " + appSecret);

console.log("开始签名:");
let signParam = []
signParam.push(appId)
signParam.push(bizId)
signParam.push(date)
signParam.push(appSecret)

let signStr = signParam.join('')
console.log("signStr is : " + signStr);

let sign = CryptoJS.MD5(signStr).toString().toUpperCase()
console.log("sign is : " + sign);

将签名放到合适的位置

将签名添加到formdata中:

let formData = pm.request.body.formdata;
let newForData = [];
formData.each((item) => {
  newForData.push({
    key: item.key,
    value: item.value
  });
});
newForData.push({
    key: 'sign',
    value: sign
  });
pm.request.body.update({
    mode: 'formdata',
    formdata: newForData
});

完整代码

/*导入JS 类库*/
var moment = require('moment');

/* 获取签名所需参数 */
let appId = ""; /*从环境变量中获取*/
let appSecret = ""; /*从环境变量中获取*/
let date = moment().format("YYYY-MM-DD");/*当前日期,自动生成*/
let bizId = "" /*从header中获取*/

/* 部分签名所需参数在环境变量中,从环境变量中获取 */
appId = pm.environment.get('appId');
appSecret = pm.environment.get('appSecret');

/* 部分签名所需参数在header中,从header中获取 */
var headers = pm.request.headers;
if (headers) {
  bizId = headers.get("bizId");
}

/* 打印签名所需参数 */
console.log("打印签名所需参数:");
console.log("appId is : " + appId);
console.log("bizId is : " + bizId);
console.log("date is : " + date);
console.log("appSecret is : " + appSecret);

console.log("开始签名:");
let signParam = []
signParam.push(appId)
signParam.push(bizId)
signParam.push(date)
signParam.push(appSecret)

let signStr = signParam.join('')
console.log("signStr is : " + signStr);

let sign = CryptoJS.MD5(signStr).toString().toUpperCase()
console.log("sign is : " + sign);

/* 将签名添加到formData */
let formData = pm.request.body.formdata;
let newForData = [];
formData.each((item) => {
  newForData.push({
    key: item.key,
    value: item.value
  });
});
newForData.push({
    key: 'sign',
    value: sign
  });
pm.request.body.update({
    mode: 'formdata',
    formdata: newForData
});