How to Verify a Webhook Signature (HMAC-SHA256), With Code

Verify a webhook signature in Node, Python or PHP: hash the raw body, compare in constant time, and fix the six mistakes that make a valid signature fail.

A webhook request with a signature header passing through a padlock check before it reaches a server

Guide · By PostBoost team · · Markdown

To verify a webhook signature, compute an HMAC of the raw request body with your webhook secret and compare it with the signature header in constant time, before you parse anything. If the two match, the request came from someone who knows the secret and the body was not changed on the way. If they don't, return an error and ignore the payload.

That is four lines of code in any language. When verification fails anyway, the cause is almost always that you hashed a slightly different string than the sender did. This guide gives working code for Node, Python and PHP, then walks through the six mistakes behind most "signature mismatch" errors, using a real PostBoost delivery as the example.

What a webhook signature proves

A webhook is a POST request that a service sends to your URL when something happens, for example "this post was published". Anyone who knows the URL can send a request to it, so the sender adds a signature: an HMAC (a keyed hash) of the request body, computed with a secret that only the sender and you know.

A valid signature tells you two things:

  • Who sent it. Without the secret, nobody can produce a matching HMAC.
  • Nothing changed. Change one byte of the body and the HMAC changes completely.

It does not tell you that the request is new. Someone who captured a signed delivery can send the same bytes again, and the signature still matches. More on that in the section on replays and retries below.

The four steps

  1. Read the raw body as bytes, exactly as they arrived, before any JSON parser touches it.
  2. Compute the HMAC of those bytes with your secret and the sender's algorithm (SHA-256 for PostBoost, GitHub, Shopify and Stripe).
  3. Encode and compare it with the header value: same encoding (hex or base64), any prefix removed, and a constant-time comparison.
  4. Only then parse the JSON and act on it.

The constant-time comparison matters. A normal == stops at the first different character, so response times leak how much of a guessed signature was right. GitHub's docs say it plainly: "Never use a plain == operator."

Code: Node, Python and PHP

The examples verify PostBoost's X-Signature header, which is a lowercase hex HMAC-SHA256 with no prefix. We ran the check in each one against the sample delivery further down: it accepts the raw body and rejects a parsed and re-encoded copy.

Node.js (Express)

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

const app = express();

// Raw body for this route only. Register it before app.use(express.json()).
app.post("/webhooks/postboost", express.raw({ type: "*/*" }), (req, res) => {
  const expected = crypto
    .createHmac("sha256", process.env.POSTBOOST_WEBHOOK_SECRET)
    .update(req.body) // a Buffer: the bytes PostBoost signed
    .digest("hex");
  const given = String(req.get("X-Signature") ?? "").trim().toLowerCase();

  const ok = /^[0-9a-f]{64}$/.test(given) &&
    crypto.timingSafeEqual(Buffer.from(given, "hex"), Buffer.from(expected, "hex"));
  if (!ok) return res.sendStatus(401);

  const delivery = JSON.parse(req.body.toString("utf8"));
  // de-duplicate on delivery.id, then queue the work
  res.status(200).json({ ok: true });
});

crypto.timingSafeEqual throws when the two buffers have different lengths, which is why the format check comes first. If express.json() runs before this route, the body is already parsed and req.body is an object, not the bytes that were signed. Stripe's troubleshooting guide gives the same advice about middleware order.

Python (Flask)

import hashlib
import hmac
import os

from flask import Flask, abort, request

app = Flask(__name__)
SECRET = os.environ["POSTBOOST_WEBHOOK_SECRET"].encode()

@app.post("/webhooks/postboost")
def postboost_webhook():
    raw = request.get_data()  # bytes, before any parsing
    expected = hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
    given = request.headers.get("X-Signature", "").strip().lower()
    if not hmac.compare_digest(expected.encode(), given.encode()):
        abort(401)

    delivery = request.get_json()
    # de-duplicate on delivery["id"], then queue the work
    return {"ok": True}, 200

Comparing bytes rather than strings keeps hmac.compare_digest from raising an error if someone sends a header with non-ASCII characters.

PHP (Laravel)

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::post('/webhooks/postboost', function (Request $request) {
    $raw = $request->getContent(); // the raw body string
    $expected = hash_hmac('sha256', $raw, config('services.postboost.webhook_secret'));
    $given = strtolower(trim((string) $request->header('X-Signature')));

    abort_unless(hash_equals($expected, $given), 401);

    $delivery = json_decode($raw, true);
    // de-duplicate on $delivery['id'], then dispatch a job
    return response()->json(['ok' => true]);
});

