- Developers
- Webhooks
Webhooks
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.
What this flow solves
Section titled “What this flow solves”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:
- 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.
- At-least-once, unordered delivery: You may receive the same event more than once, and newer events can arrive ahead of older ones.
- 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.
Before you start
Section titled “Before you start”| Requirement | Why | Where to read |
|---|---|---|
| API key with organization settings authority | Needed if registering webhook URLs via API | Authentication |
| Public HTTPS endpoint on port 443/8443 answering under 2s | Ferry blocks private networks and non-standard ports | ”Receiving URL rules” below |
| Internal asynchronous queue on your side | Return 2xx immediately and process business logic later | ”Safe handling pattern” below |
| Secret store and Standard Webhooks library | Verify signatures against the exact raw body bytes | ”Verifying signatures” below |
| Scheduled reconciliation job | Backfills events dropped after exhausting all 4 attempts | ”Safe handling pattern” below |
| Target event list | Subscribe to events actively emitted in production | ”Event catalog” below |
Flow diagram
Section titled “Flow diagram”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" endRequest headers
Section titled “Request headers”| Header | Value | Purpose |
|---|---|---|
webhook-id | msg_<ulid>, generated once per event + endpoint and kept identical across all retries | Idempotent deduplication |
webhook-timestamp | Unix seconds when signed (refreshed on each attempt) | Replay protection; accept ±5 minutes tolerance |
webhook-signature | v1,<base64(HMAC-SHA256(secret, "id.timestamp.body"))>; contains two space-separated signatures during rotation grace | Authenticity and integrity verification |
x-event-type | Event code, such as booking.created | Internal handler routing |
user-agent | Ferry-Webhooks/1 | Sender 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.
Creating and rotating signing secrets
Section titled “Creating and rotating signing secrets”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, or7d), the Dashboard displays thewhsec_...plaintext secret exactly once. Throughout the grace window, Ferry signs every delivery with both the current and previous secrets (two space-separated signatures inwebhook-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:
- An administrator opens the Dashboard, selects Rotate secret with grace
24h(or7dfor slower deployments), and stores the newwhsec_...secret in your secret manager. - Configure your webhook verifier to accept both secrets: try the new secret first, falling back to the previous secret.
- Once deployment finishes and the grace window shown on the Dashboard expires, remove the old secret from your configuration.
Verifying signatures
Section titled “Verifying signatures”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:
npm install standardwebhooksimport { Webhook } from "standardwebhooks";
// rawBody must be the unparsed raw stringconst 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:
pip install standardwebhooksfrom 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 "", 204Example verification in PHP:
composer require standard-webhooks/standard-webhooksuse 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-signaturematches (two signatures appear during rotation grace). - Reject requests whose
webhook-timestampdiffers 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”| Item | Operational reality | Your responsibility |
|---|---|---|
| HTTP method | Always POST to your configured URL | Accept POST requests |
| Event type header | x-event-type | Route payloads to domain handlers |
| Signature | Present whenever your org enabled a signing secret | Verify before enqueueing or processing |
| Timeout | 2,000 milliseconds | Enqueue and return 2xx immediately |
| Delivery semantics | At-least-once; duplicates occur | Deduplicate by webhook-id |
| Ordering | Not guaranteed | Never rely on arrival order for state transitions |
| Retries | 3 retries after initial attempt (30s, 5m, 30m) | Make handlers idempotent |
| Egress IPs | Published at GET /api/v1/webhooks/egress-ips | Optional firewall allowlist; signature remains primary |
How Ferry classifies receiver responses:
| Receiver response | Ferry classification | Behavior |
|---|---|---|
| 2xx | Success | Delivery complete, no further attempts |
| 408, 429, 5xx | Transient failure | Enqueued for retry; if 429 includes Retry-After ≤ 30 minutes, honours that delay instead of the default step |
| Network error or >2s timeout | Transient failure | Enqueued for retry |
| 3xx or other 4xx | Permanent failure | Discarded and logged without retry |
| Blocked destination (SSRF guard) | Permanent failure | Discarded 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.
Receiving URL rules
Section titled “Receiving URL rules”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) and8443only. - Private and internal address ranges are blocked: loopback, RFC1918 private networks (
10/8,172.16/12,192.168/16), CGNAT (100.64/10), link-local169.254/16(including cloud metadata services),0.0.0.0/8, multicast,::1,fc00::/7, andfe80::/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.
Outbound egress IPs
Section titled “Outbound egress IPs”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.
Implementation steps
Section titled “Implementation steps”| Step | What your system does | What Ferry does | Success signal | Common failure |
|---|---|---|---|---|
| 1 | Expose a public HTTPS endpoint on port 443 or 8443 | — | Test POST returns 2xx | Using http:// or custom port causes 422 on save |
| 2 | Return 2xx immediately after pushing raw payload to queue | — | Latency stays well under 2 seconds under load | Running database/API work synchronously times out |
| 3 | Register URL and event triggers in organization settings | Validates URL and saves channel config | Reading settings shows configured webhook | Hesitating to save out of fear of overwriting other channels |
| 4 | Admin enables signing secret on Dashboard and stores whsec_... | Generates secret and shows it once | Webhook security card on Dashboard shows signing enabled | Closing the modal before copying requires rotating again |
| 5 | Verify signatures with Standard Webhooks on raw body | Signs every delivery with org secret | Valid signature and timestamp within ±5 minutes | Parsing JSON before verification breaks HMAC |
| 6 | Trigger a real business action to verify end-to-end delivery | Emits event and retries transient errors | Event received even after a simulated 500 retry | Assuming subscription implies active emission without testing |
| 7 | Deduplicate by webhook-id and query API for ground truth | Serves authoritative resource state | Local database matches API response | Writing unverified webhook fields straight to DB |
| 8 | Run scheduled reconciliation jobs | — | Catches drift when all 4 attempts fail | Skipping periodic reconciliation |
| 9 | Alert on abnormal event silence | — | Alert fires when stream goes quiet unexpectedly | Treating prolonged silence as healthy |
Delivery state and test pings
Section titled “Delivery state and test pings”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.
Guarantees and limits
Section titled “Guarantees and limits”Where configuration lives
Section titled “Where configuration lives”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 catalog
Section titled “Event catalog”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.
Registerable does not mean it fires
Section titled “Registerable does not mean it fires”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 category | Receiving organizations |
|---|---|
| Booking events | The organization owning the booking |
| Order ticketing events | The 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 created | The 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.
Filter conditions and syntax risks
Section titled “Filter conditions and syntax risks”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 number1. - Dot-path nested traversal (
order.code). - Boolean combinators
and,or,not(notevaluates 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.
Safe handling pattern on the partner side
Section titled “Safe handling pattern on the partner side”- Verify signatures first: Read raw request bytes, verify via Standard Webhooks, and enforce ±5 minute timestamp tolerance.
- Acknowledge in under 2 seconds: Push the verified event onto an internal queue and return HTTP 2xx before running business logic.
- Deduplicate by
webhook-id: Store processedwebhook-idvalues (for a few days) and ignore duplicates; do not deduplicate solely by resource ID because subsequent updates carry distinctwebhook-idvalues. - Treat webhooks as signals: Extract the resource ID and call the Partner API for authoritative state.
- Run periodic reconciliation: Poll recently updated bookings, transactions, and disruptions (
updated_since) to recover any event lost after 4 failed attempts. - Alert on stream silence: Monitor for abnormally long gaps with zero inbound events.
Common failures and how to handle them
Section titled “Common failures and how to handle them”| Symptom | Cause | What to do | Should you retry |
|---|---|---|---|
| Saving webhook URL returns 422 | http://, non-443/8443 port, URL credentials, or private IP | Use a public https:// endpoint on port 443 or 8443 | Not applicable |
| Signature verification fails | Verified parsed JSON instead of raw bytes, or wrong whsec_... | Pass raw unparsed body bytes and exact secret to Standard Webhooks | Not applicable |
| Signature fails right after secret rotation | Receiver accepts only new secret while Ferry is still in grace | Accept both new and previous secrets until grace ends | Not applicable |
| No events arrive after subscribing | Event code has no active emitter | Test with a real action; switch to an actively emitted event | Not applicable |
| Events lost during traffic spikes | Receiver exceeded 2s timeout across all 4 attempts | Enqueue before responding; backfill via periodic reconciliation | Ferry retries up to 3 times automatically |
| Duplicate deliveries received | At-least-once delivery semantics | Deduplicate by webhook-id header | Not applicable |
| Out-of-order state updates | Delivery order is not guaranteed | Query the Partner API for current authoritative state | Not applicable |
Receiving apiKey.updated instead of apiKey.deleted | Key revocation emits apiKey.updated with status: revoked | Branch on status rather than a removed event name | Not applicable |
| Receiving ticketing events for unfamiliar orders | Ancestor delivery for a child agency’s order | Separate handlers for own orders vs childOrgIssuedTicket | Not applicable |
| Requests arriving from unexpected source IPs | Egress IP changed or retry came from worker container | Check GET /api/v1/webhooks/egress-ips and update firewall | Not applicable |
Where to look in Scalar
Section titled “Where to look in Scalar”This guide maps to the Organizations and Public Webhooks groups on https://api.ferry.vn/docs:
| Inspection goal | Group in API reference |
|---|---|
| Update organization settings (webhook URLs and triggers) | Organizations |
| Read current organization settings | Organizations |
| Enable, rotate, disable signing secrets and Send test | Dashboard UI only at Notification settings |
| Public outbound webhook egress IP list | Public Webhooks (/api/v1/webhooks/egress-ips, unauthenticated) |
| Voyage disruption event schemas | Disruptions |
| Booking event schemas | Bookings |
| Order event schemas | Orders |
| Cancellation request event schemas | Cancel Ticket Requests |
| Customer event schemas | Customers |
Read next
Section titled “Read next”| Page | When to read |
|---|---|
| Notification settings | Configure webhooks and signing secrets on the Dashboard UI |
| Authentication with an API key | Review API key scopes, rate limits, and rotation |
| The booking flow | Understand why API polling remains the final booking truth |
| Ticket issuance and order legs | Distinguish own-order and child-agency ticketing events |
| Cancellation and refunds | Review cancellation events and filter condition cautions |
| General conventions | Review shared data conventions and deduplication rules |
Open questions
Section titled “Open questions”| Question | Status |
|---|---|
| Delivery history UI and manual replay button | Not yet available; Dashboard provides Send test (unretried). Partners rely on periodic API reconciliation. |
| Per-endpoint signing secrets | Not supported; signing secrets are scoped per organization. |
| Written SLA for egress IP change notice | Current operational policy provides at least 14 days notice; no formal contractual SLA yet. |
| Invoice events emitted without standalone partner invoice read API | Pending product roadmap; invoice lookup metadata appears on issued orders and Dashboard. |