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

## Ktor

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

```kotlin
import com.cryptochief.processing.webhook.PayoutWebhookEvent
import com.cryptochief.processing.webhook.WebhookVerificationException
import com.cryptochief.processing.webhook.WebhookVerifier
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*

fun Application.webhookRouting(apiKey: String) = routing {
    post("/webhook/payout") {
        val raw = call.receiveStream().readAllBytes() // EXACT bytes — do not re-encode
        try {
            val event = WebhookVerifier.parse<PayoutWebhookEvent>(
                apiKey, raw, call.request.headers.toMap(),
            )
            if (event.status == "paid") {
                // payout.paid — reconcile your ledger
            }
            call.respond(HttpStatusCode.OK)
        } catch (e: WebhookVerificationException) {
            call.respond(HttpStatusCode.Unauthorized)
        }
    }
}
```

## Spring Boot

```kotlin
import com.cryptochief.processing.webhook.PayInWebhookEvent
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")
class WebhookController(@Value("\${cryptochief.api-key}") private val apiKey: String) {

    @PostMapping("/payin")
    fun handle(
        @RequestBody raw: ByteArray,
        @RequestHeader headers: HttpHeaders,
    ): ResponseEntity<String> = try {
        val event = WebhookVerifier.parse<PayInWebhookEvent>(apiKey, raw, headers)
        if (event.status == "paid") {
            // invoice.paid — fulfill order event.orderId
        }
        ResponseEntity.ok("")
    } catch (e: WebhookVerificationException) {
        ResponseEntity.status(401).body("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:

```kotlin
import com.cryptochief.processing.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

val server = HttpServer.create(InetSocketAddress(8080), 0)
server.createContext("/webhook") { exchange ->
    val raw = exchange.requestBody.readAllBytes()
    try {
        val event = WebhookVerifier.parse<PayoutWebhookEvent>(apiKey, raw, exchange.requestHeaders)
        println("payout ${event.uuid} → ${event.status}")
        exchange.sendResponseHeaders(200, 0)
        exchange.responseBody.use { it.write("ok".toByteArray()) }
    } catch (e: WebhookVerificationException) {
        exchange.sendResponseHeaders(401, -1)
        exchange.close()
    } catch (e: DecodeException) {
        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:

```kotlin
import com.cryptochief.processing.webhook.WebhookVerificationException
import com.cryptochief.processing.webhook.WebhookVerifier

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

`rawBody` is the `ByteArray` as received. Headers come either as a `Map<String, List<String>>` — Spring `HttpHeaders`, `com.sun.net.httpserver.Headers`, Ktor's `headers.toMap()` — or as a `(String) -> String?` lookup such as `{ name -> request.getHeader(name) }`. 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 are `WebhookVerificationException`, a sealed class. An empty `apiKey` throws `IllegalArgumentException`. `tolerance` and `now` set the window and the time source, on `verify` and `parse` alike:

```kotlin
import kotlin.time.Duration.Companion.seconds
import java.time.Instant

WebhookVerifier.verify(apiKey, rawBody, headers, tolerance = 60.seconds) { Instant.now() }
```

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

Confirmation fields on events:

| Event type                | Field                                    | 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/kotlin/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/kotlin/guides/sign-execute.md#confirm).                                                                          |
| `SweepWebhookEvent`       | `sweepConfirmations`                     | At least `requiredConfirmations`. See [Sweep callbacks](https://docs-sdk.crypto-chief.com/processing/kotlin/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` key once its transaction is on chain:

```kotlin
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive

event.sources?.jsonArray?.forEach { src ->
    val confirmations = src.jsonObject["confirmations"]?.jsonPrimitive?.intOrNull // null until seen on chain
    println("${src.jsonObject["address"]?.jsonPrimitive?.content}: ${confirmations ?: "not seen yet"}")
}
```

{% hint style="warning" %}
**Absent and empty mean different things from one event to the next.** A `static_deposit.*` payload sends `contract` as an **empty string** for a native-coin transfer, so `contract == null` is not the test for "this was a coin, not a token" — use `contract.isNullOrEmpty()`. Its `amountFiat` is likewise empty when no conversion rate was available, `blockNumber` arrives only after the transaction is in a block, and `confirmedAt` / `paidAt` stay `null` until the deposit reaches those points.

A `sweep.confirmed` payload does the opposite: fields the platform has no value for are **omitted**, so a native sweep decodes with `assetContract` as `null`, and a `null` `gasPumpTxHash` means no gas had to be fronted.
{% endhint %}

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