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

# Verify signatures

> Confirm webhook requests came from Trace Finance with HMAC-SHA256 verification.

## Overview

Every webhook delivery follows the [Standard Webhooks](https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md) specification. Three headers let you verify that the request came from Trace Finance, that the body was not modified, and that the delivery is recent:

| Header | Description |
| - | - |
| `Webhook-Id` | Event identifier. Unique per event and identical on every retry and replay of it. Use it as the idempotency key. |
| `Webhook-Timestamp` | Unix timestamp in seconds of this delivery attempt. New on every retry. |
| `Webhook-Signature` | One or more space-separated signatures, each in the form `v1,<base64>`. New on every retry. |

The event type, resource and customer travel in the body, under the signature. Any other header on the request, such as the tracing headers `X-Correlation-Id`, `traceparent` and `tracestate`, is not signed: never trust it. See [Delivery format](https://docs.tracefinance.com/webhooks/overview.md#delivery-format).

> [!WARNING]
>
> `X-Message-Signature` is not sent in this format. Integrations that verify it must move to `Webhook-Signature`. The format is live in sandbox; production switches on a date Trace Finance announces. See [Migrating from the previous format](https://docs.tracefinance.com/webhooks/overview.md#migrating-from-the-previous-format).

Reject any request that fails verification — treat unsigned or mis-signed requests as untrusted.

## What is signed

The signature covers the event ID, the timestamp and the raw request body, joined by `.`. The raw body is the whole JSON body, so `type`, `resource`, `customerId`, `timestamp` and `data` are all covered:

```text theme={"theme":"tokyo-night"}
signed_content = Webhook-Id + "." + Webhook-Timestamp + "." + raw body
signature      = "v1," + Base64(HMAC-SHA256(key = clientSecret (UTF-8 bytes), data = signed_content))
```

> [!WARNING]
>
> Verify against the **raw body bytes** exactly as received. Do not parse and re-serialize the JSON before verifying: any change in whitespace or key order invalidates the signature.

## Verification steps

1. Read `Webhook-Id`, `Webhook-Timestamp` and `Webhook-Signature` from the request headers. Header names are case-insensitive and most frameworks lowercase them, so look them up without regard to case.
2. Reject the request if `Webhook-Timestamp` differs from your current time by more than a tolerance (5 minutes is recommended). This blocks replay of captured requests.
3. Compute the expected signature over `{Webhook-Id}.{Webhook-Timestamp}.{raw body}` with your client secret.
4. Split `Webhook-Signature` on spaces. Accept the request if **any** entry starting with `v1,` matches the expected value, using a constant-time comparison.

## Use a Standard Webhooks library

The official [Standard Webhooks libraries](https://github.com/standard-webhooks/standard-webhooks#libraries) perform every step above, including the timestamp check. They expect the secret in the form `whsec_` followed by the Base64 encoding of your client secret:

```text theme={"theme":"tokyo-night"}
whsec_<base64(clientSecret)>
```

> [tab] Python
>
> ```python theme={"theme":"tokyo-night"}
> import base64
> from standardwebhooks import Webhook
>
> secret = "whsec_" + base64.b64encode(client_secret.encode("utf-8")).decode("ascii")
> wh = Webhook(secret)
>
> # raw_body is the request body exactly as received (bytes or str)
> payload = wh.verify(raw_body, headers)  # raises WebhookVerificationError on failure
> event_type, event = payload["type"], payload["data"]
> ```

> [tab] JavaScript
>
> ```javascript theme={"theme":"tokyo-night"}
> import { Webhook } from "standardwebhooks";
>
> const secret = "whsec_" + Buffer.from(clientSecret, "utf8").toString("base64");
> const wh = new Webhook(secret);
>
> // rawBody is the request body exactly as received (string or Buffer)
> const payload = wh.verify(rawBody, headers); // throws on failure
> const { type, data } = payload;
> ```

> [tab] Go
>
> ```go theme={"theme":"tokyo-night"}
> import (
>     "encoding/base64"
>     standardwebhooks "github.com/standard-webhooks/standard-webhooks/libraries/go"
> )
>
> secret := "whsec_" + base64.StdEncoding.EncodeToString([]byte(clientSecret))
> wh, err := standardwebhooks.NewWebhook(secret)
> if err != nil {
>     return err
> }
>
> // rawBody is the request body exactly as received ([]byte); headers is the http.Header
> err = wh.Verify(rawBody, headers)
> ```

## Verify manually

If you prefer not to add a dependency, implement the steps yourself.

> [tab] Python
>
> ```python theme={"theme":"tokyo-night"}
> import base64
> import hashlib
> import hmac
> import time
>
> TOLERANCE_SECONDS = 300
>
> def verify_signature(webhook_id: str, timestamp: str, signature_header: str,
>                      raw_body: bytes, client_secret: str) -> bool:
>     if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
>         return False
>     signed_content = f"{webhook_id}.{timestamp}.".encode("utf-8") + raw_body
>     digest = hmac.new(client_secret.encode("utf-8"), signed_content, hashlib.sha256).digest()
>     expected = base64.b64encode(digest).decode("ascii")
>     for entry in signature_header.split(" "):
>         version, _, signature = entry.partition(",")
>         if version == "v1" and hmac.compare_digest(expected, signature):
>             return True
>     return False
> ```

> [tab] JavaScript
>
> ```javascript theme={"theme":"tokyo-night"}
> import { createHmac, timingSafeEqual } from "node:crypto";
>
> const TOLERANCE_SECONDS = 300;
>
> function verifySignature(webhookId, timestamp, signatureHeader, rawBody, clientSecret) {
>   if (Math.abs(Date.now() / 1000 - Number(timestamp)) > TOLERANCE_SECONDS) {
>     return false;
>   }
>   const expected = createHmac("sha256", clientSecret)
>     .update(`${webhookId}.${timestamp}.`)
>     .update(rawBody) // Buffer or string, exactly as received
>     .digest();
>   return signatureHeader.split(" ").some((entry) => {
>     const [version, signature] = entry.split(",");
>     if (version !== "v1" || !signature) return false;
>     const received = Buffer.from(signature, "base64");
>     return received.length === expected.length && timingSafeEqual(received, expected);
>   });
> }
> ```

> [tab] Go
>
> ```go theme={"theme":"tokyo-night"}
> import (
>     "crypto/hmac"
>     "crypto/sha256"
>     "encoding/base64"
>     "strconv"
>     "strings"
>     "time"
> )
>
> const toleranceSeconds = 300
>
> func VerifySignature(webhookID, timestamp, signatureHeader string, rawBody []byte, clientSecret string) bool {
>     ts, err := strconv.ParseInt(timestamp, 10, 64)
>     if err != nil {
>         return false
>     }
>     if diff := time.Now().Unix() - ts; diff > toleranceSeconds || diff < -toleranceSeconds {
>         return false
>     }
>     mac := hmac.New(sha256.New, []byte(clientSecret))
>     mac.Write([]byte(webhookID + "." + timestamp + "."))
>     mac.Write(rawBody)
>     expected := mac.Sum(nil)
>     for _, entry := range strings.Split(signatureHeader, " ") {
>         version, signature, found := strings.Cut(entry, ",")
>         if !found || version != "v1" {
>             continue
>         }
>         received, err := base64.StdEncoding.DecodeString(signature)
>         if err == nil && hmac.Equal(expected, received) {
>             return true
>         }
>     }
>     return false
> }
> ```

Always compare signatures in constant time (`hmac.compare_digest`, `crypto.timingSafeEqual`, `hmac.Equal`) to prevent timing attacks.

## Retries and idempotency

Each retry or replay of an event keeps the same body and `Webhook-Id` but carries a **new** `Webhook-Timestamp` and a **new** `Webhook-Signature`, so every attempt passes the timestamp check on its own. Use `Webhook-Id` as your idempotency key: persist it durably and skip events you have already processed. See [Retry policy](https://docs.tracefinance.com/webhooks/retry-policy.md).

## Where to find your client secret

Your `clientId` and `clientSecret` are issued during onboarding — the same credentials used to obtain access tokens (see [Authentication](https://docs.tracefinance.com/guides/authentication.md)). Store the secret server-side; never commit it to source control or expose it in client-side code.

> [!WARNING]
>
> If you suspect your client secret has been compromised, rotate it immediately and re-verify previously stored event IDs to detect any spoofed deliveries.

## Related

* [Retry policy](https://docs.tracefinance.com/webhooks/retry-policy.md) — handle failed verifications without losing events
* [Authentication](https://docs.tracefinance.com/guides/authentication.md) — how `clientId`/`clientSecret` are provisioned


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