---
title: "Verify signatures | Developer guide | R&D Copilot"
lang: en
canonical: https://rdcopilot.com/docs/signatures/
content_version: 61b08d124f43caacf4ae3b4831c7c73cb4fbc4ef2c354b28e4c297c6d856d63c
contact: https://rdcopilot.com/contact/
---

# Verify signatures

The three headers, the signed content, the check in five languages, a test vector and the mistakes that fail it.

Every delivery is signed, and your endpoint refuses one whose signature does not match.

The signature follows the public webhook signing specification, unchanged, so a library written for it works with our deliveries as well.

## The three headers

| Header | Value |
| --- | --- |
| `webhook-id` | The `id` of the event. The same on every attempt. |
| `webhook-timestamp` | Seconds since the epoch, of this attempt. |
| `webhook-signature` | `v1,<signature>`. Several values separated by a space while a secret is being rotated. |

## The signed content

The signed content is `<webhook-id>.<webhook-timestamp>.<raw body>`. The signature is HMAC-SHA256 of it with the secret of the subscription, in base64.

The secret is `whsec_` followed by base64. It is returned once, in the answer that creates the subscription. When the request is sent again, the answer leaves out `secret`, and so does `GET /operations/{operationId}`. The key of the HMAC is the part after `whsec_`, decoded from base64.

## The check

1.  Read the raw body before any parsing.
2.  Refuse the delivery when `webhook-timestamp` is more than 5 minutes from your clock.
3.  Compute the signature over the signed content, with the base64-decoded part of the secret after `whsec_`.
4.  Compare it with each value of `webhook-signature`, in constant time.
5.  Answer 2xx only if one of them matches.

## The check in code

Each function returns `true` when one of the signatures matches and the time is within the tolerance. Read the body as bytes, before any JSON parsing, and pass it as it is.

Verify a delivery

JavaScript

```javascript
import {createHmac, timingSafeEqual} from 'node:crypto';

const TOLERANCE_SECONDS = 300;

// headers: the request headers, names in lower case. rawBody: the body exactly as it arrived (a Buffer or a string).
export function verify(secret, headers, rawBody, now = Date.now() / 1000) {
  const id = headers['webhook-id'];
  const timestamp = headers['webhook-timestamp'];
  const received = headers['webhook-signature'];
  if (!id || !timestamp || !received) return false;

  const sent = Number(timestamp);
  if (!Number.isFinite(sent) || Math.abs(now - sent) > TOLERANCE_SECONDS) return false;

  const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
  const signed = Buffer.concat([Buffer.from(`${id}.${timestamp}.`), Buffer.from(rawBody)]);
  const expected = createHmac('sha256', key).update(signed).digest();

  return received.split(' ').some((value) => {
    const [version, signature] = value.split(',');
    if (version !== 'v1' || !signature) return false;
    const candidate = Buffer.from(signature, 'base64');
    return candidate.length === expected.length && timingSafeEqual(candidate, expected);
  });
}
```

Python

```python
import base64
import hashlib
import hmac
import time

TOLERANCE_SECONDS = 300

# headers: the request headers, names in lower case. raw_body: the body exactly as it arrived, as bytes.
def verify(secret, headers, raw_body, now=None):
    webhook_id = headers.get('webhook-id')
    timestamp = headers.get('webhook-timestamp')
    received = headers.get('webhook-signature')
    if not (webhook_id and timestamp and received):
        return False

    try:
        sent = int(timestamp)
    except ValueError:
        return False
    if abs((time.time() if now is None else now) - sent) > TOLERANCE_SECONDS:
        return False

    key = base64.b64decode(secret.removeprefix('whsec_'))
    signed = f'{webhook_id}.{timestamp}.'.encode() + raw_body
    expected = hmac.new(key, signed, hashlib.sha256).digest()

    for value in received.split(' '):
        version, _, signature = value.partition(',')
        if version != 'v1':
            continue
        try:
            candidate = base64.b64decode(signature)
        except ValueError:
            continue
        if hmac.compare_digest(candidate, expected):
            return True
    return False
```

PHP

