> ## Documentation Index
> Fetch the complete documentation index at: https://docs.widgetic.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Verify signatures

> Check that a call to your server really comes from Widgetic, in TypeScript, Python, Go, Java, C#, Ruby and PHP

Every call Widgetic makes to your server is signed: [partner webhooks](https://docs.widgetic.com/docs/webhooks/partner-webhooks.md) and [MCP events](https://docs.widgetic.com/docs/webhooks/mcp-events.md) alike. Anyone can send a request to a public address, so check the signature before you trust a call.

The scheme is [Standard Webhooks](https://www.standardwebhooks.com). A library for it checks a call (see [Use a library](#use-a-library)), and the examples below need no library at all.

## What is signed

Three headers go with every call.

| Header | What it holds |
| - | - |
| `webhook-id` | The id of the call. It is the same on every try of one event, so keep the ids you handled and drop a repeat |
| `webhook-timestamp` | When the call was signed, in seconds since 1970 |
| `webhook-signature` | One or more signatures separated by a space, each one `v1,` and a base64 text. Two are listed while a [rotated secret](#rotate-a-secret) overlaps |

The signature is an HMAC-SHA256, in base64, of the text `<webhook-id>.<webhook-timestamp>.<raw body>`. To check a call:

1. Take your secret (it starts with `whsec_`), drop that prefix and decode the rest from base64. Those bytes are the key.
2. Join the `webhook-id`, a dot, the `webhook-timestamp`, a dot and the raw body.
3. Sign it with HMAC-SHA256 under the key, encode the result in base64 and put `v1,` in front.
4. Compare it, in constant time, with each signature in the header. One match is enough.
5. Refuse a call whose `webhook-timestamp` is more than five minutes away from your clock.

> [!WARNING]
>
> Sign the **raw body**, exactly as it arrived, and not a copy that your framework parsed and wrote out again: one space or one key in another place breaks the signature. [Get the raw body](#get-the-raw-body) shows where it is in the common frameworks.

## Check a call

Each example takes the raw body, the three headers and your secret, and throws (Go returns an error) when the call does not come from Widgetic. The last argument is the current time: leave it out, and the example reads the clock. A test passes the time of its sample call.

```typescript TypeScript theme={"theme":"css-variables"}
import { createHmac, timingSafeEqual } from 'node:crypto';

const TOLERANCE_IN_SECONDS = 5 * 60;

/**
 * Checks that a call really comes from Widgetic, and throws when it does not.
 * `rawBody` is the exact bytes that arrived, before any JSON parsing.
 */
export function verifyWidgeticWebhook(
  rawBody: string | Buffer,
  webhookId: string | undefined,
  webhookTimestamp: string | undefined,
  webhookSignature: string | undefined,
  webhookSecret: string,
  nowInSeconds: number = Date.now() / 1000,
): void {
  if (!webhookId || !webhookTimestamp || !webhookSignature) {
    throw new Error('The call has no webhook headers');
  }

  // A copied call cannot be sent again later: refuse anything older (or newer) than five minutes.
  const ageInSeconds = Math.abs(nowInSeconds - Number(webhookTimestamp));
  if (!Number.isFinite(ageInSeconds)) {
    throw new Error('The webhook timestamp is not a number');
  }
  if (ageInSeconds > TOLERANCE_IN_SECONDS) {
    throw new Error('The webhook timestamp is outside the allowed window');
  }

  // The secret is "whsec_" followed by the key in base64.
  const signingKey = Buffer.from(webhookSecret.replace(/^whsec_/, ''), 'base64');
  const signature = createHmac('sha256', signingKey)
    .update(`${webhookId}.${webhookTimestamp}.`)
    .update(rawBody)
    .digest('base64');
  const expected = Buffer.from(`v1,${signature}`);

  // While a rotated secret overlaps, the header holds two signatures separated by a space.
  const matches = webhookSignature.split(' ').some((candidate) => {
    const received = Buffer.from(candidate);
    return received.length === expected.length && timingSafeEqual(received, expected);
  });
  if (!matches) {
    throw new Error('The webhook signature does not match');
  }
}
```

```python Python theme={"theme":"css-variables"}
import base64
import hashlib
import hmac
import time

TOLERANCE_IN_SECONDS = 5 * 60


def verify_widgetic_webhook(raw_body, webhook_id, webhook_timestamp, webhook_signature, webhook_secret, now=None):
    """Checks that a call really comes from Widgetic, and raises ValueError when it does not.

    `raw_body` is the exact bytes that arrived, before any JSON parsing.
    """
    if not (webhook_id and webhook_timestamp and webhook_signature):
        raise ValueError("The call has no webhook headers")

    # A copied call cannot be sent again later: refuse anything older (or newer) than five minutes.
    try:
        signed_at = int(webhook_timestamp)
    except ValueError:
        raise ValueError("The webhook timestamp is not a number") from None
    if abs((time.time() if now is None else now) - signed_at) > TOLERANCE_IN_SECONDS:
        raise ValueError("The webhook timestamp is outside the allowed window")

    # The secret is "whsec_" followed by the key in base64.
    signing_key = base64.b64decode(webhook_secret.removeprefix("whsec_"))
    signed_content = f"{webhook_id}.{webhook_timestamp}.".encode() + raw_body
    digest = hmac.new(signing_key, signed_content, hashlib.sha256).digest()
    expected = ("v1," + base64.b64encode(digest).decode()).encode()

    # While a rotated secret overlaps, the header holds two signatures separated by a space.
    if not any(hmac.compare_digest(candidate.encode(), expected) for candidate in webhook_signature.split(" ")):
        raise ValueError("The webhook signature does not match")
```

```go Go theme={"theme":"css-variables"}
package widgetic

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

const toleranceInSeconds = 5 * 60

// VerifyWebhook checks that a call really comes from Widgetic, and returns an error when it does not.
// rawBody is the exact bytes that arrived, before any JSON parsing. Pass time.Now() as now.
func VerifyWebhook(rawBody []byte, webhookID, webhookTimestamp, webhookSignature, webhookSecret string, now time.Time) error {
	if webhookID == "" || webhookTimestamp == "" || webhookSignature == "" {
		return errors.New("the call has no webhook headers")
	}

	// A copied call cannot be sent again later: refuse anything older (or newer) than five minutes.
	signedAt, err := strconv.ParseInt(webhookTimestamp, 10, 64)
	if err != nil {
		return errors.New("the webhook timestamp is not a number")
	}
	if age := now.Unix() - signedAt; age > toleranceInSeconds || age < -toleranceInSeconds {
		return errors.New("the webhook timestamp is outside the allowed window")
	}

	// The secret is "whsec_" followed by the key in base64.
	signingKey, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(webhookSecret, "whsec_"))
	if err != nil {
		return errors.New("the webhook secret is not valid base64")
	}
	mac := hmac.New(sha256.New, signingKey)
	mac.Write([]byte(webhookID + "." + webhookTimestamp + "."))
	mac.Write(rawBody)
	expected := []byte("v1," + base64.StdEncoding.EncodeToString(mac.Sum(nil)))

	// While a rotated secret overlaps, the header holds two signatures separated by a space.
	for _, candidate := range strings.Fields(webhookSignature) {
		if hmac.Equal([]byte(candidate), expected) {
			return nil
		}
	}
	return errors.New("the webhook signature does not match")
}
```

```java Java theme={"theme":"css-variables"}
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public final class WidgeticWebhook {
    private static final long TOLERANCE_IN_SECONDS = 5 * 60;

    private WidgeticWebhook() {}

    /**
     * Checks that a call really comes from Widgetic, and throws SecurityException when it does not.
     * rawBody is the exact bytes that arrived, before any JSON parsing. Pass System.currentTimeMillis() / 1000 as nowInSeconds.
     */
    public static void verify(byte[] rawBody, String webhookId, String webhookTimestamp, String webhookSignature,
                              String webhookSecret, long nowInSeconds) throws GeneralSecurityException {
        if (webhookId == null || webhookTimestamp == null || webhookSignature == null) {
            throw new SecurityException("The call has no webhook headers");
        }

        // A copied call cannot be sent again later: refuse anything older (or newer) than five minutes.
        long signedAt;
        try {
            signedAt = Long.parseLong(webhookTimestamp);
        } catch (NumberFormatException error) {
            throw new SecurityException("The webhook timestamp is not a number");
        }
        if (Math.abs(nowInSeconds - signedAt) > TOLERANCE_IN_SECONDS) {
            throw new SecurityException("The webhook timestamp is outside the allowed window");
        }

        // The secret is "whsec_" followed by the key in base64.
        byte[] signingKey = Base64.getDecoder().decode(webhookSecret.replaceFirst("^whsec_", ""));
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(signingKey, "HmacSHA256"));
        mac.update((webhookId + "." + webhookTimestamp + ".").getBytes(StandardCharsets.UTF_8));
        String signature = Base64.getEncoder().encodeToString(mac.doFinal(rawBody));
        byte[] expected = ("v1," + signature).getBytes(StandardCharsets.UTF_8);

        // While a rotated secret overlaps, the header holds two signatures separated by a space.
        for (String candidate : webhookSignature.split(" ")) {
            if (MessageDigest.isEqual(candidate.getBytes(StandardCharsets.UTF_8), expected)) {
                return;
            }
        }
        throw new SecurityException("The webhook signature does not match");
    }
}
```

```csharp C# theme={"theme":"css-variables"}
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

public static class WidgeticWebhook
{
    private const long ToleranceInSeconds = 5 * 60;

    /// <summary>
    /// Checks that a call really comes from Widgetic, and throws UnauthorizedAccessException when it does not.
    /// <paramref name="rawBody"/> is the exact bytes that arrived, before any JSON parsing. Pass DateTimeOffset.UtcNow as <paramref name="now"/>.
    /// </summary>
    public static void Verify(byte[] rawBody, string webhookId, string webhookTimestamp, string webhookSignature, string webhookSecret, DateTimeOffset now)
    {
        if (string.IsNullOrEmpty(webhookId) || string.IsNullOrEmpty(webhookTimestamp) || string.IsNullOrEmpty(webhookSignature))
        {
            throw new UnauthorizedAccessException("The call has no webhook headers");
        }

        // A copied call cannot be sent again later: refuse anything older (or newer) than five minutes.
        if (!long.TryParse(webhookTimestamp, out var signedAt))
        {
            throw new UnauthorizedAccessException("The webhook timestamp is not a number");
        }
        if (Math.Abs(now.ToUnixTimeSeconds() - signedAt) > ToleranceInSeconds)
        {
            throw new UnauthorizedAccessException("The webhook timestamp is outside the allowed window");
        }

        // The secret is "whsec_" followed by the key in base64.
        var signingKey = Convert.FromBase64String(webhookSecret.StartsWith("whsec_") ? webhookSecret.Substring(6) : webhookSecret);
        var signedContent = Encoding.UTF8.GetBytes($"{webhookId}.{webhookTimestamp}.").Concat(rawBody).ToArray();
        var signature = Convert.ToBase64String(HMACSHA256.HashData(signingKey, signedContent));
        var expected = Encoding.UTF8.GetBytes($"v1,{signature}");

        // While a rotated secret overlaps, the header holds two signatures separated by a space.
        foreach (var candidate in webhookSignature.Split(' ', StringSplitOptions.RemoveEmptyEntries))
        {
            if (CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(candidate), expected))
            {
                return;
            }
        }
        throw new UnauthorizedAccessException("The webhook signature does not match");
    }
}
```

```ruby Ruby theme={"theme":"css-variables"}
require "base64"
require "openssl"

module WidgeticWebhook
  TOLERANCE_IN_SECONDS = 5 * 60

  class InvalidWebhook < StandardError; end

  # Checks that a call really comes from Widgetic, and raises InvalidWebhook when it does not.
  # raw_body is the exact text that arrived, before any JSON parsing.
  def self.verify!(raw_body, webhook_id, webhook_timestamp, webhook_signature, webhook_secret, now: Time.now.to_i)
    if [webhook_id, webhook_timestamp, webhook_signature].any? { |header| header.to_s.empty? }
      raise InvalidWebhook, "The call has no webhook headers"
    end

    # A copied call cannot be sent again later: refuse anything older (or newer) than five minutes.
    signed_at = Integer(webhook_timestamp, 10, exception: false)
    raise InvalidWebhook, "The webhook timestamp is not a number" if signed_at.nil?
    raise InvalidWebhook, "The webhook timestamp is outside the allowed window" if (now - signed_at).abs > TOLERANCE_IN_SECONDS

    # The secret is "whsec_" followed by the key in base64.
    signing_key = Base64.strict_decode64(webhook_secret.delete_prefix("whsec_"))
    signed_content = "#{webhook_id}.#{webhook_timestamp}.".b + raw_body.b
    expected = "v1,#{Base64.strict_encode64(OpenSSL::HMAC.digest("SHA256", signing_key, signed_content))}"

    # While a rotated secret overlaps, the header holds two signatures separated by a space.
    matches = webhook_signature.split(" ").any? do |candidate|
      candidate.bytesize == expected.bytesize && OpenSSL.fixed_length_secure_compare(candidate, expected)
    end
    raise InvalidWebhook, "The webhook signature does not match" unless matches
  end
end
```

```php PHP theme={"theme":"css-variables"}
<?php

declare(strict_types=1);

const TOLERANCE_IN_SECONDS = 5 * 60;

/**
 * Checks that a call really comes from Widgetic, and throws when it does not.
 * $rawBody is the exact text that arrived, before any JSON parsing.
 */
function verifyWidgeticWebhook(
    string $rawBody,
    ?string $webhookId,
    ?string $webhookTimestamp,
    ?string $webhookSignature,
    string $webhookSecret,
    ?int $now = null,
): void {
    if ($webhookId === null || $webhookId === '' || $webhookTimestamp === null || $webhookTimestamp === '' || $webhookSignature === null || $webhookSignature === '') {
        throw new RuntimeException('The call has no webhook headers');
    }

    // A copied call cannot be sent again later: refuse anything older (or newer) than five minutes.
    if (!ctype_digit($webhookTimestamp)) {
        throw new RuntimeException('The webhook timestamp is not a number');
    }
    if (abs(($now ?? time()) - (int) $webhookTimestamp) > TOLERANCE_IN_SECONDS) {
        throw new RuntimeException('The webhook timestamp is outside the allowed window');
    }

    // The secret is "whsec_" followed by the key in base64.
    $signingKey = base64_decode(str_starts_with($webhookSecret, 'whsec_') ? substr($webhookSecret, 6) : $webhookSecret, true);
    if ($signingKey === false) {
        throw new RuntimeException('The webhook secret is not valid base64');
    }
    $expected = 'v1,' . base64_encode(hash_hmac('sha256', "$webhookId.$webhookTimestamp.$rawBody", $signingKey, true));

    // While a rotated secret overlaps, the header holds two signatures separated by a space.
    foreach (explode(' ', $webhookSignature) as $candidate) {
        if (hash_equals($expected, $candidate)) {
            return;
        }
    }
    throw new RuntimeException('The webhook signature does not match');
}
```

## Get the raw body

Every framework has a way to hand you the body before it parses it.

| Framework | The raw body |
| - | - |
| Express | Put `express.raw({ type: 'application/json' })` on the route; `request.body` is a `Buffer` |
| Next.js (route handler) | `await request.text()` |
| Flask | `request.get_data()` |
| Django | `request.body` |
| FastAPI | `await request.body()` |
| Go (`net/http`) | `io.ReadAll(request.Body)` |
| Spring Boot | A `@RequestBody byte[] rawBody` parameter |
| ASP.NET Core | Read `Request.Body` yourself, before model binding turns it into an object |
| Rails | `request.raw_post` |
| Laravel | `$request->getContent()` |
| PHP without a framework | `file_get_contents('php://input')` |

## Use it in a receiver

This Express receiver keeps the body as it arrived, checks it, drops an event it has already handled and answers quickly. The same steps fit any framework.

```typescript theme={"theme":"css-variables"}
import express from 'express';
import { verifyWidgeticWebhook } from './verifyWidgeticWebhook';

const app = express();
const handledEventIds = new Set<string>(); // Use your database in production

// Keep the body as bytes: the signature covers exactly what was sent.
app.post('/widgetic/events', express.raw({ type: 'application/json' }), (request, response) => {
  const rawBody: Buffer = request.body;

  try {
    verifyWidgeticWebhook(
      rawBody,
      request.header('webhook-id'),
      request.header('webhook-timestamp'),
      request.header('webhook-signature'),
      process.env.WIDGETIC_WEBHOOK_SECRET ?? '',
    );
  } catch (error) {
    console.warn('Rejected a call to /widgetic/events:', error instanceof Error ? error.message : error);
    return response.status(400).send('Invalid signature');
  }

  const event = JSON.parse(rawBody.toString('utf8'));

  // Delivery is at least once, so the same event can arrive again with the same id.
  if (handledEventIds.has(event.id)) {
    return response.status(200).send('Already handled');
  }
  handledEventIds.add(event.id);

  if (event.type === 'invoice.paid') {
    console.log(`Invoice ${event.data.invoiceNumber} was paid at ${event.data.paidAt}`);
  } else if (event.type === 'credits.low') {
    console.log(`Credits are ${event.data.band}: ${event.data.balance} left`);
  }
  // Any other type: answer 2xx and move on. Widgetic adds event types from time to time.

  return response.status(200).send('ok');
});
```

## Use a library

Standard Webhooks publishes [a library](https://github.com/standard-webhooks/standard-webhooks/tree/main/libraries) for C#, Elixir, Go, Java, JavaScript, PHP, Python, Ruby and Rust. It reads the secret as Widgetic gives it, with the `whsec_` prefix, and checks the five minutes for you. In JavaScript:

```typescript theme={"theme":"css-variables"}
import { Webhook } from 'standardwebhooks';

const webhook = new Webhook(process.env.WIDGETIC_WEBHOOK_SECRET ?? '');

// Throws when the signature or the timestamp is wrong, and returns the parsed body when they are right.
const event = webhook.verify(rawBody, {
  'webhook-id': request.header('webhook-id') ?? '',
  'webhook-timestamp': request.header('webhook-timestamp') ?? '',
  'webhook-signature': request.header('webhook-signature') ?? '',
});
```

## Rotate a secret

A secret can change while calls are on their way. For a while, Widgetic signs each call with the old secret and the new one, and lists both signatures in `webhook-signature`, separated by a space. The examples above accept a call when either one matches, so you can switch your receiver to the new secret before the old one stops signing.

* For partner webhooks, [rotate the secret](https://docs.widgetic.com/docs/webhooks/partner-webhooks.md#rotate-the-secret) with `POST /partners/{partnerId}/notifications/webhook-secret`. The old one keeps signing for 1 day.
* For MCP events, send `events/subscribe` again with a new `secret`. The old one keeps signing for 10 minutes.

## Check your code against a known call

Use this call to try your code before the first real event. It is made up: the secret signs nothing else.

| What | Value |
| - | - |
| Secret | `whsec_AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=` |
| `webhook-id` | `evt_test_5f0c2a9e4b7d4c1e8a3b6d9f1c2e4a7b` |
| `webhook-timestamp` | `1794303005` |
| `webhook-signature` | `v1,/pZsd1vsezT/+z2mrlhajVG2sIHAIXFYJE27JKZyCXc=` |

The body is this text, in one line and without a line break at the end:

```json theme={"theme":"css-variables"}
{"id":"evt_test_5f0c2a9e4b7d4c1e8a3b6d9f1c2e4a7b","type":"credits.low","createdAt":"2026-11-10T09:30:05.000Z","partnerId":"7d5f3c1a-2b64-4c0e-9a51-6f1e2d3c4b5a","data":{"band":"low","balance":80,"threshold":100}}
```

Call your check with these values and `1794303005` as the current time. It must accept the call. Change one character of the body, or of the secret, and it must refuse it. The clock is a separate check: with a current time more than 300 seconds away from `1794303005`, it must refuse a call whose signature is right.

## When the signature does not match

* **You signed a copy of the body.** Parsing the JSON and writing it out again changes the bytes. Use the [raw body](#get-the-raw-body).
* **Something changed the body on its way.** A proxy or a middleware that reads the body first, or one that changes its encoding, breaks the signature. Look at the bytes your application receives.
* **It is the secret of another source.** A partner webhook and every MCP subscription have a secret of their own. A partner secret is shown once, when you set the address or rotate it; an MCP secret is the one you gave to `events/subscribe`.
* **You used the secret as text.** The key is the base64-decoded part after `whsec_`, as bytes.
* **Your clock is off.** A call whose `webhook-timestamp` is more than five minutes away from your clock is refused, even with a right signature. Keep the clock of your servers in step with a time service.
* **Your framework lower-cases or merges header names.** Header names are not case-sensitive, so look them up in a way that is not either.

To see what Widgetic sent for a partner webhook, and how your receiver answered, read the [delivery log](https://docs.widgetic.com/docs/partners/notifications.md#see-what-was-sent), or [send a test event](https://docs.widgetic.com/docs/webhooks/partner-webhooks.md#send-a-test-event).

> [card] [Partner webhooks](https://docs.widgetic.com/docs/webhooks/partner-webhooks.md)
>
> Set an address, choose events, answer and retries

> [card] [MCP events](https://docs.widgetic.com/docs/webhooks/mcp-events.md)
>
> Be called when a visitor sends an entry


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.