# Receive webhooks

> Canonical URL: https://docs.mountaya.com/en/sdks/swift/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 Swift server with constructWebhookEvent, switch over its event, and test your receiver.

Mountaya sends each event your endpoint subscribes to as a signed `POST`. `constructWebhookEvent` checks the signature and gives you a typed event. [Webhooks](https://docs.mountaya.com/en/webhooks.md) explains deliveries, and [signatures](https://docs.mountaya.com/en/webhooks/signatures.md) the header.

## Verify a delivery

Hand it the body exactly as it arrived, the `Mountaya-Signature` header and your endpoint's secret:

```swift
import Foundation
import MountayaAdmin
import MountayaClient

let secret = ProcessInfo.processInfo.environment["MOUNTAYA_WEBHOOK_SECRET"] ?? ""

// On a server: the body exactly as it arrived and its Mountaya-Signature header in, the status out.
func receive(body: Data, signature: String?) -> Int {
  let event: WebhookEvent
  do {
    event = try constructWebhookEvent(rawBody: body, signatureHeader: signature, secret: secret)
  } catch MountayaError.webhookSignature(let refusal) {
    print(refusal.reason)
    return 400
  } catch {
    return 500
  }

  // Queue the event and answer at once. Deduplicate on event.id later.
  print(event.id, event.type.rawValue)
  return 200
}
```

Read the body before any JSON parser touches it. A body decoded and encoded again is other bytes, which do not verify.

- `constructWebhookEvent(rawBody:signatureHeader:secret:tolerance:now:)` takes the body as `Data` or as a `String` (verified by its UTF-8 bytes), and `throws(MountayaError)`. It exists on macOS and Linux only; an app build cannot name it.
- A refused delivery is `MountayaError.webhookSignature(WebhookSignatureError)`, the core's case, so one `catch` of `MountayaError` catches it. `reason`: `.missingHeader`, `.malformedHeader`, `.signature` (no `v1` of the header matches), `.timestamp` (the signature verifies but was made further from your clock than the tolerance). Answer it `400`.
- `tolerance` defaults to 300 seconds either way, a `Duration`: `tolerance: .seconds(600)`. A tolerance below zero, or a secret that does not start with `whsk_` (which the error never quotes), is your server's set-up and throws `MountayaError.configuration` before any byte is verified.
- The secret is the endpoint's, `whsk_` included, answered once by `mountaya.admin.webhooks.postOrganizationWebhookEndpoint`. Keep it on the server, in `MOUNTAYA_WEBHOOK_SECRET`.
- Answer `200` within 10 seconds, before any slow work: queue the event and act on it afterwards.
- In Swift the refusal case lives in the core (`MountayaClient`) while the function lives in `MountayaAdmin`; in the Kotlin and Dart SDKs the refusal type sits in another unit.

## Handle an event

`WebhookEvent` has a case for each event type, so a `switch` reads what each one carries:

```swift
import MountayaAdmin
import MountayaClient

func handle(_ event: WebhookEvent) {
  switch event {
  case .organizationMemberUpdated(let updated):
    // The membership as it is now, and the role it held before the change.
    let before = updated.data.previous_attributes?.role?.rawValue ?? ""
    print("role", before, "->", updated.data.object.role.rawValue)
  case .collectionDeleted(let deleted):
    print("collection \(deleted.data.object.id) deleted")
  default:
    break
  }
}
```

An event can arrive more than once and in any order. Act on each `id` once.

- Every member of the envelope is read off the event whatever its case: `id`, `type`, `created_at` (a `Date`), `task`, `actor`, and on each payload `organization_id`, `api_version`, `related_object`, `request`.
- A payload's `data.object` is the resource as it is now; `data.previous_attributes` holds the fields its change moved, each `nil` where it did not move, and is `Never` for a type whose change moves none.
- Case names are the event type in lowerCamelCase: `itinerary.published` is `.itineraryPublished`, `organization.member.updated` is `.organizationMemberUpdated`, `collection.itinerary.moved` is `.collectionItineraryMoved`.
- The event catalogue is one page per resource, such as [itinerary events](https://docs.mountaya.com/en/webhooks/events/itinerary.md), each type with what it carries.

## Ignore unknown events

An event type newer than your build arrives as `.unknown`, with the raw envelope:

```swift
import MountayaAdmin

func handleAny(_ event: WebhookEvent) {
  if case .unknown(let envelope) = event {
    print("not handled yet:", envelope.type.rawValue)
    return
  }
  print("handled", event.id)
}
```

Answer it `200` like any other, so Mountaya does not send it again.

- `.unknown(AdminSchema.WebhookEvent)` holds the contract's envelope, the shape `mountaya.admin.webhooks.getOrganizationWebhookEvents` lists. It covers both a type a newer contract added and a payload this build's types cannot read.
- `WebhookEvent` is non-frozen, so a `switch` over it outside the SDK needs `default` or `@unknown default`.
- Every enum of the contract is open: an unknown `AdminSchema.WebhookEventType` decodes as itself.

## Rotate the secret

Rotate a secret in the Mountaya app, under **Organization → Webhooks**. For up to 7 days both secrets sign, and either one verifies, so deploy the new secret to your server before the overlap ends.

- During the overlap every delivery carries one `v1` per secret in its header, in no promised order; `constructWebhookEvent` accepts the delivery when any `v1` matches the secret you pass. No code change is needed: switch the value of `MOUNTAYA_WEBHOOK_SECRET`.
- A rotation with no overlap stops every earlier secret at once: use it when a secret leaked.
- No API operation rotates or reveals a secret. See [rotation](https://docs.mountaya.com/en/webhooks/signatures.md#rotation).

## Test your receiver

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

```swift
import Foundation
import MountayaAdmin
import MountayaClient
import Testing

// signature-vectors.json, downloaded from the signatures page.
struct SignatureVectors: Decodable {
  struct Case: Decodable {
    struct Expect: Decodable { let valid: Bool }
    let name: String
    let secret: String
    let now: TimeInterval
    let header: String
    let body: String
    let expect: Expect
  }
  let cases: [Case]
}

@Test func verifiesThePublishedVectors() throws {
  let file = URL(fileURLWithPath: "signature-vectors.json")
  let vectors = try JSONDecoder().decode(SignatureVectors.self, from: Data(contentsOf: file))
  for vector in vectors.cases {
    var verifies = true
    do {
      _ = try constructWebhookEvent(
        rawBody: vector.body, signatureHeader: vector.header, secret: vector.secret,
        now: Date(timeIntervalSince1970: vector.now))
    } catch MountayaError.webhookSignature {
      verifies = false
    }
    #expect(verifies == vector.expect.valid, "\(vector.name)")
  }
}
```

To try a real delivery, send your endpoint a test event from **Organization → Webhooks**, or with `postOrganizationWebhookDelivery`.

- `now:` is the clock a delivery is judged by; left out, it is the platform's. A test pins it to check the tolerance both ways.
- A test delivery through the API: `mountaya.admin.webhooks.postOrganizationWebhookDelivery(organization_id:body: .init(webhook_endpoint_id:) { $0.test = .init(type: "organization.member.updated") })`. See [testing webhooks](https://docs.mountaya.com/en/webhooks/testing.md).
- The vectors file (`/schemas/v0.9.0/openapi/api/webhooks/signature-vectors.json`) holds `cases`, each with `name`, `secret`, `now` (Unix seconds), `header`, `body` and `expect.valid`; the invalid cases are `tampered-body` (reason `.signature`) and `outside-tolerance` (`.timestamp`). Every case's body is a real event, so a verified case also decodes.

## Next steps

- [Itinerary events](https://docs.mountaya.com/en/webhooks/events/itinerary.md): What each itinerary event carries.
- [Manage an organization](https://docs.mountaya.com/en/sdks/swift/admin.md): Create and list webhook endpoints.
