> 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/java/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 Java 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/java/guides/webhook-deliveries.md#keep-the-delivery-id).

## Spring Boot

Read the raw bytes off the request, then verify and decode in one step. `WebhookVerifier.parse(...)` returns the typed event you ask for:

```java
import com.cryptochief.processing.webhook.PayoutWebhookEvent;
import com.cryptochief.processing.webhook.WebhookVerificationException;
import com.cryptochief.processing.webhook.WebhookVerifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/webhook")
public class WebhookController {

    @Value("${cryptochief.api-key}")
    private String apiKey;

    @PostMapping("/payout")
    public ResponseEntity<String> handle(@RequestBody byte[] raw, @RequestHeader HttpHeaders headers) {
        try {
            var event = WebhookVerifier.parse(apiKey, raw, headers, PayoutWebhookEvent.class);
            if ("paid".equals(event.status())) {
                // payout.paid — reconcile your ledger
            }
            return ResponseEntity.ok("");
        } catch (WebhookVerificationException e) {
            return ResponseEntity.status(401).body("webhook verification failed");
        }
    }
}
```

## Servlet (Tomcat, Jetty)

```java
import com.cryptochief.processing.webhook.PayInWebhookEvent;
import com.cryptochief.processing.webhook.WebhookVerificationException;
import com.cryptochief.processing.webhook.WebhookVerifier;
import jakarta.servlet.http.*;

public class WebhookServlet extends HttpServlet {
    private final String apiKey = System.getenv("CRYPTO_CHIEF_API_KEY");

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        byte[] raw = req.getInputStream().readAllBytes();
        try {
            var event = WebhookVerifier.parse(apiKey, raw, req::getHeader, PayInWebhookEvent.class);
            if ("paid".equals(event.status())) {
                // invoice.paid — fulfill order event.orderId()
            }
            resp.setStatus(200);
        } catch (WebhookVerificationException e) {
            resp.sendError(401, "webhook verification failed");
        }
    }
}
```

## Plain JDK server

The verification helpers do no I/O, so the JDK's built-in `HttpServer` works too. A handler that throws leaves the request unanswered, so catch both exceptions:

```java
import com.cryptochief.processing.exceptions.DecodeException;
import com.cryptochief.processing.webhook.PayoutWebhookEvent;
import com.cryptochief.processing.webhook.WebhookVerificationException;
import com.cryptochief.processing.webhook.WebhookVerifier;
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;

var server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/webhook", exchange -> {
    byte[] raw = exchange.getRequestBody().readAllBytes();
    try {
        var event = WebhookVerifier.parse(
                apiKey, raw, exchange.getRequestHeaders(), PayoutWebhookEvent.class);
        System.out.println("payout " + event.uuid() + " → " + event.status());
        exchange.sendResponseHeaders(200, 0);
        exchange.getResponseBody().write("ok".getBytes());
        exchange.close();
    } catch (WebhookVerificationException e) {
        exchange.sendResponseHeaders(401, -1);
        exchange.close();
    } catch (DecodeException e) {
        exchange.sendResponseHeaders(400, -1); // signed, but not a payout event
        exchange.close();
    }
});
server.start();
```

## Manual verification

For any other stack, pass the raw bytes and the headers. `verify` returns nothing and throws on failure:

```java
import com.cryptochief.processing.webhook.WebhookVerificationException;
import com.cryptochief.processing.webhook.WebhookVerifier;

try {
    WebhookVerifier.verify(apiKey, rawBody, headers);
} catch (WebhookVerificationException e) {
    // reject with 401
}
```

`rawBody` is the `byte[]` as received. Headers come either as a `Map<String, ?>` — values a `String`, a `String[]` or a `Collection<String>`, as in `com.sun.net.httpserver.Headers` or Spring `HttpHeaders` — or as a `Function<String, String>` lookup such as `request::getHeader`. Names are compared case-insensitively; the `Map` overloads see a header sent twice, a lookup cannot.

Catch the subclass to tell the checks apart:

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

All three extend `WebhookVerificationException`. An empty `apiKey` throws `IllegalArgumentException`. `WebhookOptions` sets the tolerance and the clock, on `verify` and `parse` alike:

```java
var options = WebhookOptions.defaults()
        .withTolerance(Duration.ofSeconds(60))
        .withClock(Clock.systemUTC());
WebhookVerifier.verify(apiKey, rawBody, headers, options);
```

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

## Event types

Typed payloads: `PayoutWebhookEvent`, `TransactionWebhookEvent`, `PayInWebhookEvent`, `StaticDepositWebhookEvent`, `SweepWebhookEvent`. Event-name prefixes are `payout.*`, `transaction.*`, `invoice.*` (pay-ins), `static_deposit.*`, and `sweep.*`. Payout and transaction webhooks fire **only on terminal status**.

`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/java/guides/sweep-callbacks.md).

Confirmation accessors on events:

| Event type                | Accessor                                     | Meaning                                                                                                                                                                                          |
| ------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `PayoutWebhookEvent`      | `confirmations()`                            | `Integer`. The lowest count among the sources; `null` while no source has a transaction. See [Send a payout](https://docs-sdk.crypto-chief.com/processing/java/guides/payouts.md#confirmations). |
| `PayoutWebhookEvent`      | `requiredConfirmations()`                    | `Integer`. 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/java/guides/sign-execute.md#confirm).                                                                             |
| `SweepWebhookEvent`       | `sweepConfirmations()`                       | At least `requiredConfirmations()`. See [Sweep callbacks](https://docs-sdk.crypto-chief.com/processing/java/guides/sweep-callbacks.md#payload).                                                  |
| `SweepWebhookEvent`       | `requiredConfirmations()`                    | `Integer`. The network's finality depth; `null` when not sent.                                                                                                                                   |

`sources()` and `serviceOperations()` on a payout event are raw `JsonNode`s. Each element has a `confirmations` field once its transaction is on chain:

```java
for (var src : event.sources()) {
    var confirmations = src.get("confirmations");   // null until on chain
    System.out.println(src.path("address").asText() + ": "
        + (confirmations == null ? "not seen yet" : confirmations.asInt()));
}
```

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

## How absence is spelled

The two deposit-side events disagree about how a missing value looks, and a `String` accessor cannot tell you which convention it just handed you.

`StaticDepositWebhookEvent.contract()` is an **empty string** for a native coin transfer — not `null`. That is the opposite of `WalletCoinBalance.contract()` on a wallet's balances, which is `null` for a native coin, so a helper shared between the two has to test for both.

```java
boolean isToken = event.contract() != null && !event.contract().isEmpty();
```

`SweepWebhookEvent` goes the other way: optional fields are **omitted** rather than sent empty, so `assetContract()` and `gasPumpTxHash()` arrive as `null` — a native sweep has no contract, and a null gas-pump hash means no gas had to be fronted. Sweep *history* sends the same absence as `""`; see [Auto-sweep settings](https://docs-sdk.crypto-chief.com/processing/java/guides/auto-sweep-settings.md#sent-is-not-settled).

On a static deposit, `confirmedAt()` is `null` until the deposit confirms and `paidAt()` is `null` until it is paid, `amountFiat()` may be empty when no conversion was available, and `blockNumber()` is a nullable `Long` — present only after block inclusion.