A route in routes/web.php checks a CSRF token on every POST, and a webhook sender has none. Put the route in routes/api.php, or exclude its path with $middleware->validateCsrfTokens(except: ['webhooks/*']) in bootstrap/app.php.

Why a valid signature fails: six mistakes

Here is a shortened PostBoost post.published delivery (sample IDs, fewer fields than a real one), encoded the way PostBoost encodes every delivery. It is 401 bytes:

{"event":"post.published","id":"3f2a1b4c-5d6e-4f70-8a9b-0c1d2e3f4a5b","occurred_at":"2026-10-12T10:00:03+00:00","workspace_uuid":"7d0c5b8e-2f4a-4c1e-9b3d-5a6f7e8d9c0b","data":{"uuid":"9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d","status":"published","account":{"id":12,"provider":"linkedin","name":"Acme Studio","external_url":"https:\/\/www.linkedin.com\/feed\/update\/urn:li:share:7000000000000000000\/"}}}

With the test secret whsec_test, its X-Signature is:

035b3c6d217015594d897b789e4ede4899c8f0ef4308e1216554a3b31259aeba

Each mistake below turns that valid delivery into a "mismatch". We ran every case through the free webhook signature verifier, which tries one fix at a time and names the one that works.

Mistake What happens The verifier's hint
Hashing a parsed, re-encoded copy Look at https:\/\/ in the URL. PostBoost encodes JSON the PHP way and escapes every /. JSON.stringify(JSON.parse(body)) in Node writes https:// instead, so the bytes change and the HMAC becomes eb6de52d…. Python's json.dumps adds spaces after : and , and fails too. "Valid for the same JSON re-encoded with escaped slashes and unicode (PHP json_encode): sign the raw request body, not a re-encoded copy."
A trailing newline Copying the body from a log or saving it in an editor often adds \n. One extra byte, a different HMAC. "Valid without the trailing newline: sign the raw bytes you received…"
A prefix left on the header GitHub's header starts with sha256=; PostBoost's has no prefix. Comparing sha256=035b… with 035b… always fails. "Valid once the "sha256=" prefix is stripped…"
Hex vs base64 The same 32 bytes are 64 hex characters or 44 base64 characters. PostBoost and GitHub send hex; Shopify sends base64. "Valid as base64: the signature is base64-encoded, not hex."
A space or newline around the secret Secrets pasted into .env files or secret managers often pick up whitespace. whsec_test with a trailing space gives a completely different HMAC. "Valid with the spaces or line breaks around the secret removed: check how your secret is loaded."
The wrong algorithm or secret SHA-1 or SHA-512 instead of SHA-256, or the secret of another webhook or environment. Names the algorithm that matches, or says no single usual mistake explains it.

The first row is the one that catches most people, because the parsed JSON looks identical. Escaping, key order and spacing are invisible after parsing, but they are part of the bytes that were signed.

How senders differ

The method is the same everywhere; the header, the encoding and what gets hashed are not.

Sender Header Algorithm and encoding What is signed
PostBoost X-Signature HMAC-SHA256, lowercase hex, no prefix The raw body
GitHub X-Hub-Signature-256 HMAC-SHA256, hex, prefixed sha256= The raw body
Shopify X-Shopify-Hmac-SHA256 HMAC-SHA256, base64 The raw body, keyed with the app's client secret
Stripe Stripe-Signature HMAC-SHA256, hex, in t=…,v1=… The timestamp, a ., then the raw body

Stripe is the odd one out: because the timestamp is part of what is signed, a plain body HMAC never matches. Stripe recommends its official libraries, which also reject deliveries older than a default tolerance of 5 minutes.

Replays, retries and what to return

PostBoost and GitHub sign only the body, so a signature alone cannot tell a fresh delivery from a captured one sent again. The fix is cheap: store each delivery's id and skip any you have already processed. Every PostBoost delivery has an id in the envelope, and it stays the same on automatic retries and on a manual Resend, so the same check also protects you from processing a retry twice.

The envelope's occurred_at is inside the signed body, so nobody can change it without breaking the signature. Don't reject deliveries for being old, though: a manual resend keeps the original occurred_at, possibly days later.

What PostBoost does with your response, from its webhooks docs:

  • Return 200, 201 or 202. Anything else, including 204, counts as a failed delivery.
  • A failed delivery is retried until the webhook's maximum number of attempts is reached. In the app you choose 1, 2 or 3 attempts, and webhooks created through the API use 3. The waits double each time: 2 minutes, then 4.
  • Answer fast and do the real work in a queue, so a slow handler doesn't turn into a failed delivery.

A wrong signature should get 401. PostBoost then records the delivery as failed, which is what you want: you will see it in the webhook's deliveries list and can fix your handler.

Set up a signed webhook in PostBoost

