# Receive webhooks

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

Verify Mountaya webhook deliveries with constructWebhookEvent on a Dart server, switch over the typed events, and test your receiver.

Mountaya sends each event your [webhook endpoint](https://docs.mountaya.com/en/webhooks.md) subscribes to as a signed `POST`. Verify the signature, then act on the typed event.

## Verify a delivery

`constructWebhookEvent` checks the delivery's `Mountaya-Signature` against your endpoint's secret, then returns the event. Hand it the body exactly as it arrived:

```dart
import 'dart:io';
import 'dart:typed_data';

import 'package:mountaya_admin/mountaya_admin.dart';

final secret = Platform.environment['MOUNTAYA_WEBHOOK_SECRET'] ?? '';

// Call it with the body exactly as it arrived and its Mountaya-Signature header.
int receive(Uint8List body, String? signature) {
  final WebhookEvent event;
  try {
    event = constructWebhookEvent(body, signature, secret);
  } on WebhookSignatureException catch (refusal) {
    print(refusal.reason);
    return 400;
  }

  // Queue the event and answer at once. Act on each event.id once.
  print('${event.id} ${event.type}');
  return 200;
}
```

Your framework's route calls it, and answers with the status it returns. [Verify webhook signatures](https://docs.mountaya.com/en/webhooks/signatures.md) shows how the signature is computed.

- `constructWebhookEvent(Object rawBody, String? signatureHeader, String secret, {Duration tolerance = const Duration(seconds: 300), DateTime? now})`, from `package:mountaya_admin/mountaya_admin.dart`. It exists on the Dart VM only, behind the admin unit's conditional export, as `SecretCredential` is behind the client's: a Flutter build has no symbol for it, so the secret never ships in an app.
- Pass the body as it arrived, a `Uint8List`: the signature covers those bytes, and a body decoded and encoded again does not verify. A body read as a `String` is verified by its UTF-8 bytes.
- A refusal is `WebhookSignatureException`, whose `reason` is a `WebhookSignatureReason`: `missingHeader`, `malformedHeader`, `signature` (no `v1` of the header matches), `timestamp` (the signature verifies, and was made further from your clock than `tolerance`, either way). Answer it with a `400`. It is a `MountayaException`, so `on MountayaException` catches it beside every other failure. The class is declared in the client's error ladder and published from the admin barrel; in Swift and Kotlin it lives in another unit.
- A secret that does not open with `whsk_`, or a negative tolerance, is a `ConfigurationException` before the header is read. A body that is neither bytes (`Uint8List`, `List<int>`) nor a `String` is an `ArgumentError`.
- Answer with a `2xx` (the sample answers `200`) within 10 seconds, before any slow work: Mountaya retries a delivery that fails or times out ([delivery](https://docs.mountaya.com/en/webhooks/delivery.md)).
- With `dart:io`'s `HttpServer`, read the body as bytes (`await request.fold(BytesBuilder(), (bytes, chunk) => bytes..add(chunk))`), pass `request.headers.value('Mountaya-Signature')`, and set `request.response.statusCode` to what `receive` answers.

## Handle an event

Each event type is a class of its own, so a `switch` reads what each carries:

```dart
import 'package:mountaya_admin/mountaya_admin.dart';

// Called with each event constructWebhookEvent answered.
void handle(WebhookEvent event) {
  switch (event) {
    case OrganizationMemberUpdatedEvent(:final data):
      // The member's role now, and the one they held before.
      print('${data.object.role}, was ${data.previous_attributes?.role}');
    case CollectionDeletedEvent(:final data):
      print('Collection ${data.object.id} deleted');
    default:
      print('Not handled here: ${event.type}');
  }
}
```

Mountaya delivers an event at least once and in no set order. Keep what you act on keyed by `event.id`.

- Every class extends `WebhookEvent`, a top-level type each: `OrganizationMemberUpdatedEvent`, `ItineraryPublishedEvent`, `CollectionDeletedEvent`, `ZoneUpdatedEvent` and one per type of the [catalogue](https://docs.mountaya.com/en/webhooks.md#envelope). Each carries the envelope (`id`, `type`, `created_at`, `organization_id`, `task`, `actor`, `related_object`, `request`, `api_version`) and `data`, a `WebhookEventPayloadData<O, P>`.
- `data.object` is the object its type names; `data.previous_attributes` holds the fields the change moved, each `null` where it did not move, and `moved` names the fields that did, so a field that was `null` before reads apart from one that stayed. A type whose change moves nothing types it `Never`.
- `WebhookEvent` is not `sealed`, so a `switch` over it keeps a default and never has to name every type.
- `event.type` is a `WebhookEventType`, an open extension type over the type's text.

## Ignore unknown events

An event this build cannot type still arrives, as `UnknownWebhookEvent`. Answer it with a `2xx` like any other:

```dart
import 'package:mountaya_admin/mountaya_admin.dart';

// What a log line says of each delivery.
String describe(WebhookEvent event) => switch (event) {
  OrganizationMemberUpdatedEvent(:final data) => 'Member now ${data.object.role}',
  UnknownWebhookEvent() => 'A type this build does not know: ${event.type}',
  _ => 'Not handled here: ${event.type}',
};
```

- `UnknownWebhookEvent` arrives for a type a newer contract added, or one whose payload this build's types do not read. It holds the envelope as `mountaya.admin.webhooks.getOrganizationWebhookEvents` lists it, every envelope member included, so a receiver that reads a delivery its own way reads it there (`toJson()`).
- An endpoint is sent only the types its `enabled_events` names: a new type reaches it only through `*` or `<family>.*`.
- Upgrade the packages to type a new event: a release printed from a later contract declares its class.

## Rotate the secret

Rotate a secret in the Mountaya app, under **Organization → Webhooks**. Both secrets sign every delivery for up to 7 days, and either verifies, so deploy the new one before the overlap ends.

- During the overlap of up to 7 days, every delivery carries one `v1` per secret, the new and the previous, in no promised order, and `constructWebhookEvent` verifies with either secret on its own: a receiver holds one secret, the old one until the new one is deployed.
- Rotation is done in the Mountaya app (**Organization → Webhooks**, the endpoint's menu, **Rotate secret**) by an owner or admin; no API operation reveals or rotates a secret. A rotation with no overlap stops every earlier secret at once: use it when a secret leaked. See [rotation](https://docs.mountaya.com/en/webhooks/signatures.md#rotation).

## Test your receiver

Check your code against the published [test vectors](https://docs.mountaya.com/en/webhooks/signatures.md#test-vectors). `now:` pins the clock each case is judged by:

```dart
import 'dart:convert';
import 'dart:io';

import 'package:mountaya_admin/mountaya_admin.dart';
import 'package:test/test.dart';

void main() {
  // Downloaded from the test vectors link on Verify webhook signatures.
  final vectors = jsonDecode(
    File('test/signature-vectors.json').readAsStringSync(),
  );
  final cases = switch (vectors) {
    {'cases': final List<Object?> cases} => cases,
    _ => const <Object?>[],
  };
  for (final entry in cases) {
    if (entry case {
      'name': final String name,
      'secret': final String secret,
      'now': final int now,
      'header': final String header,
      'body': final String body,
      'expect': {'valid': final bool valid},
    }) {
      test(name, () {
        var verified = true;
        try {
          constructWebhookEvent(
            body,
            header,
            secret,
            now: DateTime.fromMillisecondsSinceEpoch(now * 1000, isUtc: true),
          );
        } on WebhookSignatureException {
          verified = false;
        }
        expect(verified, valid);
      });
    }
  }
}
```

To send a real test event to your endpoint, call `mountaya.admin.webhooks.postOrganizationWebhookDelivery` with `test:`, or use **Send test event** in the Mountaya app.

- `now:` states the time a delivery is judged by; left out, it is `package:clock`'s `clock`, so a test under `fake_async` or `withClock` moves it too.
- A test event: `mountaya.admin.webhooks.postOrganizationWebhookDelivery(organization_id:, body: admin_schema.WebhookDeliveryCreateParams(webhook_endpoint_id:, test: admin_schema.WebhookDeliveryTestParams(type:)))`. It answers `202` with the delivery's id, carries the type's example payload with an id of its own, is signed like any delivery, sent once and never retried. Owner or admin only; 30 a minute per user. See [test your endpoint](https://docs.mountaya.com/en/webhooks/testing.md).
- There is no test mode: test with an organization of its own, made for development.

## Next steps

- [Webhooks](https://docs.mountaya.com/en/webhooks.md): The envelope, the guarantees and every event type.
- [Manage an organization](https://docs.mountaya.com/en/sdks/dart/admin.md): Create the endpoint that receives them.
