> For the complete documentation index, see [llms.txt](https://docs-sdk.crypto-chief.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs-sdk.crypto-chief.com/processing/dotnet/guides/webhooks.md). Agents can also search and read this documentation through its [MCP server](https://docs-sdk.crypto-chief.com/~gitbook/mcp).

# Webhooks

Verify and handle Crypto Chief webhooks in ASP.NET Core with typed event payloads.

Webhooks are signed with your API key using HMAC-SHA256.

| Header               | Value                                                                               |
| -------------------- | ----------------------------------------------------------------------------------- |
| `X-Webhook-Delivery` | Delivery id, 1–128 characters `[A-Za-z0-9_-]`; the same on every attempt and resend |
| `X-CC-Timestamp`     | Unix time of the attempt, seconds                                                   |
| `X-CC-Signature`     | `v1=` + 64 hex characters                                                           |

The string to sign is four lines joined with `\n`, with no line break after the last one:

```
CC-HMAC-SHA256-WEBHOOK-V1
<X-CC-Timestamp>
<X-Webhook-Delivery>
<lowercase hex SHA-256 of the body>
```

`X-CC-Signature` is `v1=` followed by the lowercase hex HMAC-SHA256 of that string under your API key.

`body` is the raw request body. `WebhookVerifier` checks, in order: the three headers, the timestamp window (300 seconds), the signature (constant-time, hex in any case).

A retry or resend carries the same `X-Webhook-Delivery` and a new `X-CC-Timestamp`. Deduplicate by the delivery id — see [Webhook deliveries](https://docs-sdk.crypto-chief.com/processing/dotnet/guides/webhook-deliveries.md#keep-the-delivery-id).

## ASP.NET Core minimal API

Read the body, verify it, then decode it. A webhook that fails verification is answered `401`; a signed body that does not decode into the event type, `400`:

```csharp
using System.Text.Json;
using CryptoChief.Processing.Errors;
using CryptoChief.Processing.Webhooks;
using CryptoChief.Processing.Webhooks.Events;

var apiKey = builder.Configuration["CryptoChief:ApiKey"]!;

app.MapPost("/webhooks/payout", async (HttpRequest req) =>
{
    using var ms = new MemoryStream();
    await req.Body.CopyToAsync(ms);
    var body = ms.ToArray();

    PayoutWebhookEvent evt;
    try
    {
        evt = WebhookVerifier.VerifyAndDecode<PayoutWebhookEvent>(apiKey, body, req.Headers);
    }
    catch (WebhookVerificationException)
    {
        return Results.Unauthorized();
    }
    catch (Exception e) when (e is JsonException or CryptoChiefException)
    {
        return Results.BadRequest(); // signed, but not a payout event
    }

    // process evt — evt.Uuid, evt.OrderId, evt.Status, evt.AmountToReceive, ...
    return Results.Ok();
});
```

Pass `req.Headers`, not `name => req.Headers[name]`: the collection overload sees a header sent twice, a lookup cannot.

## Manual verification

For a custom HTTP stack or controller-based API:

```csharp
if (!WebhookVerifier.TryVerify(apiKey, body, Request.Headers))
    return Unauthorized();
```

Or the throwing form, which names the failed check:

```csharp
try
{
    WebhookVerifier.Verify(apiKey, body, Request.Headers);
}
catch (WebhookVerificationException)
{
    return Unauthorized();
}
```

`body` is the raw body as `byte[]` or `ReadOnlySpan<byte>` (a string: `Encoding.UTF8.GetBytes(body)`). Headers come as `IEnumerable<KeyValuePair<string, StringValues>>` (ASP.NET Core `Request.Headers`), `IEnumerable<KeyValuePair<string, IEnumerable<string>>>`, `IEnumerable<KeyValuePair<string, string>>`, `HttpHeaders`, or a `Func<string, string?>` lookup. Names are compared case-insensitively.

Catch the subclass to tell the checks apart:

| Exception                   | Cause                                                                     |
| --------------------------- | ------------------------------------------------------------------------- |
| `WebhookHeadersException`   | A signature header is missing, repeated or not in format                  |
| `WebhookTimestampException` | `X-CC-Timestamp` differs from the current time by more than the tolerance |
| `WebhookSignatureException` | The signature does not match the body                                     |

All three derive from `WebhookVerificationException`. An empty `apiKey` throws `ArgumentException` from `Verify` and makes `TryVerify` return `false`. `WebhookVerifyOptions` sets the tolerance and the clock, on every overload:

```csharp
var options = new WebhookVerifyOptions
{
    Tolerance = TimeSpan.FromSeconds(60),
    Now = () => DateTimeOffset.UtcNow,
};
WebhookVerifier.Verify(apiKey, body, Request.Headers, options);
```

`RequestSigner.SignWebhookV1(apiKey, timestamp, deliveryId, body)` returns the `X-CC-Signature` value, for testing a receiver.

## Event types

Typed payloads live in `CryptoChief.Processing.Webhooks.Events`:

* `PayoutWebhookEvent` — `payout.*`
* `TransactionWebhookEvent` — `transaction.*`
* `PayInWebhookEvent` — `invoice.*`
* `StaticDepositWebhookEvent` — `static_deposit.*`
* `SweepWebhookEvent` — `sweep.*`

Payout and transaction webhooks fire **only on terminal status**.

Confirmation properties on events:

| Event type                | Property                                 | Meaning                                                                                                                                                                                         |
| ------------------------- | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `PayoutWebhookEvent`      | `Confirmations`                          | `int?`. The lowest count among the sources; `null` while no source has a transaction. See [Send a payout](https://docs-sdk.crypto-chief.com/processing/dotnet/guides/payouts.md#confirmations). |
| `PayoutWebhookEvent`      | `RequiredConfirmations`                  | `int?`. The network's finality depth, at least `1`; `null` when not sent.                                                                                                                       |
| `TransactionWebhookEvent` | `Confirmations`, `RequiredConfirmations` | Always sent. See [Sign & execute](https://docs-sdk.crypto-chief.com/processing/dotnet/guides/sign-execute.md#confirm).                                                                          |
| `SweepWebhookEvent`       | `SweepConfirmations`                     | At least `RequiredConfirmations`. See [Sweep callbacks](https://docs-sdk.crypto-chief.com/processing/dotnet/guides/sweep-callbacks.md#payload).                                                 |
| `SweepWebhookEvent`       | `RequiredConfirmations`                  | `int?`. The network's finality depth; `null` when not sent.                                                                                                                                     |

`Sources` and `ServiceOperations` on a payout event are raw `JsonElement`s. Each element has a `confirmations` property once its transaction is on chain:

```csharp
using System.Text.Json;

if (evt.Sources is { ValueKind: JsonValueKind.Array } sources)
{
    foreach (var src in sources.EnumerateArray())
    {
        var count = src.TryGetProperty("confirmations", out var c) ? c.GetInt32().ToString() : "not seen yet";
        Console.WriteLine($"{src.GetProperty("address").GetString()}: {count}");
    }
}
```

{% hint style="warning" %}
**The two deposit-side events spell "nothing here" differently.** On `StaticDepositWebhookEvent` a native-coin transfer carries `Contract` as an **empty string**, not `null`; `ConfirmedAt` and `PaidAt` are `null` until the deposit is confirmed and paid, `BlockNumber` arrives only after block inclusion, and `AmountFiat` can be empty when no rate was available. On `SweepWebhookEvent` the platform leaves an unused key out of the payload instead, so a native sweep's `AssetContract` and an unfunded sweep's `GasPumpTxHash` decode as `null`. `string.IsNullOrEmpty` reads both correctly; `is null` alone does not.
{% endhint %}

`sweep.confirmed` is the moment swept funds reach the network's finality depth in your master wallet — the other half of a deposit's life, and what treasury reporting should key off. See [Sweep callbacks](https://docs-sdk.crypto-chief.com/processing/dotnet/guides/sweep-callbacks.md).

{% hint style="info" %}
`WebhookVerifier.SenderIps` lists the addresses webhooks are delivered from — whitelist them at your edge for defence in depth.
{% endhint %}
