跳至內容
StagePayDocs v2

請求簽章(選用)

為防止 REST API 請求本文遭竄改與重放攻擊而提供的選用 X-StagePay-Signature 請求簽章規格,以及 Node.js・PHP・Python 範例。

除了 API 金鑰驗證外,還可以在每個請求附上 HMAC 簽章,以防止本文遭竄改與重放(replay)。簽章規格與回呼簽章相同,都是 HMAC-SHA256 方式,只是方向相反(商戶 → StagePay)。

選用功能

請求簽章為選用項目。未傳送簽章標頭的請求,也會僅以 API 金鑰處理。對於傳送價格覆寫(price)等敏感欄位的請求,建議使用。是否要將簽章設為必要,請在金鑰設定中與營運團隊協調。

規格

signed_payload = X-StagePay-Timestamp + "." + rawBody
X-StagePay-Signature = "v1=" + hex( HMAC-SHA256( key = API 金鑰的 secret, message = signed_payload ) )
項目值
金鑰API 金鑰的密鑰(secret)(Bearer 權杖中 : 之後的部分),UTF-8
rawBody實際傳送的本文位元組。像 GET 這類沒有本文的請求則為空字串
X-StagePay-TimestampUnix 秒數。必須與伺服器時間相差在 300 秒以內
結果64 個小寫十六進位字元,前綴 v1=

必須傳送與簽章字串完全相同的位元組。為避免 HTTP 用戶端在簽章後重新序列化 JSON,請以字串形式傳送。

範例

import crypto from 'node:crypto';

const keyId = process.env.STAGEPAY_KEY_ID;
const secret = process.env.STAGEPAY_KEY_SECRET;

export async function stagepayPost(path, payload) {
  const body = JSON.stringify(payload);
  const ts = Math.floor(Date.now() / 1000).toString();
  const sig = 'v1=' + crypto.createHmac('sha256', secret).update(`${ts}.${body}`).digest('hex');
  const res = await fetch(`https://api.stagepay.io${path}`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${keyId}:${secret}`,
      'Content-Type': 'application/json',
      'X-StagePay-Timestamp': ts,
      'X-StagePay-Signature': sig,
    },
    body, // 原樣傳送已簽章的字串
  });
  if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);
  return res.json();
}

錯誤

HTTP原因
401簽章不符、缺少時間戳記・格式錯誤、超出容許範圍(300 秒)

若伺服器時間偏移,所有簽章請求都會被拒絕。請以 NTP 同步時間。

本頁目錄