Skip to content

Webhooks

15 min read

Ferry sends outbound webhooks to partner receiving endpoints whenever business events occur across the platform. Every request carries a Standard Webhooks HMAC-SHA256 signature, a unique delivery identifier, and a timestamp; deliveries follow at-least-once semantics and retry automatically on transient receiver errors.

Webhooks notify your system that a resource just changed. Because deliveries can arrive late, repeat, or drop after prolonged outages, the foundational architectural rule remains: use webhooks as signals, and query the API as the source of truth.

Three operational properties shape your receiver design:

  1. Signed when enabled, verified by you: Ferry signs every outbound request once your organization enables a signing secret; if your receiver skips signature verification, anyone who learns your URL can still post forged payloads.
  2. At-least-once, unordered delivery: You may receive the same event more than once, and newer events can arrive ahead of older ones.
  3. Hard 2-second response deadline: Your endpoint must acknowledge within 2 seconds; slower responses count as failures and schedule retries.

If you use TypeScript or JavaScript, the official SDK ships parseWebhook to type payloads by event code and safeEqual to compare URL tokens in constant time.

RequirementWhyWhere to read
API key with organization settings authorityNeeded if registering webhook URLs via APIAuthentication
Public HTTPS endpoint on port 443/8443 answering under 2sFerry blocks private networks and non-standard ports”Receiving URL rules” below
Internal asynchronous queue on your sideReturn 2xx immediately and process business logic later”Safe handling pattern” below
Secret store and Standard Webhooks libraryVerify signatures against the exact raw body bytes”Verifying signatures” below
Scheduled reconciliation jobBackfills events dropped after exhausting all 4 attempts”Safe handling pattern” below
Target event listSubscribe to events actively emitted in production”Event catalog” below

The diagram below traces the delivery lifecycle of an outbound event, including the retry queue:

flowchart TB
A["Business event inside Ferry"] --> B["Dispatcher builds body and webhook-id"]
B --> C["Sign payload if org signing secret enabled"]
C --> D["Attempt 1 from API container, 2s timeout"]
D --> E{"Receiver returns 2xx"}
E -->|Yes| OK["Delivery complete"]
E -->|"Network error, timeout, 408, 429, 5xx"| Q["Enqueue on worker delivery queue"]
E -->|"Other 4xx or blocked destination"| X["Discard, log, no retry"]
Q --> R["Retry at 30s, 5m, 30m<br/>re-signed, same webhook-id"]
R -->|2xx| OK
R -->|"4 attempts exhausted"| F["Log final delivery failure<br/>partner reconciles via API"]

The diagram below shows the safe ingestion pattern on the partner side:

sequenceDiagram
autonumber
participant P as "Your system"
participant Q as "Internal queue"
participant F as "Ferry API"
F--)P: "POST with webhook-id, webhook-timestamp, webhook-signature"
P->>P: "Verify signature on raw body and check timestamp"
P->>Q: "Enqueue event, defer business processing"
P-->>F: "Return 2xx in under 2 seconds"
Q->>P: "Worker dequeues event"
P->>P: "Deduplicate by webhook-id"
P->>F: "Fetch authoritative resource via API"
F-->>P: "Current authoritative state"
P->>P: "Update local state from API response"
alt No events received within expected window
P->>P: "Scheduled reconciliation job triggers"
P->>F: "Query recently updated resources"
F-->>P: "Authoritative resource list"
P->>P: "Backfill missed updates"
end
HeaderValuePurpose
webhook-idmsg_<ulid>, generated once per event + endpoint and kept identical across all retriesIdempotent deduplication
webhook-timestampUnix seconds when signed (refreshed on each attempt)Replay protection; accept ±5 minutes tolerance
webhook-signaturev1,<base64(HMAC-SHA256(secret, "id.timestamp.body"))>; contains two space-separated signatures during rotation graceAuthenticity and integrity verification
x-event-typeEvent code, such as booking.createdInternal handler routing
user-agentFerry-Webhooks/1Sender identification

The signed message string is ${webhook-id}.${webhook-timestamp}.${body}, where body is the exact raw UTF-8 byte sequence transmitted by Ferry. Re-serializing a parsed JSON object with JSON.stringify breaks signature verification whenever key order or whitespace differs — always verify against the unparsed raw body.