```php
<?php

const TOLERANCE_SECONDS = 300;

// $headers: the request headers, names in lower case. $rawBody: the body exactly as it arrived.
function verify(string $secret, array $headers, string $rawBody, ?int $now = null): bool
{
    $id = $headers['webhook-id'] ?? '';
    $timestamp = $headers['webhook-timestamp'] ?? '';
    $received = $headers['webhook-signature'] ?? '';
    if ($id === '' || $received === '' || !ctype_digit($timestamp)) {
        return false;
    }
    if (abs(($now ?? time()) - (int) $timestamp) > TOLERANCE_SECONDS) {
        return false;
    }

    $key = base64_decode(preg_replace('/^whsec_/', '', $secret), true);
    if ($key === false) {
        return false;
    }
    $expected = hash_hmac('sha256', "$id.$timestamp.$rawBody", $key, true);

    foreach (explode(' ', $received) as $value) {
        [$version, $signature] = array_pad(explode(',', $value, 2), 2, '');
        if ($version !== 'v1') {
            continue;
        }
        $candidate = base64_decode($signature, true);
        if ($candidate !== false && hash_equals($expected, $candidate)) {
            return true;
        }
    }
    return false;
}
```

C#

```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

public static class Webhook
{
    const int ToleranceSeconds = 300;

    // headers: the request headers, names in lower case. rawBody: the body exactly as it arrived.
    public static bool Verify(string secret, IDictionary<string, string> headers, byte[] rawBody, DateTimeOffset? now = null)
    {
        if (!headers.TryGetValue("webhook-id", out var id)
            || !headers.TryGetValue("webhook-timestamp", out var timestamp)
            || !headers.TryGetValue("webhook-signature", out var received)) return false;

        if (!long.TryParse(timestamp, out var sent)) return false;
        if (Math.Abs((now ?? DateTimeOffset.UtcNow).ToUnixTimeSeconds() - sent) > ToleranceSeconds) return false;

        var key = Convert.FromBase64String(secret.StartsWith("whsec_") ? secret[6..] : secret);
        var signed = Encoding.UTF8.GetBytes($"{id}.{timestamp}.").Concat(rawBody).ToArray();
        var expected = HMACSHA256.HashData(key, signed);

        foreach (var value in received.Split(' '))
        {
            var parts = value.Split(',', 2);
            if (parts.Length != 2 || parts[0] != "v1") continue;
            try
            {
                if (CryptographicOperations.FixedTimeEquals(Convert.FromBase64String(parts[1]), expected)) return true;
            }
            catch (FormatException) { }
        }
        return false;
    }
}
```

Bash

```bash
# Recompute the signature of a delivery at the command line.
# WEBHOOK_SECRET comes from the answer that created the subscription; WEBHOOK_ID and WEBHOOK_TIMESTAMP come from the headers; BODY is the raw body.
key=$(printf '%s' "${WEBHOOK_SECRET#whsec_}" | base64 -d | xxd -p -c 256)
printf '%s.%s.%s' "$WEBHOOK_ID" "$WEBHOOK_TIMESTAMP" "$BODY" \
  | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$key" -binary \
  | base64
```

## The tolerance

The timestamp is the time of this attempt, in seconds since the epoch. A delivery whose timestamp is more than 5 minutes from your clock is refused, so a recorded delivery cannot be played back after that time. Keep the clock of your servers synchronised.

## Rotating the secret

Rotate the secret when it may have leaked, or on your own schedule: `POST /subscriptions/{id}/secret` returns a new one, in the first answer only: the same request sent again omits `secret`. After a rotation, every delivery carries both signatures for 24 hours, then only the new one. Your check accepts a delivery that carries two signatures, because it compares with each value of `webhook-signature`.

Rotate the secret

curl

```bash
curl -X POST "$RDC_BASE_URL/inventory/v1/subscriptions/a71c5e03-2d98-4b6f-8e40-f3b9d1c6a572/secret" \
  -H "Authorization: Bearer $RDC_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
  "operationId": "2c9f6b14-5a07-4d83-b1e6-8d40a7c3e925"
}'
```

JavaScript

```javascript
const response = await fetch(`${process.env.RDC_BASE_URL}/inventory/v1/subscriptions/a71c5e03-2d98-4b6f-8e40-f3b9d1c6a572/secret`, {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.RDC_TOKEN}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "operationId": "2c9f6b14-5a07-4d83-b1e6-8d40a7c3e925"
  }),
});
const result = await response.json();
```

Python

```python
import os
import requests

response = requests.request(
    'POST',
    f'{os.environ["RDC_BASE_URL"]}/inventory/v1/subscriptions/a71c5e03-2d98-4b6f-8e40-f3b9d1c6a572/secret',
    headers={
        'Authorization': f'Bearer {os.environ["RDC_TOKEN"]}',
    },
    json={
        'operationId': '2c9f6b14-5a07-4d83-b1e6-8d40a7c3e925',
    },
)
result = response.json()
```

PHP

