---
title: "Verify Webhook Signatures"
description: "Verify SignatureAPI webhook signatures with the standard library in Node.js, Python, PHP, Ruby, Go, Java and C#: one tested function per language."
canonical: "https://signatureapi.com/docs/api/guides/how-to/verify-webhooks"
source: "https://signatureapi.com/docs/api/guides/how-to/verify-webhooks.md"
last_verified_api_version: "1.18.0"
last_modified: "2026-11-18T17:35:44Z"
---

# Verify Webhook Signatures

Verify SignatureAPI webhook signatures with the standard library in Node.js, Python, PHP, Ruby, Go, Java and C#: one tested function per language.

_Last verified against API version 1.18.0._

Anyone who knows your webhook URL can send a request to it. Check the signature of every delivery before you trust the event.

SignatureAPI signs each delivery following the [Standard Webhooks specification](https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md#verifying-webhook-authenticity). The functions on this page implement that check with each language's standard library, so there is nothing to install. Each one passes the same six-case test vector: a valid delivery, several signatures with one valid, a tampered body, a wrong secret, an old timestamp and missing headers.

> **Tip:** Prefer a library? The Standard Webhooks project publishes one for most languages, listed on [Webhooks](https://signatureapi.com/docs/api/webhooks#authentication).

## How Verification Works

1. Read the `webhook-id`, `webhook-timestamp` and `webhook-signature` headers. Reject the request if one is missing.
2. Reject the request if `webhook-timestamp` (Unix seconds) is more than 5 minutes away from your clock. This blocks replayed requests.
3. Take the endpoint's signing secret (`whsec_...`), drop the `whsec_` prefix and base64-decode the rest. That is the HMAC key.
4. Compute `HMAC-SHA256(key, "<webhook-id>.<webhook-timestamp>.<raw body>")`.
5. `webhook-signature` holds one or more space-separated `v1,<base64>` entries. Compare each with your result in constant time. One match means the delivery is authentic.

Find the signing secret on the endpoint's page in [Settings > Webhooks](https://dashboard.signatureapi.com/settings/webhooks). Test and live endpoints have different secrets.

## The Function

Copy the function for your language. It returns (or returns `true`) when the delivery is authentic and throws an error when it is not.

```javascript Node.js
import { createHmac, timingSafeEqual } from "node:crypto";

export class WebhookVerificationError extends Error {}

/**
 * Verify a Standard Webhooks signature.
 *
 * @param {string} secret   Signing secret, "whsec_<base64 key>".
 * @param {Record<string, string | undefined>} headers  Request headers. Names are matched case-insensitively.
 * @param {string | Buffer} rawBody  The exact bytes received. Never a re-serialized object.
 * @param {{ now?: number, toleranceSeconds?: number }} [options]  `now` is Unix seconds (defaults to the clock).
 * @returns {true} Throws WebhookVerificationError when the delivery is not authentic.
 */
export function verifyWebhook(secret, headers, rawBody, options = {}) {
  const { now = Math.floor(Date.now() / 1000), toleranceSeconds = 300 } = options;
  const lower = Object.fromEntries(
    Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value]),
  );
  const id = lower["webhook-id"];
  const timestamp = lower["webhook-timestamp"];
  const signatureHeader = lower["webhook-signature"];
  if (!id || !timestamp || !signatureHeader) {
    throw new WebhookVerificationError("Missing webhook-id, webhook-timestamp or webhook-signature header");
  }

  if (!/^\d+$/.test(timestamp)) {
    throw new WebhookVerificationError("Invalid webhook-timestamp");
  }
  if (Math.abs(now - Number(timestamp)) > toleranceSeconds) {
    throw new WebhookVerificationError("Timestamp outside the tolerance window");
  }

  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const body = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(rawBody, "utf8");
  const expected = createHmac("sha256", key)
    .update(Buffer.concat([Buffer.from(`${id}.${timestamp}.`, "utf8"), body]))
    .digest();

  // The header holds space-separated "v1,<base64>" entries. Any match is enough.
  for (const entry of signatureHeader.split(" ")) {
    const [version, signature] = entry.split(",", 2);
    if (version !== "v1" || !signature) continue;
    const candidate = Buffer.from(signature, "base64");
    if (candidate.length === expected.length && timingSafeEqual(candidate, expected)) {
      return true;
    }
  }
  throw new WebhookVerificationError("No matching signature");
}
```

```python Python
"""Verify Standard Webhooks signatures with the standard library only."""

import base64
import hashlib
import hmac
import time


class WebhookVerificationError(Exception):
    pass


def verify_webhook(secret, headers, raw_body, now=None, tolerance_seconds=300):
    """Return True when the delivery is authentic, otherwise raise WebhookVerificationError.

    secret: signing secret, "whsec_<base64 key>".
    headers: mapping of request headers (names matched case-insensitively).
    raw_body: the exact bytes (or str) received. Never a re-serialized object.
    now: Unix seconds, defaults to the clock.
    """
    if now is None:
        now = int(time.time())
    lower = {name.lower(): value for name, value in headers.items()}
    msg_id = lower.get("webhook-id")
    timestamp = lower.get("webhook-timestamp")
    signature_header = lower.get("webhook-signature")
    if not msg_id or not timestamp or not signature_header:
        raise WebhookVerificationError("Missing webhook-id, webhook-timestamp or webhook-signature header")

    if not timestamp.isdigit():
        raise WebhookVerificationError("Invalid webhook-timestamp")
    if abs(now - int(timestamp)) > tolerance_seconds:
        raise WebhookVerificationError("Timestamp outside the tolerance window")

    key = base64.b64decode(secret.removeprefix("whsec_"))
    body = raw_body.encode("utf-8") if isinstance(raw_body, str) else raw_body
    signed = f"{msg_id}.{timestamp}.".encode("utf-8") + body
    expected = hmac.new(key, signed, hashlib.sha256).digest()

    # The header holds space-separated "v1,<base64>" entries. Any match is enough.
    for entry in signature_header.split(" "):
        version, _, signature = entry.partition(",")
        if version != "v1" or not signature:
            continue
        try:
            candidate = base64.b64decode(signature, validate=True)
        except ValueError:
            continue
        if hmac.compare_digest(candidate, expected):
            return True
    raise WebhookVerificationError("No matching signature")
```

```php PHP
<?php

declare(strict_types=1);

final class WebhookVerificationError extends RuntimeException
{
}

/**
 * Verify a Standard Webhooks signature. Returns true or throws WebhookVerificationError.
 *
 * @param array<string, string> $headers Request headers (names matched case-insensitively).
 * @param string $rawBody The exact bytes received. Never a re-encoded JSON string.
 * @param int|null $now Unix seconds, defaults to the clock.
 */
function verifyWebhook(string $secret, array $headers, string $rawBody, ?int $now = null, int $toleranceSeconds = 300): bool
{
    $now ??= time();
    $lower = array_change_key_case($headers, CASE_LOWER);
    $id = $lower['webhook-id'] ?? '';
    $timestamp = $lower['webhook-timestamp'] ?? '';
    $signatureHeader = $lower['webhook-signature'] ?? '';
    if ($id === '' || $timestamp === '' || $signatureHeader === '') {
        throw new WebhookVerificationError('Missing webhook-id, webhook-timestamp or webhook-signature header');
    }
    if (!ctype_digit($timestamp)) {
        throw new WebhookVerificationError('Invalid webhook-timestamp');
    }
    if (abs($now - (int) $timestamp) > $toleranceSeconds) {
        throw new WebhookVerificationError('Timestamp outside the tolerance window');
    }

    $key = base64_decode(preg_replace('/^whsec_/', '', $secret), true);
    if ($key === false) {
        throw new WebhookVerificationError('Secret is not valid base64');
    }
    $expected = hash_hmac('sha256', "{$id}.{$timestamp}.{$rawBody}", $key, true);

    // The header holds space-separated "v1,<base64>" entries. Any match is enough.
    foreach (explode(' ', $signatureHeader) as $entry) {
        $parts = explode(',', $entry, 2);
        if (count($parts) !== 2 || $parts[0] !== 'v1') {
            continue;
        }
        $candidate = base64_decode($parts[1], true);
        if ($candidate !== false && hash_equals($expected, $candidate)) {
            return true;
        }
    }
    throw new WebhookVerificationError('No matching signature');
}
```

```ruby Ruby
# frozen_string_literal: true

require "base64"
require "openssl"

module SignatureApi
  class WebhookVerificationError < StandardError; end

  # Verify a Standard Webhooks signature. Returns true or raises WebhookVerificationError.
  #
  # headers:  Hash of request headers (names matched case-insensitively).
  # raw_body: the exact bytes received. Never a re-serialized object.
  # now:      Unix seconds, defaults to the clock.
  def self.verify_webhook(secret, headers, raw_body, now: Time.now.to_i, tolerance_seconds: 300)
    lower = headers.to_h { |name, value| [name.to_s.downcase, value] }
    id = lower["webhook-id"]
    timestamp = lower["webhook-timestamp"]
    signature_header = lower["webhook-signature"]
    if [id, timestamp, signature_header].any? { |v| v.nil? || v.empty? }
      raise WebhookVerificationError, "Missing webhook-id, webhook-timestamp or webhook-signature header"
    end
    raise WebhookVerificationError, "Invalid webhook-timestamp" unless timestamp.match?(/\A\d+\z/)
    if (now - timestamp.to_i).abs > tolerance_seconds
      raise WebhookVerificationError, "Timestamp outside the tolerance window"
    end

    key = Base64.strict_decode64(secret.delete_prefix("whsec_"))
    expected = OpenSSL::HMAC.digest("SHA256", key, "#{id}.#{timestamp}.#{raw_body}")

    # The header holds space-separated "v1,<base64>" entries. Any match is enough.
    signature_header.split(" ").each do |entry|
      version, signature = entry.split(",", 2)
      next unless version == "v1" && signature

      candidate = begin
        Base64.strict_decode64(signature)
      rescue ArgumentError
        next
      end
      if candidate.bytesize == expected.bytesize && OpenSSL.fixed_length_secure_compare(candidate, expected)
        return true
      end
    end
    raise WebhookVerificationError, "No matching signature"
  end
end
```

```go Go
// Package verifywebhooks verifies Standard Webhooks signatures with the standard library only.
package verifywebhooks

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"errors"
	"strconv"
	"strings"
	"time"
)

// ErrVerification is wrapped by every verification failure.
var ErrVerification = errors.New("webhook verification failed")

func fail(reason string) error { return errors.Join(ErrVerification, errors.New(reason)) }

// Verify checks the delivery. It returns nil when authentic.
//
// secret is "whsec_<base64 key>". headers is matched case-insensitively. rawBody must be the
// exact bytes received, never a re-serialized object. now is the reference time; use time.Now().
func Verify(secret string, headers map[string]string, rawBody []byte, now time.Time, tolerance time.Duration) error {
	lower := make(map[string]string, len(headers))
	for name, value := range headers {
		lower[strings.ToLower(name)] = value
	}
	id, timestamp, signatureHeader := lower["webhook-id"], lower["webhook-timestamp"], lower["webhook-signature"]
	if id == "" || timestamp == "" || signatureHeader == "" {
		return fail("missing webhook-id, webhook-timestamp or webhook-signature header")
	}
	seconds, err := strconv.ParseInt(timestamp, 10, 64)
	if err != nil || seconds < 0 {
		return fail("invalid webhook-timestamp")
	}
	diff := now.Sub(time.Unix(seconds, 0))
	if diff < 0 {
		diff = -diff
	}
	if diff > tolerance {
		return fail("timestamp outside the tolerance window")
	}

	key, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(secret, "whsec_"))
	if err != nil {
		return fail("secret is not valid base64")
	}
	mac := hmac.New(sha256.New, key)
	mac.Write([]byte(id + "." + timestamp + "."))
	mac.Write(rawBody)
	expected := mac.Sum(nil)

	// The header holds space-separated "v1,<base64>" entries. Any match is enough.
	for _, entry := range strings.Fields(signatureHeader) {
		version, signature, ok := strings.Cut(entry, ",")
		if !ok || version != "v1" {
			continue
		}
		candidate, err := base64.StdEncoding.DecodeString(signature)
		if err == nil && hmac.Equal(candidate, expected) {
			return nil
		}
	}
	return fail("no matching signature")
}
```

```java Java
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.Map;
import java.util.TreeMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/** Verifies Standard Webhooks signatures with the JDK only. */
public final class WebhookVerifier {
  public static final class VerificationException extends Exception {
    public VerificationException(String message) {
      super(message);
    }
  }

  private WebhookVerifier() {}

  /**
   * Returns normally when the delivery is authentic, otherwise throws VerificationException.
   *
   * @param secret signing secret, "whsec_&lt;base64 key&gt;"
   * @param headers request headers (names matched case-insensitively)
   * @param rawBody the exact bytes received, never a re-serialized object
   * @param nowSeconds reference time as Unix seconds (use System.currentTimeMillis() / 1000)
   */
  public static void verify(
      String secret,
      Map<String, String> headers,
      byte[] rawBody,
      long nowSeconds,
      long toleranceSeconds)
      throws VerificationException {
    Map<String, String> lower = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
    lower.putAll(headers);
    String id = lower.get("webhook-id");
    String timestamp = lower.get("webhook-timestamp");
    String signatureHeader = lower.get("webhook-signature");
    if (isEmpty(id) || isEmpty(timestamp) || isEmpty(signatureHeader)) {
      throw new VerificationException(
          "Missing webhook-id, webhook-timestamp or webhook-signature header");
    }
    if (!timestamp.matches("\\d{1,18}")) {
      throw new VerificationException("Invalid webhook-timestamp");
    }
    if (Math.abs(nowSeconds - Long.parseLong(timestamp)) > toleranceSeconds) {
      throw new VerificationException("Timestamp outside the tolerance window");
    }

    byte[] expected;
    try {
      byte[] key = Base64.getDecoder().decode(secret.replaceFirst("^whsec_", ""));
      Mac mac = Mac.getInstance("HmacSHA256");
      mac.init(new SecretKeySpec(key, "HmacSHA256"));
      mac.update((id + "." + timestamp + ".").getBytes(StandardCharsets.UTF_8));
      expected = mac.doFinal(rawBody);
    } catch (Exception e) {
      throw new VerificationException("Cannot compute signature: " + e.getMessage());
    }

    // The header holds space-separated "v1,<base64>" entries. Any match is enough.
    for (String entry : signatureHeader.split(" ")) {
      String[] parts = entry.split(",", 2);
      if (parts.length != 2 || !parts[0].equals("v1")) {
        continue;
      }
      try {
        byte[] candidate = Base64.getDecoder().decode(parts[1]);
        if (MessageDigest.isEqual(candidate, expected)) {
          return;
        }
      } catch (IllegalArgumentException ignored) {
        // Not base64: try the next entry.
      }
    }
    throw new VerificationException("No matching signature");
  }

  private static boolean isEmpty(String value) {
    return value == null || value.isEmpty();
  }
}
```

```csharp C#
using System.Security.Cryptography;
using System.Text;

/// <summary>Verifies Standard Webhooks signatures with the .NET base library only.</summary>
public static class WebhookVerifier
{
    public sealed class VerificationException(string message) : Exception(message);

    /// <summary>
    /// Returns normally when the delivery is authentic, otherwise throws VerificationException.
    /// rawBody must be the exact bytes received, never a re-serialized object.
    /// </summary>
    public static void Verify(
        string secret,
        IDictionary<string, string> headers,
        byte[] rawBody,
        long nowSeconds,
        long toleranceSeconds = 300)
    {
        var lower = new Dictionary<string, string>(headers, StringComparer.OrdinalIgnoreCase);
        lower.TryGetValue("webhook-id", out var id);
        lower.TryGetValue("webhook-timestamp", out var timestamp);
        lower.TryGetValue("webhook-signature", out var signatureHeader);
        if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(signatureHeader))
            throw new VerificationException("Missing webhook-id, webhook-timestamp or webhook-signature header");
        if (!long.TryParse(timestamp, out var seconds) || seconds < 0)
            throw new VerificationException("Invalid webhook-timestamp");
        if (Math.Abs(nowSeconds - seconds) > toleranceSeconds)
            throw new VerificationException("Timestamp outside the tolerance window");

        byte[] key;
        try
        {
            key = Convert.FromBase64String(secret.StartsWith("whsec_") ? secret["whsec_".Length..] : secret);
        }
        catch (FormatException)
        {
            throw new VerificationException("Secret is not valid base64");
        }
        using var hmac = new HMACSHA256(key);
        var prefix = Encoding.UTF8.GetBytes($"{id}.{timestamp}.");
        var expected = hmac.ComputeHash([.. prefix, .. rawBody]);

        // The header holds space-separated "v1,<base64>" entries. Any match is enough.
        foreach (var entry in signatureHeader.Split(' ', StringSplitOptions.RemoveEmptyEntries))
        {
            var parts = entry.Split(',', 2);
            if (parts.Length != 2 || parts[0] != "v1") continue;
            try
            {
                if (CryptographicOperations.FixedTimeEquals(Convert.FromBase64String(parts[1]), expected)) return;
            }
            catch (FormatException)
            {
                // Not base64: try the next entry.
            }
        }
        throw new VerificationException("No matching signature");
    }
}
```

## Call It With the Raw Body

The signature covers the exact bytes SignatureAPI sent. If a framework parses the JSON before you verify, serializing it again changes spacing or key order and the check fails. Verify first, parse second.

| Framework            | Read the raw body with                                               |
| -------------------- | -------------------------------------------------------------------- |
| Express              | `express.raw({ type: "*/*" })` on the webhook route, then `req.body` |
| Next.js (App Router) | `await request.text()`                                               |
| FastAPI              | `await request.body()`                                               |
| Django               | `request.body`                                                       |
| Laravel              | `$request->getContent()`                                             |
| Rails                | `request.raw_post`                                                   |
| Spring Boot          | a `@RequestBody byte[]` parameter                                    |
| ASP.NET Core         | copy `Request.Body` into a `MemoryStream`                            |

Then answer the request:

- **Signature fails:** respond with a `4XX` status and do nothing else.
- **Signature passes:** respond with a `2XX` status quickly, and move slow work to a background job. Any other status counts as a failed delivery, and SignatureAPI [retries it](https://signatureapi.com/docs/api/webhooks#retries).

The same event can arrive more than once. [Idempotent webhook processing](https://signatureapi.com/docs/api/guides/best-practices/idempotent-webhooks) shows how to process each event once.

## When Verification Fails

- **Every delivery fails with "No matching signature".** You are verifying a parsed body, or using the wrong secret. Check that the secret belongs to the endpoint's mode (test or live).
- **Only some deliveries fail.** A proxy or middleware changed the body, for example by decompressing or re-encoding it. Read the body before any middleware touches it.
- **"Timestamp outside the tolerance window".** Your server clock is more than 5 minutes off. Sync the clock with NTP instead of widening the tolerance.
- **The secret is "not valid base64".** Pass the whole `whsec_...` value. The functions remove the prefix themselves.

To check one delivery by hand, paste it into the [signature checker on the Webhooks page](https://signatureapi.com/docs/api/webhooks#authentication). It runs in your browser.