Signing secrets belong to the organization rather than individual webhook URLs. For partners, enabling, rotating, and disabling webhook signing secrets are performed exclusively via the Dashboard UI at Notification settings (inside the Webhook security card) by an organization administrator — there is no partner API endpoint for managing signing secrets:

  • Enable or rotate secret: When an administrator creates a secret for the first time or clicks Rotate secret with a grace window (none, 1h, 24h, or 7d), the Dashboard displays the whsec_... plaintext secret exactly once. Throughout the grace window, Ferry signs every delivery with both the current and previous secrets (two space-separated signatures in webhook-signature) so you can roll out the new secret without downtime.
  • Disable signing: An administrator disables signing in the Webhook security card; Ferry removes the secret and subsequent webhooks flow unsigned.
  • Inspect signing status: The Webhook security card on the Dashboard displays whether signing is active, when any previous secret expires, the outbound egress IPs, and the retry schedule (never re-displaying the secret value).

Zero-downtime rotation procedure:

  1. An administrator opens the Dashboard, selects Rotate secret with grace 24h (or 7d for slower deployments), and stores the new whsec_... secret in your secret manager.
  2. Configure your webhook verifier to accept both secrets: try the new secret first, falling back to the previous secret.
  3. Once deployment finishes and the grace window shown on the Dashboard expires, remove the old secret from your configuration.

Use the official Standard Webhooks library instead of rolling custom HMAC code. The library accepts Ferry’s whsec_... secret directly, strips the prefix, and performs constant-time comparison.

Example verification in Node.js / TypeScript:

Terminal window
npm install standardwebhooks
import { Webhook } from "standardwebhooks";
// rawBody must be the unparsed raw string
const wh = new Webhook(process.env.FERRY_WEBHOOK_SECRET!);
export function handleFerryWebhook(rawBody: string, headers: Record<string, string>) {
// throws if signature mismatches or timestamp drifts past 5 minutes
const event = wh.verify(rawBody, headers);
return event; // { type, timestamp, data }
}

Example verification in Python:

Terminal window
pip install standardwebhooks
from standardwebhooks import Webhook, WebhookVerificationError
wh = Webhook(os.environ["FERRY_WEBHOOK_SECRET"])
def handle(request):
try:
event = wh.verify(request.get_data(), {
"webhook-id": request.headers["webhook-id"],
"webhook-timestamp": request.headers["webhook-timestamp"],
"webhook-signature": request.headers["webhook-signature"],
})
except WebhookVerificationError:
return "", 400
enqueue(event)
return "", 204

Example verification in PHP:

Terminal window
composer require standard-webhooks/standard-webhooks
use StandardWebhooks\Webhook;
use StandardWebhooks\WebhookVerificationException;
$wh = new Webhook(getenv('FERRY_WEBHOOK_SECRET'));
try {
$event = $wh->verify($rawBody, [
'webhook-id' => $headers['webhook-id'],
'webhook-timestamp' => $headers['webhook-timestamp'],
'webhook-signature' => $headers['webhook-signature'],
]);
} catch (WebhookVerificationException $e) {
http_response_code(400);
exit;
}

Rules if implementing verification manually without the official library:

  • Compare digests using a constant-time equality function, never ==.
  • Accept the request if any signature in webhook-signature matches (two signatures appear during rotation grace).
  • Reject requests whose webhook-timestamp differs by more than ±5 minutes from your NTP-synchronized server clock.
  • Return HTTP 400 on invalid signatures; Ferry treats 400 as a permanent failure and does not retry.

Delivery, retry schedule, and response codes

Section titled “Delivery, retry schedule, and response codes”
ItemOperational realityYour responsibility
HTTP methodAlways POST to your configured URLAccept POST requests
Event type headerx-event-typeRoute payloads to domain handlers
SignaturePresent whenever your org enabled a signing secretVerify before enqueueing or processing
Timeout2,000 millisecondsEnqueue and return 2xx immediately
Delivery semanticsAt-least-once; duplicates occurDeduplicate by webhook-id
OrderingNot guaranteedNever rely on arrival order for state transitions
Retries3 retries after initial attempt (30s, 5m, 30m)Make handlers idempotent
Egress IPsPublished at GET /api/v1/webhooks/egress-ipsOptional firewall allowlist; signature remains primary