```php
<?php

$body = <<<'JSON'
{
  "operationId": "2c9f6b14-5a07-4d83-b1e6-8d40a7c3e925"
}
JSON;

$curl = curl_init(getenv('RDC_BASE_URL') . '/inventory/v1/subscriptions/a71c5e03-2d98-4b6f-8e40-f3b9d1c6a572/secret');
curl_setopt_array($curl, [
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('RDC_TOKEN'),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => $body,
]);
$result = json_decode(curl_exec($curl), true);
curl_close($curl);
```

C#

```csharp
using System.Net.Http.Headers;

var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, $"{Environment.GetEnvironmentVariable("RDC_BASE_URL")}/inventory/v1/subscriptions/a71c5e03-2d98-4b6f-8e40-f3b9d1c6a572/secret");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("RDC_TOKEN"));
request.Content = new StringContent("""
{
  "operationId": "2c9f6b14-5a07-4d83-b1e6-8d40a7c3e925"
}
""", System.Text.Encoding.UTF8, "application/json");
var response = await client.SendAsync(request);
var result = await response.Content.ReadAsStringAsync();
```

Answer 202

```json
{
  "operationId": "2c9f6b14-5a07-4d83-b1e6-8d40a7c3e925",
  "status": "completed",
  "aggregateRevision": 2,
  "secret": "whsec_bmV3LXNpZ25pbmctc2VjcmV0LTAwMDAyIQ=="
}
```

-   Put the new secret in your endpoint within the 24 hours.
-   After that, only the new signature is sent, and a check with the old secret refuses every delivery.

## A test vector

Use these values to check your code before you receive a delivery. With this secret, id, timestamp and body, the signature is the one below. The body is one line, byte for byte.

| Part | Value |
| --- | --- |
| Secret | `whsec_cmRjLXNpZ25pbmctdGVzdC12ZWN0b3Ih` |
| `webhook-id` | `5e2b9c47-8d13-4a6f-b0e5-71c4a2d93f68` |
| `webhook-timestamp` | `1795167668` |
| `webhook-signature` | `v1,nHwjLFLsubbZ6pBvBHo16KBiIcMHXt3Ge72v7Zr6eUk=` |

The body

```json
{"specversion":"1.0","id":"5e2b9c47-8d13-4a6f-b0e5-71c4a2d93f68","type":"com.rdcopilot.inventory.movement.v1","source":"urn:rdcopilot:service:inventory-runtime","time":"2026-11-20T09:41:07Z","customerOrgId":"a3f1d7c2-64be-4b09-9d58-2c0e7f1a8b34","legalCompanyId":"c8b25e90-1d47-4f3a-a6d2-93e0b51f7c68","aggregateType":"inventory-balance","aggregateId":"e17d3b60-4a98-4c25-9f02-6b8a1d5c7e39","aggregateRevision":8,"correlationId":"3b7e41a8-9c25-4d60-b8f3-1a05e6d27c94","causationId":"4c8a1f72-e6b9-4d35-a0c8-5b2e9d7f1a63","actor":{"serviceId":"erp","userId":"9a4e7b10-2c6d-4f38-b5a1-0d3e8c7f6b25"},"data":{"movementId":"f2a95c08-6d41-4e7b-83a0-b7d14e92c5a6","productId":"7d0c4e19-b3a2-4f65-8e91-2a6f5c8d3b40","locationId":"1b9e6a35-d4c7-4082-b5f3-9e0a7c2d8164","onHandDelta":"0","reservedDelta":"24"}}
```

The vector has an old timestamp. Pass the time of the test to your function, or compare the computed signature with the value above before the time check.

## Mistakes that fail the check

| Mistake | What happens | What to do |
| --- | --- | --- |
| Parsing the body, then serialising it again | The bytes differ, so a good delivery is refused. | Keep the raw bytes, verify them, and parse only afterwards. |
| Comparing with `==` | The time to answer leaks how much of the signature matched. | Use the constant-time comparison of your language. |
| A clock that is wrong | Every delivery is refused as too old or too new. | Synchronise the clock of the server. |
| Using the secret as text | The signature never matches. | Remove `whsec_` and decode the rest from base64. |
| Reading only the first value of `webhook-signature` | During a rotation the right signature can be the second. | Split on spaces and try each value. |

Answer 2xx only after the check passes. An endpoint that accepts every request accepts forged ones.

## Related pages

-   [Webhooks](https://rdcopilot.com/docs/webhooks/): the endpoint around the check.
-   [Replay parked events](https://rdcopilot.com/docs/replay/): deliveries that failed.

[Previous · **Webhooks**](https://rdcopilot.com/docs/webhooks/) [Next · **Replay parked events**](https://rdcopilot.com/docs/replay/)

---

R&D Copilot · Made in EU · Contact: https://rdcopilot.com/contact/
