---
title: "Webhooks | Developer guide | R&D Copilot"
lang: en
canonical: https://rdcopilot.com/docs/webhooks/
content_version: 7ad4db155028729cbaa61cdf62905eeae529586473f37c8517c2622efc472d00
contact: https://rdcopilot.com/contact/
---

# Webhooks

Write an endpoint, create a subscription, verify each delivery, handle repeats, and read the schedule and the states.

A webhook is an HTTPS address of yours that receives events as they happen.

## Step 1: write the endpoint

An endpoint is a route of your service that accepts a `POST` with a JSON body. Answer with a 2xx status within 10 seconds and do the work afterwards, from a queue. A slow endpoint is a failed one.

An endpoint that verifies, then answers at once

```javascript
import {createServer} from 'node:http';
import {verify} from './verify.mjs';

const seen = new Set();
// queue() is yours: it puts the event where a worker takes it.

createServer((request, response) => {
  const chunks = [];
  request.on('data', (chunk) => chunks.push(chunk));
  request.on('end', () => {
    const rawBody = Buffer.concat(chunks);
    if (!verify(process.env.WEBHOOK_SECRET, request.headers, rawBody)) {
      response.writeHead(400).end();
      return;
    }
    const id = request.headers['webhook-id'];
    if (!seen.has(id)) {
      seen.add(id);
      queue(JSON.parse(rawBody));
    }
    response.writeHead(204).end();
  });
}).listen(8080);
```

## Step 2: create a subscription

A subscription names your endpoint and the event types you want. The answer carries the signing secret, `whsec_` followed by base64. It is shown once: store it as you receive it. When the request is sent again, the answer leaves out `secret`, and so does `GET /operations/{operationId}`. If you lose it, rotate it, as [Verify signatures](https://rdcopilot.com/docs/signatures/) shows.

Create the subscription

curl

```bash
curl -X POST "$RDC_BASE_URL/inventory/v1/subscriptions" \
  -H "Authorization: Bearer $RDC_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
  "operationId": "c4e8a2d1-7b30-4f95-a6c3-0e91d5b7f284",
  "endpoint": "https://erp.client.example/hooks/inventory",
  "eventTypes": [
    "com.rdcopilot.inventory.movement.v1"
  ]
}'
```

JavaScript

```javascript
const response = await fetch(`${process.env.RDC_BASE_URL}/inventory/v1/subscriptions`, {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.RDC_TOKEN}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "operationId": "c4e8a2d1-7b30-4f95-a6c3-0e91d5b7f284",
    "endpoint": "https://erp.client.example/hooks/inventory",
    "eventTypes": [
      "com.rdcopilot.inventory.movement.v1"
    ]
  }),
});
const result = await response.json();
```

Python

```python
import os
import requests

response = requests.request(
    'POST',
    f'{os.environ["RDC_BASE_URL"]}/inventory/v1/subscriptions',
    headers={
        'Authorization': f'Bearer {os.environ["RDC_TOKEN"]}',
    },
    json={
        'operationId': 'c4e8a2d1-7b30-4f95-a6c3-0e91d5b7f284',
        'endpoint': 'https://erp.client.example/hooks/inventory',
        'eventTypes': [
            'com.rdcopilot.inventory.movement.v1',
        ],
    },
)
result = response.json()
```

PHP

```php
<?php

$body = <<<'JSON'
{
  "operationId": "c4e8a2d1-7b30-4f95-a6c3-0e91d5b7f284",
  "endpoint": "https://erp.client.example/hooks/inventory",
  "eventTypes": [
    "com.rdcopilot.inventory.movement.v1"
  ]
}
JSON;

$curl = curl_init(getenv('RDC_BASE_URL') . '/inventory/v1/subscriptions');
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");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("RDC_TOKEN"));
request.Content = new StringContent("""
{
  "operationId": "c4e8a2d1-7b30-4f95-a6c3-0e91d5b7f284",
  "endpoint": "https://erp.client.example/hooks/inventory",
  "eventTypes": [
    "com.rdcopilot.inventory.movement.v1"
  ]
}
""", System.Text.Encoding.UTF8, "application/json");
var response = await client.SendAsync(request);
var result = await response.Content.ReadAsStringAsync();
```

Answer 202

```json
{
  "operationId": "c4e8a2d1-7b30-4f95-a6c3-0e91d5b7f284",
  "status": "completed",
  "aggregateRevision": 1,
  "subscriptionId": "a71c5e03-2d98-4b6f-8e40-f3b9d1c6a572",
  "secret": "whsec_cmRjLXNpZ25pbmctdGVzdC12ZWN0b3Ih"
}
```

The same request sent again: answer 202, with no secret

```json
{
  "operationId": "c4e8a2d1-7b30-4f95-a6c3-0e91d5b7f284",
  "status": "completed",
  "aggregateRevision": 1,
  "subscriptionId": "a71c5e03-2d98-4b6f-8e40-f3b9d1c6a572"
}
```

## Step 3: verify the signature

Every delivery is signed. Check the signature on the raw body before you read the event. [Verify signatures](https://rdcopilot.com/docs/signatures/) has the check and the code in five languages.

## Step 4: handle repeats and order

-   Skip an event whose `id` you already handled: a delivery can repeat, and `webhook-id` is the `id` of the event on every attempt.
-   Skip an event whose `aggregateRevision` is older than the state you hold for that record: deliveries can arrive out of order.
-   Keep the `id` of every event you handled. A replayed event keeps its `id`, so the same check works on it: see [Replay parked events](https://rdcopilot.com/docs/replay/).

## Delivery

A delivery has 6 attempts: at once, then after 1 minute, 5 minutes, 30 minutes, 2 hours and 12 hours. Your endpoint has 10 seconds to answer 2xx. After the sixth failure the event is parked.

| Attempt | Pause before it |
| --- | --- |
| `1` | None: sent at once |
| `2` | 1 minute after the first |
| `3` | 5 minutes after the second |
| `4` | 30 minutes after the third |
| `5` | 2 hours after the fourth |
| `6` | 12 hours after the fifth |

## The four states of a delivery

| Status | Meaning |
| --- | --- |
| delivered | Your endpoint confirmed the event. |
| retrying | An attempt failed and another one is waiting. |
| parked | The last attempt failed. The event is kept and is not sent again until you replay it. |
| replayed | A parked event was sent again on request. |

## What counts as a failure

| Your endpoint | Counted as |
| --- | --- |
| Answers with a 2xx status in time | Delivered |
| Answers with any other status, a redirect included | A failed attempt |
| Does not answer within 10 seconds | A failed attempt |
| Cannot be reached, or its certificate is not valid | A failed attempt |

## Changing and pausing a subscription

A subscription has a state, `state`, that is `active` or `paused`, an endpoint and the event types. Change them with a `PATCH` that carries `expectedRevision`, like any change. A paused subscription receives no deliveries. The events that happen meanwhile are parked: replay them when you resume.

Pause the subscription

curl

```bash
curl -X PATCH "$RDC_BASE_URL/inventory/v1/subscriptions/a71c5e03-2d98-4b6f-8e40-f3b9d1c6a572" \
  -H "Authorization: Bearer $RDC_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
  "operationId": "5d2b9e47-1a63-4c80-b7f2-93e6a0d8c415",
  "expectedRevision": 1,
  "state": "paused"
}'
```

JavaScript

```javascript
const response = await fetch(`${process.env.RDC_BASE_URL}/inventory/v1/subscriptions/a71c5e03-2d98-4b6f-8e40-f3b9d1c6a572`, {
  method: 'PATCH',
  headers: {
    Authorization: `Bearer ${process.env.RDC_TOKEN}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "operationId": "5d2b9e47-1a63-4c80-b7f2-93e6a0d8c415",
    "expectedRevision": 1,
    "state": "paused"
  }),
});
const result = await response.json();
```

Python

```python
import os
import requests