In the app. Open Webhooks in the sidebar (under Configuration, workspace admins only) and choose Create webhook. Enter your callback URL, pick the events, and fill in Secret: it is optional, and without one PostBoost sends no X-Signature header. Keep Method on POST and the content type on application/json. With GET, the payload travels in the query string and there is no body to hash. To check your handler, open the webhook's menu and choose Test webhook: PostBoost sends a signed test event to your URL.

With the API. n8n, Zapier, Make or your own code can subscribe with one call. The response contains a 40-character secret, shown only this once, so store it straight away:

curl -X POST "https://postboost.co/app/api/$WORKSPACE/webhooks/subscriptions" \
  -H "Authorization: Bearer $POSTBOOST_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"callback_url":"https://example.com/webhooks/postboost","events":["post.published","post.publishing_failed"]}'

Subscriptions always send JSON POST requests, retry up to 3 times, and accept only public https:// URLs. The automations page shows what teams build on these events, and reliability covers the account.disconnected and account.token_expiring events that warn you before posts start failing. If you are new to the API side, API vs MCP explains when code should drive a workflow and when an AI assistant should.

Debug a failing signature in a minute

When your handler rejects a delivery and you can't see why:

  1. Log the raw body (as bytes or base64, never pretty-printed) and the X-Signature header of one failed delivery. Don't copy the payload from the webhook's deliveries list in PostBoost for this: it is shown parsed and formatted for reading, so it is not the exact bytes that were signed.
  2. Open the webhook signature verifier, pick the PostBoost preset, and paste the body, the header and a test secret. The page computes the HMAC in your browser and sends nothing.
  3. Read the hint, fix that one thing in your handler, and check the next delivery.

The same check runs from code or from an AI agent: POST https://postboost.co/app/api/tools/webhook-signature-verifier, or the verify-webhook-signature tool on the free MCP server at https://postboost.co/mcp/tools. Both run on our server, so send only sample payloads and test secrets. Here is what it returns for a header that still has GitHub's prefix on it:

curl -X POST https://postboost.co/app/api/tools/webhook-signature-verifier \
  -H "Content-Type: application/json" \
  -d '{"body":"{\"event\":\"post.published\",\"id\":\"3f2a1b4c-5d6e-4f70-8a9b-0c1d2e3f4a5b\"}","secret":"whsec_test","signature":"sha256=3adad22d800f610f3b2b538129299b0f2b4cc4b73fb323e3699805e78c16d718"}'
{
  "valid": false,
  "expected": "3adad22d800f610f3b2b538129299b0f2b4cc4b73fb323e3699805e78c16d718",
  "hints": [
    "Valid once the \"sha256=\" prefix is stripped: set it in the prefix field, or remove it before comparing."
  ]
}

Building the API call that creates the post in the first place? The API request builder writes it for you in curl and other languages, and the webhooks docs list every event and payload field.

Do this in PostBoost

Free tools for this guide

FAQ

How do I verify a webhook signature?

Read the raw request body before any JSON parsing, compute an HMAC of it with your webhook secret and the sender's algorithm (usually SHA-256), encode it the way the sender does (hex or base64), and compare it with the signature header using a constant-time function. Reject the request when they differ.

Why does my webhook signature not match?

Usually because you hashed a different string than the sender did. A framework parsed the JSON and you re-encoded it, a newline was added, the header still has a prefix such as sha256=, the encoding is base64 not hex, or the secret has a space or line break around it. Paste the body, secret and header into a signature verifier to see which one it is.

Why compare signatures in constant time?

A normal string comparison stops at the first different character, so an attacker can learn a valid signature one character at a time by measuring response times. hash_equals in PHP, hmac.compare_digest in Python and crypto.timingSafeEqual in Node take the same time whatever the input.

Does a valid signature stop replay attacks?

Not by itself. A signature proves who sent the body and that it was not changed, but someone who captured a delivery can send it again. Stripe signs a timestamp with the body for that reason. For senders that sign only the body, such as PostBoost and GitHub, store each delivery id and ignore repeats.

How does PostBoost sign webhooks?

When the webhook has a secret, every delivery carries an X-Signature header: the HMAC-SHA256 of the raw JSON body, keyed with the secret, as lowercase hex with no prefix. Webhooks created through the API always get a secret, returned once in the response.

Where do I find the webhook secret in PostBoost?

You set it yourself when you create or edit a webhook under Webhooks in the app (workspace admins), and you can change it later with Change secret. For a webhook created with POST /{workspaceUuid}/webhooks/subscriptions, the secret is in the response and is shown only once.

Sources

Related guides

Try PostBoost free

API, webhooks and MCP on every plan, including Free. No credit card required.