Postman - 使用pre-request-script動態計算簽名

OpenApi一般都有簽名,在對接的時候,不管文檔寫得多麼完善,總是會有人不明白,所以可以提供一個Postman的Collection,裏面包含了簽名邏輯

整體思路

  • 每個對接方分配一對appKey和appSecret,其中appSecret不能泄露
  • 每個請求需要appKey, timestamp以及signature
  • 根據請求信息(method, url, body) + appSecret生成signature

請求樣例

  • 請求URL如下
https://www.tenmao.com/hello/world?app_key={{appKey}}&signtime={{timestamp}}&signature={{signature}}

ps: 因爲歷史原因,這裏的簽名信息放在URL裏面,其實最好還是放在header

簽名Pre-request-Script

let timestamp = new Date().getTime().toString();

//從環境變量讀取appKey和appSecret
const appKey = pm.environment.get("appKey")
const appSecret = pm.environment.get("appSecret")
console.log(`基本信息: appKey=${appKey}, appSecret=${appSecret}, timestamp=${timestamp}`)
if (!appKey || !appSecret) {
    //如果不存在就直接拋出異常,這樣就會彈出錯誤信息,同時不會再執行請求
    throw new Error("請先在環境變量中配置appKey和appSecret")
}

//計算簽名 - 獲取計算簽名的數據
var method = request.method;

var canonicalUrl = pm.request.url.getPath();
var data = pm.request.body.raw;
if (!data) {
    data = "";
}

var message = method.toLowerCase() + "\n"
+ encodeURIComponent(canonicalUrl) + "\n"
+ data;

//計算簽名 - 第一次摘要(針對時間戳)
var signKey = CryptoJS.HmacSHA1(timestamp, appSecret).toString(CryptoJS.enc.Hex);

console.log("timestamp:" + timestamp + ", appSecret:" + appSecret + ",signKey:" + signKey)

//計算簽名 - 第二次摘要(計算最終簽名)
var signature = CryptoJS.HmacSHA1(message, signKey).toString(CryptoJS.enc.Hex);
console.log(`簽名信息: \nmessage=${message}\nsignKey=${signKey}\nsignature=${signature}`)

//簽名信息設置到環境變量
pm.environment.set("timestamp", timestamp)
pm.environment.set("signature", signature)

script中關鍵點

  • 環境變量: pm.environment.get("appKey"), pm.environment.set("timestamp", timestamp)
  • ES6引入的字符串格式化語法: appKey=${appKey}, appSecret=${appSecret}, timestamp=${timestamp}
  • 異常提醒: throw new Error("請先在環境變量中配置appKey和appSecret")
  • 簽名計算: CryptoJS.HmacSHA1(timestamp, appSecret).toString(CryptoJS.enc.Hex)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章