response = requests.request(
    'PATCH',
    f'{os.environ["RDC_BASE_URL"]}/inventory/v1/subscriptions/a71c5e03-2d98-4b6f-8e40-f3b9d1c6a572',
    headers={
        'Authorization': f'Bearer {os.environ["RDC_TOKEN"]}',
    },
    json={
        'operationId': '5d2b9e47-1a63-4c80-b7f2-93e6a0d8c415',
        'expectedRevision': 1,
        'state': 'paused',
    },
)
result = response.json()
```

PHP

```php
<?php

$body = <<<'JSON'
{
  "operationId": "5d2b9e47-1a63-4c80-b7f2-93e6a0d8c415",
  "expectedRevision": 1,
  "state": "paused"
}
JSON;

$curl = curl_init(getenv('RDC_BASE_URL') . '/inventory/v1/subscriptions/a71c5e03-2d98-4b6f-8e40-f3b9d1c6a572');
curl_setopt_array($curl, [
    CURLOPT_CUSTOMREQUEST => 'PATCH',
    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.Patch, $"{Environment.GetEnvironmentVariable("RDC_BASE_URL")}/inventory/v1/subscriptions/a71c5e03-2d98-4b6f-8e40-f3b9d1c6a572");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("RDC_TOKEN"));
request.Content = new StringContent("""
{
  "operationId": "5d2b9e47-1a63-4c80-b7f2-93e6a0d8c415",
  "expectedRevision": 1,
  "state": "paused"
}
""", System.Text.Encoding.UTF8, "application/json");
var response = await client.SendAsync(request);
var result = await response.Content.ReadAsStringAsync();
```

Register one endpoint for each environment, with its own subscription and its own secret. A test event must never reach a live endpoint.

Return a 2xx for an event you are skipping as a repeat. A repeat answered with an error is sent again for nothing.

## Related pages

-   [Verify signatures](https://rdcopilot.com/docs/signatures/): the check on every delivery.
-   [Replay parked events](https://rdcopilot.com/docs/replay/): when the last attempt failed.
-   [Events](https://rdcopilot.com/docs/events/): the envelope of an event.

[Previous · **Events**](https://rdcopilot.com/docs/events/) [Next · **Verify signatures**](https://rdcopilot.com/docs/signatures/)

---

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