How Ferry classifies receiver responses:

Receiver responseFerry classificationBehavior
2xxSuccessDelivery complete, no further attempts
408, 429, 5xxTransient failureEnqueued for retry; if 429 includes Retry-After ≤ 30 minutes, honours that delay instead of the default step
Network error or >2s timeoutTransient failureEnqueued for retry
3xx or other 4xxPermanent failureDiscarded and logged without retry
Blocked destination (SSRF guard)Permanent failureDiscarded and logged

Return 2xx (200, 202, or 204) as fast as possible. If your server finishes work in 2.5 seconds, Ferry has already timed out at 2.0 seconds and scheduled a retry — making webhook-id deduplication mandatory.

Ferry validates destination URLs both when saving settings and immediately before each outbound connection:

  • Only https:// is accepted. http:// URLs are rejected (HTTP 422 on save) and blocked at dispatch.
  • Embedded URL credentials (https://user:pass@host) are rejected.
  • Allowed ports: default HTTPS (443) and 8443 only.
  • Private and internal address ranges are blocked: loopback, RFC1918 private networks (10/8, 172.16/12, 192.168/16), CGNAT (100.64/10), link-local 169.254/16 (including cloud metadata services), 0.0.0.0/8, multicast, ::1, fc00::/7, and fe80::/10. At dispatch time, Ferry resolves DNS and aborts if any resolved IP falls into a blocked range, connecting directly to the verified IP to defeat DNS rebinding.
  • Redirects (3xx) are never followed; configure the final destination URL directly.

Blocked destinations are never retried. Updating an existing webhook URL validates the new URL, while leaving an unchanged legacy URL untouched does not block saving other organization settings.

If your firewall restricts inbound traffic by source IP, query the unauthenticated public endpoint GET /api/v1/webhooks/egress-ips (cached for 1 hour), also shown inside the Webhook security card on the Dashboard.

  • The response lists IPv4/IPv6 egress addresses for both API containers (initial inline attempt) and worker containers (queued retry attempts).
  • Egress IPs may change during infrastructure migrations with at least 14 days advance notice; avoid hard-coding IPs without an update plan.
  • Signatures remain the primary authentication mechanism. IP allowlisting is a defense-in-depth layer, never a substitute for verifying webhook-signature.
StepWhat your system doesWhat Ferry doesSuccess signalCommon failure
1Expose a public HTTPS endpoint on port 443 or 8443—Test POST returns 2xxUsing http:// or custom port causes 422 on save
2Return 2xx immediately after pushing raw payload to queue—Latency stays well under 2 seconds under loadRunning database/API work synchronously times out
3Register URL and event triggers in organization settingsValidates URL and saves channel configReading settings shows configured webhookHesitating to save out of fear of overwriting other channels
4Admin enables signing secret on Dashboard and stores whsec_...Generates secret and shows it onceWebhook security card on Dashboard shows signing enabledClosing the modal before copying requires rotating again
5Verify signatures with Standard Webhooks on raw bodySigns every delivery with org secretValid signature and timestamp within ±5 minutesParsing JSON before verification breaks HMAC
6Trigger a real business action to verify end-to-end deliveryEmits event and retries transient errorsEvent received even after a simulated 500 retryAssuming subscription implies active emission without testing
7Deduplicate by webhook-id and query API for ground truthServes authoritative resource stateLocal database matches API responseWriting unverified webhook fields straight to DB
8Run scheduled reconciliation jobs—Catches drift when all 4 attempts failSkipping periodic reconciliation
9Alert on abnormal event silence—Alert fires when stream goes quiet unexpectedlyTreating prolonged silence as healthy

Webhooks do not maintain a partner-queryable delivery log or manual replay API. Every event ends in one of three outcomes: delivered on the initial attempt, delivered on one of the 3 retries, or dropped after the fourth attempt.

Authoritative state always lives on the underlying domain resource (booking, order, cancellation request, or disruption), queried via its Partner API endpoint.

Clicking Send test on the Dashboard dispatches a signed webhook.test event to that specific endpoint without retries, displaying the HTTP status code, latency, and any connection error immediately.

Webhook receiving URLs live under the integrations section of organization settings, configurable via two paths:

  • Dashboard UI: Open Notification settings to manage URLs, event triggers, and signing secrets visually.
  • Organization settings API: Update webhook URLs and event subscriptions programmatically using your organization’s API key.

Each webhook entry contains three fields:

  • Receiving URL: A valid public HTTPS URL accepting POST.
  • Event triggers: Event codes your organization wants to receive.
  • Filter condition (optional): A dynamic expression evaluated before sending.

Settings updates merge per integration channel without overwriting unrelated organization settings.

Event codes across the platform include:

  • Organization: organization.created, organization.updated, organization.disabled, organization.enabled, child-organization.created
  • Booking: booking.created, booking.updated, booking.issuedTicket, booking.issuedTicketError, booking.cancelOrder, booking.hold_payment, booking.canceled_payment
  • Order: order.created, order.updated, order.issuedTicket, order.childOrgIssuedTicket, order.childOrgIssuedTicketError, order.newManualIssueOrder, order.canceled, order.cancelTicket, order.forcedCanceled
  • Cancellation request: cancel_ticket_request.created, .child_org_created, .updated, .accepted, .rejected, .accepted_refunded, .refunded, .recalled, .release_ticket
  • Customer: customer.created, customer.updated, customer.deleted
  • Company: company.created, company.updated, company.deleted
  • Lead: lead.created, lead.updated, lead.deleted
  • User: user.created, user.updated, user.deleted, user.created-with-profile
  • API key: apiKey.created, apiKey.updated
  • Voyage: voyage.created, voyage.created.manually, voyage.updated, voyage.disabled, voyage.has-order-voyage-disabled
  • Voyage disruptions: disruption.created, disruption.updated, disruption.closed
  • Ticket watchlist: ticketWatchlist.targetReached
  • Invoice: invoice.created, invoice.updated, invoice.published, invoice.failed, invoice.orphanReconcileAlert

apiKey.deleted is no longer emitted: revoking a key emits apiKey.updated with status: "revoked". Payloads for apiKey.created and apiKey.updated contain only id, organization_id, note, status, scopes, expires_at, rotated_from, rotated_to, and revoked_at — never hashes, key hints, or IPs.

For electronic invoices, issued VAT invoices cannot be cancelled directly. When an invoice replacement occurs, Partner Webhooks emit invoice.created and invoice.published for the newly issued replacement invoice, alongside invoice.updated (with status REPLACED) for the replaced original invoice.

The dictionary of subscribable event names is broader than the set of active emitters. Always verify each subscribed event with a concrete test action before relying on it in production.

Within the organization group, only child-organization.created actively dispatches a webhook; organization.created, organization.updated, organization.disabled, and organization.enabled do not fire.

Receiving audience across the organization hierarchy

Section titled “Receiving audience across the organization hierarchy”
Event categoryReceiving organizations
Booking eventsThe organization owning the booking
Order ticketing eventsThe ordering organization, plus a separate event for each ancestor organization in the parent chain (with NET prices computed from each ancestor’s perspective)
Voyage disruption events (disruption.*)Every organization owning an affected booking plus ancestor organizations in their parent chains (each payload is scoped strictly to affected bookings within the recipient’s organization subtree, with no passenger PII)
Child organization createdThe direct parent organization, not the newly created child

Multi-tier agencies receive two distinct order ticketing events — one for their own bookings and one for sub-agency bookings — carrying different event codes and NET figures that must be routed to separate handlers.

Webhook payloads differ from API responses

Section titled “Webhook payloads differ from API responses”

Webhook payloads bypass the role-based serialization filter applied to standard API responses and may expose fields absent from REST responses.

  • Security: Treat webhook bodies as confidential; never log raw bodies containing PII or forward them to untrusted third parties.
  • Engineering: Build core business logic on documented Partner API fields rather than incidental fields appearing only in webhook payloads.

Optional filter conditions evaluate payloads prior to dispatch:

  • Supports 6 comparison operators: equal, not equal, greater than, greater than or equal, less than, less than or equal.
  • Strict type matching: string '1' never equals number 1.
  • Dot-path nested traversal (order.code).
  • Boolean combinators and, or, not (not evaluates only its first child branch).
  • Omitting a filter delivers every event matching the subscribed trigger.

Webhook filters support 6 operators whereas dynamic API filters support 13 — do not copy filter expressions verbatim between the two systems.

In the cancellation flow, invalid filter syntax can abort your organization’s entire cancellation webhook loop rather than skipping one event. Prefer receiving unfiltered events and filtering inside your own worker unless server-side filtering is strictly necessary.

  1. Verify signatures first: Read raw request bytes, verify via Standard Webhooks, and enforce ±5 minute timestamp tolerance.
  2. Acknowledge in under 2 seconds: Push the verified event onto an internal queue and return HTTP 2xx before running business logic.
  3. Deduplicate by webhook-id: Store processed webhook-id values (for a few days) and ignore duplicates; do not deduplicate solely by resource ID because subsequent updates carry distinct webhook-id values.
  4. Treat webhooks as signals: Extract the resource ID and call the Partner API for authoritative state.
  5. Run periodic reconciliation: Poll recently updated bookings, transactions, and disruptions (updated_since) to recover any event lost after 4 failed attempts.
  6. Alert on stream silence: Monitor for abnormally long gaps with zero inbound events.
SymptomCauseWhat to doShould you retry
Saving webhook URL returns 422http://, non-443/8443 port, URL credentials, or private IPUse a public https:// endpoint on port 443 or 8443Not applicable
Signature verification failsVerified parsed JSON instead of raw bytes, or wrong whsec_...Pass raw unparsed body bytes and exact secret to Standard WebhooksNot applicable
Signature fails right after secret rotationReceiver accepts only new secret while Ferry is still in graceAccept both new and previous secrets until grace endsNot applicable
No events arrive after subscribingEvent code has no active emitterTest with a real action; switch to an actively emitted eventNot applicable
Events lost during traffic spikesReceiver exceeded 2s timeout across all 4 attemptsEnqueue before responding; backfill via periodic reconciliationFerry retries up to 3 times automatically
Duplicate deliveries receivedAt-least-once delivery semanticsDeduplicate by webhook-id headerNot applicable
Out-of-order state updatesDelivery order is not guaranteedQuery the Partner API for current authoritative stateNot applicable
Receiving apiKey.updated instead of apiKey.deletedKey revocation emits apiKey.updated with status: revokedBranch on status rather than a removed event nameNot applicable
Receiving ticketing events for unfamiliar ordersAncestor delivery for a child agency’s orderSeparate handlers for own orders vs childOrgIssuedTicketNot applicable
Requests arriving from unexpected source IPsEgress IP changed or retry came from worker containerCheck GET /api/v1/webhooks/egress-ips and update firewallNot applicable

This guide maps to the Organizations and Public Webhooks groups on https://api.ferry.vn/docs:

Inspection goalGroup in API reference
Update organization settings (webhook URLs and triggers)Organizations
Read current organization settingsOrganizations
Enable, rotate, disable signing secrets and Send testDashboard UI only at Notification settings
Public outbound webhook egress IP listPublic Webhooks (/api/v1/webhooks/egress-ips, unauthenticated)
Voyage disruption event schemasDisruptions
Booking event schemasBookings
Order event schemasOrders
Cancellation request event schemasCancel Ticket Requests
Customer event schemasCustomers
PageWhen to read
Notification settingsConfigure webhooks and signing secrets on the Dashboard UI
Authentication with an API keyReview API key scopes, rate limits, and rotation
The booking flowUnderstand why API polling remains the final booking truth
Ticket issuance and order legsDistinguish own-order and child-agency ticketing events
Cancellation and refundsReview cancellation events and filter condition cautions
General conventionsReview shared data conventions and deduplication rules
QuestionStatus
Delivery history UI and manual replay buttonNot yet available; Dashboard provides Send test (unretried). Partners rely on periodic API reconciliation.
Per-endpoint signing secretsNot supported; signing secrets are scoped per organization.
Written SLA for egress IP change noticeCurrent operational policy provides at least 14 days notice; no formal contractual SLA yet.
Invoice events emitted without standalone partner invoice read APIPending product roadmap; invoice lookup metadata appears on issued orders and Dashboard.