# Receive webhooks

> Canonical URL: https://docs.mountaya.com/en/sdks/kotlin/webhooks/
> Last updated: 2026-11-27
> Rules for agents: https://docs.mountaya.com/llms.txt#rules-for-agents

Verify a Mountaya webhook delivery on a JVM server with constructWebhookEvent, handle its typed event, and test your receiver.

Mountaya delivers each change your [webhook endpoints](https://docs.mountaya.com/en/webhooks.md) subscribe to as a signed `POST`. On a JVM server, `constructWebhookEvent` checks the signature and reads the event.

## Verify a delivery

Pass the body exactly as it arrived, before any JSON parser reads it, with its `Mountaya-Signature` header:

```kotlin
import com.mountaya.admin.WebhookSignatureException
import com.mountaya.admin.constructWebhookEvent

val secret = System.getenv("MOUNTAYA_WEBHOOK_SECRET").orEmpty()

fun receive(body: ByteArray, signature: String?): Int {
    val event =
        try {
            constructWebhookEvent(body, signature, secret)
        } catch (refusal: WebhookSignatureException) {
            println(refusal.reason)
            return 400
        }
    // Queue the event and answer at once. Act on each event.id once.
    println("${event.id} ${event.type}")
    return 200
}
```

Answer a refused delivery with `400`, and every other one with a `2xx` within 10 seconds. [Signatures](https://docs.mountaya.com/en/webhooks/signatures.md) explains the header.

- `constructWebhookEvent(rawBody, signatureHeader, secret, tolerance = 300.seconds, now = null)` is declared in `mountaya-admin` on the jvm alone, so an Android or iOS build cannot call it and the endpoint's secret never ships in an app. `WebhookSignatureException` and `WebhookEvent` are common code (`com.mountaya.admin`, `com.mountaya.admin.generated`).
- The body is a `ByteArray`, or a `String` verified by its UTF-8 bytes. A body decoded and encoded again is other bytes and does not verify.
- The secret is the endpoint's, `whsk_` included. A secret that does not open with `whsk_` and a negative `tolerance` are each a `ConfigurationException` thrown before the header is read, since either is a mistake in your code; the message never quotes the secret.
- `WebhookSignatureException.reason`: `MissingHeader`, `MalformedHeader`, `Signature` (no `v1` of the header matches) and `Timestamp` (the signature verifies, but was made further from your clock than the tolerance, 300 seconds either way). It is a `MountayaException`, so a handler catching the family catches it too.
- Mountaya delivers an event at least once and in no set order: keep what you acted on keyed by `event.id`. A non-`2xx` answer is a failed attempt, retried on the delivery schedule.
- In this SDK the refusal type, `WebhookSignatureException`, lives in the admin unit, `mountaya-admin` (`com.mountaya.admin`), beside `constructWebhookEvent`; the client core declares neither.

## Handle an event

Each event type has a class of `WebhookEvent`, so a `when` reads what each carries:

```kotlin
import com.mountaya.admin.generated.WebhookEvent

fun handle(event: WebhookEvent) {
    when (event) {
        is WebhookEvent.OrganizationMemberUpdated -> {
            // The membership as it is now, and the role it held before the change.
            println("${event.data.`object`.role}, was ${event.data.previous_attributes?.role}")
        }

        is WebhookEvent.CollectionDeleted -> println("collection ${event.data.`object`.id} deleted")
        else -> println("${event.type} at ${event.created_at}")
    }
}
```

- Every member of the envelope is read off the event whatever its class: `id`, `type`, `api_version`, `created_at`, `organization_id`, `task`, `related_object`, `request`, `actor`.
- `event.data.object` is the resource as it is now. `event.data.previous_attributes` holds the fields the change moved, each null where it did not move; a field that may be null reads as a `Stated` holding null where it was null. A type whose change moves nothing has `Nothing` there.
- Instants are `kotlin.time.Instant`s, read as a method answers them.
- The event types and their payloads are on [webhooks](https://docs.mountaya.com/en/webhooks.md), one page per family (such as [itinerary events](https://docs.mountaya.com/en/webhooks/events/itinerary.md)).

## Ignore unknown events

A type newer than your build arrives as `WebhookEvent.Unknown`. Answer it `2xx` and move on:

```kotlin
import com.mountaya.admin.generated.WebhookEvent

fun isKnown(event: WebhookEvent): Boolean =
    when (event) {
        is WebhookEvent.Unknown -> {
            // A type added after this build: keep the id, act on nothing.
            println("unknown ${event.type}, id ${event.id}")
            false
        }

        else -> true
    }
```

- `WebhookEvent.Unknown` holds the contract's envelope, `AdminSchema.WebhookEvent`, as `admin.webhooks.getOrganizationWebhookEvents` lists it, in `event.event`. An event whose payload this build's types do not read arrives as `Unknown` too.
- A `when` over an event keeps an `else`: the types grow with the contract.

## Rotate the secret

Rotate the secret in the Mountaya app, under **Organization → Webhooks**. The previous secret keeps signing for up to 7 days, and the header carries a `v1` for each. Deploy the new secret to `MOUNTAYA_WEBHOOK_SECRET` before the overlap ends: either secret verifies meanwhile.

- Rotation is in the Mountaya app alone (an endpoint's menu, **Rotate secret**), by an owner or admin; no API operation rotates or reveals a secret. A second rotation that keeps an overlap is refused while one runs (`409` coded `SECRET_ROTATION_IN_OVERLAP`).
- `constructWebhookEvent` takes one secret and accepts a delivery when any `v1` of the header matches it, so swapping the configured secret at any point of the overlap loses no delivery.
- After a leak, rotate with no overlap: every earlier secret stops at once. See [rotation](https://docs.mountaya.com/en/webhooks/signatures.md#rotation).

## Test your receiver

Run your receiver against the published [test vectors](https://docs.mountaya.com/en/webhooks/signatures.md#test-vectors), with `now` pinned to each vector's clock:

```kotlin
import com.mountaya.admin.WebhookSignatureException
import com.mountaya.admin.constructWebhookEvent
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.boolean
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.long
import java.io.File
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.time.Instant

class SignatureVectorsTest {
    @Test
    fun everyPublishedVectorVerifiesAsExpected() {
        // Downloaded from /schemas/v0.9.0/openapi/api/webhooks/signature-vectors.json.
        val vectors = Json.parseToJsonElement(File("signature-vectors.json").readText()).jsonObject
        for (case in vectors.getValue("cases").jsonArray.map { it.jsonObject }) {
            fun text(name: String) = case.getValue(name).jsonPrimitive.content
            val verified =
                try {
                    constructWebhookEvent(
                        text("body"),
                        text("header"),
                        text("secret"),
                        now = Instant.fromEpochSeconds(case.getValue("now").jsonPrimitive.long),
                    )
                    true
                } catch (refusal: WebhookSignatureException) {
                    false
                }
            val expected = case.getValue("expect").jsonObject.getValue("valid").jsonPrimitive.boolean
            assertEquals(expected, verified, text("name"))
        }
    }
}
```

- Each vector gives the secret the receiver holds, the receiver's clock as `now` (Unix seconds), the header, the body and whether it verifies (`expect.valid`, and `expect.reason` where it does not): `valid`, `rotation-new-secret`, `rotation-previous-secret`, `tampered-body` (`Signature`) and `outside-tolerance` (`Timestamp`). Pass the body as the `String` the file holds: it is verified by its UTF-8 bytes.
- To send a real test delivery to your endpoint, call `admin.webhooks.postOrganizationWebhookDelivery(organizationId, AdminSchema.WebhookDeliveryCreateParams(endpointId) { test = AdminSchema.WebhookDeliveryTestParams(AdminSchema.WebhookEventType.ItineraryPublished) })`.
- `WebhookDeliveryCreateParams(webhook_endpoint_id) { … }` takes exactly one of `test` (a test event of a type), `event_id` (resend one event) or `since` (redeliver every event sent to the endpoint from an instant on); none or more than one is a `400`. A disabled endpoint is a `409`.
- `constructWebhookEvent(body, signature, secret, now = …)` judges the timestamp against the instant you pass; left out, it is the machine's wall clock. See [testing webhooks](https://docs.mountaya.com/en/webhooks/testing.md).

## Next steps

- [Manage an organization](https://docs.mountaya.com/en/sdks/kotlin/admin.md): Create webhook endpoints from a server.
- [Webhook signatures](https://docs.mountaya.com/en/webhooks/signatures.md): The header, the tolerance and the test vectors.
