let cryptoJs = require("crypto-js");
let jsonObj = JSON.parse(pm.request.body.raw); //Convert the submitted body string into an object
let jsonStr = JSON.stringify(jsonObj)//Turn the object back into a string to compress, avoiding line breaks in the body that affect signature compression.
let appID = jsonObj.app_id;
let mchID = jsonObj.mch_id;
// Generate the current timestamp
let timestamp = Math.round(new Date() / 1000).toString()
//Define random string
var nonceStr = randomString(); // Random string
function randomString(e) {
e = e || 32;
var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
a = t.length,
n = "";
for (i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
return n
}
//Get the full path
var reqURL = "/" + pm.request.url.path.join("/");
//Splice signature plaintext
message = reqURL + "\n" + timestamp + "\n" + nonceStr + "\n" + jsonStr
let key = CryptoJS.enc.Utf8.parse("********************************") // AppSecret
//AES encryption
let ciphertext = cryptoJs.AES.encrypt(message, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
}).toString();
//Splice on the authorization of Header, TTPAY-{EncryMode)},currently supports only AES-256-ECB
let authorization = 'TTPAY-AES-256-ECB app_id=' + appID + ',mch_id=' + mchID + ',nonce_str=' + nonceStr + ',timestamp=' + timestamp + ',signature=' + ciphertext
pm.request.headers.upsert({ key: "authorization", value: authorization })