Developers

Verifying signatures

Check that a webhook really came from PetraPay.

Every webhook carries a PetraPay-Signature header so you can check it came from PetraPay and wasn't changed in transit.

PetraPay-Signature: t=1791190800,v1=5f2b9c…
  1. Split the header

    t is a Unix timestamp; v1 is the signature.

  2. Compute the expected signature

    HMAC-SHA256 of `${t}.${rawBody}`, keyed with your endpoint's signing secret, as hex. Use the raw request body, before any JSON parsing.

  3. Compare and check the time

    Compare in constant time, and reject timestamps more than five minutes old.

import crypto from "node:crypto";
import express from "express";

function verifyPetraPay(rawBody, header, secret) {
  const parts = Object.fromEntries(header.split(",").map((p) => p.split("=")));
  const expected = crypto.createHmac("sha256", secret).update(`${parts.t}.${rawBody}`).digest("hex");
  const a = Buffer.from(expected);
  const b = Buffer.from(parts.v1 ?? "");
  const fresh = Math.abs(Date.now() / 1000 - Number(parts.t)) < 300;
  return fresh && a.length === b.length && crypto.timingSafeEqual(a, b);
}

app.post("/webhooks/petrapay", express.raw({ type: "application/json" }), (req, res) => {
  if (!verifyPetraPay(req.body.toString(), req.get("PetraPay-Signature"), process.env.PETRAPAY_WEBHOOK_SECRET)) {
    return res.status(400).end();
  }
  const event = JSON.parse(req.body);
  if (event.type === "checkout.paid") fulfil(event.data.object.reference);
  res.sendStatus(200);
});
If you rotate the signing secret in the dashboard, update your server right away: the old secret stops working immediately.