Skip to content

Webhooks ​

Providers implement the HandlesWebhooks interface to receive inbound webhooks with signature verification, event routing, and deduplication.

The HandlesWebhooks interface ​

php
use Integrations\Contracts\HandlesWebhooks;

interface HandlesWebhooks
{
    public function handleWebhook(Integration $integration, Request $request): mixed;
    public function verifyWebhookSignature(Integration $integration, Request $request): bool;
    public function resolveWebhookEvent(Request $request): ?string;
    public function webhookHandlers(): array;
    public function webhookDeliveryId(Request $request): ?string;
}

Routes ​

Webhook routes are registered automatically:

RouteNamePurpose
GET|POST /integrations/{provider}/webhookintegrations.webhookGeneric provider webhook
GET|POST /integrations/{provider}/{id}/webhookintegrations.webhook.specificIntegration-specific webhook

Point your external service's webhook URL at:

https://yourapp.com/integrations/zendesk/webhook
https://yourapp.com/integrations/zendesk/42/webhook  # for a specific integration

Webhook routes have no middleware by default -- most providers can't handle CSRF or session auth.

Webhook lifecycle ​

When a webhook arrives:

  1. The provider is resolved from the URL
  2. Signature is verified via verifyWebhookSignature()
  3. The webhook is persisted to integration_webhooks
  4. A WebhookReceived event is dispatched
  5. A ProcessWebhook job is dispatched to the configured queue
  6. The job calls your handleWebhook() (or routed handler)
  7. The result is logged in IntegrationLog

Signature verification ​

php
class StripeProvider implements IntegrationProvider, HandlesWebhooks
{
    public function verifyWebhookSignature(Integration $integration, Request $request): bool
    {
        $secret = $integration->credentialsArray()['webhook_secret'];

        return hash_equals(
            hash_hmac('sha256', $request->getContent(), $secret),
            $request->header('Stripe-Signature', ''),
        );
    }
}

Event type routing ​

Providers can declare how to extract the event type from the payload and route to specific handlers:

php
class StripeProvider implements IntegrationProvider, HandlesWebhooks
{
    public function resolveWebhookEvent(Request $request): ?string
    {
        return $request->input('type'); // e.g. 'invoice.paid'
    }

    public function webhookHandlers(): array
    {
        return [
            'invoice.paid' => HandleInvoicePaid::class,
            'customer.created' => HandleCustomerCreated::class,
        ];
    }
}

Deduplication ​

Providers can declare a deduplication key to prevent processing the same webhook twice:

php
public function webhookDeliveryId(Request $request): ?string
{
    return $request->header('X-Webhook-Id');
}

When webhookDeliveryId() returns null, the controller computes a fallback delivery ID from the real HTTP method, raw query string and body:

  • For a POST with no query string, the ID is hash('xxh128', $body).
  • For any other delivery, the ID is "{METHOD}:" followed by hash('xxh128', $query."\n".$body). An absent query string is treated as an empty string.

The raw query string is used exactly as received. Deliveries with different query strings or HTTP methods have different fallback IDs, even when their bodies are identical.

The (integration_id, delivery_id) unique constraint detects duplicates. If the insert fails on that constraint, the controller returns {"status": "duplicate"}. It does not store another row or dispatch another processing job.

Queue processing ​

All webhooks are processed asynchronously via the ProcessWebhook job:

php
// config/integrations.php
'webhook' => [
    'queue' => 'webhooks',
],

After signature verification, the controller checks the combined byte length of the raw body and raw query string against webhook.max_payload_bytes (default 1,048,576 bytes). If the total exceeds the limit, it returns 413 with {"error": "Payload too large."} and stores nothing. This also applies to GET deliveries.

The controller also returns 413 with {"error": "Payload exceeds PHP input limits."} and stores nothing if PHP reports that the raw query string or form body exceeds max_input_vars (default 1000) or max_input_nesting_level (default 64). These limits are independent of the byte limit. A form with 1,001 short fields can exceed the default field limit while staying well below 1 MB.

The check uses PHP's own parser. Query fields and form fields are checked separately. PHP splits fields on any character in arg_separator.input. Empty pairs, such as && or a trailing &, do not count toward max_input_vars, but a pair with an empty name, such as =1, does. Exactly max_input_vars fields are accepted; one more is rejected.

The form check applies only to application/x-www-form-urlencoded bodies for POST, PUT, DELETE, PATCH and QUERY. A GET body is never parsed or rejected for exceeding these input limits. PHP may already have truncated a live POST's parsed input, so the controller checks the raw body used for signature verification.

PHP reports the nesting warning only with display_errors off, as in production. With display_errors on, PHP silently drops an over-nested field, so the controller does not reject it for that limit.

In a stock Laravel 11+ app, a query string over max_input_vars can cause a 500 before the controller runs. The global HandleCors middleware reads the full URL, and Symfony parses the query string during normalisation. The controller's query check covers apps where the request reaches it, such as apps without that middleware.

Replaying webhooks ​

Stored webhooks can be replayed by their webhook ID:

bash
php artisan integrations:replay-webhook {webhookId}

The command runs the handler synchronously. It uses IntegrationWebhook::toRequest() to rebuild a request to / with the stored HTTP method, raw query string, body and headers. Queued processing uses the same method. The rebuilt request contains only the stored headers; Symfony's default headers are not added.

The controller stores the real HTTP method with getRealMethod(), before any method override is applied. A method override header is stored with the other headers and is available to the rebuilt request. The raw query string is stored exactly as received, or as null when empty. For a GET delivery, $request->getMethod() returns GET and $request->query() contains the stored query fields.

If the stored Content-Type is application/x-www-form-urlencoded, toRequest() parses the body into input for POST, PUT, DELETE, PATCH and QUERY. The Content-Type match ignores case and parameters such as ; charset=UTF-8. For example, a POST body of type=invoice.paid makes $request->input('type') return invoice.paid. A GET body is never parsed into input or query fields. The raw body remains available through $request->getContent().

If a stored query string or form body exceeds PHP's input limits, toRequest() returns the fields PHP keeps instead of throwing an input-limit exception. PHP stops at max_input_vars and drops fields nested beyond max_input_nesting_level. When PHP reports a limit, the package logs a warning with the webhook ID. With display_errors on, PHP drops over-nested fields without a warning.

When PHP reports an input-limit warning while parsing the query string, toRequest() replaces the rebuilt request's server QUERY_STRING with the query fields PHP kept, re-encoded with RFC 3986. Calls to $request->getQueryString() and $request->fullUrl() then use those fields without raising an input-limit ErrorException.

Without a query parsing warning, the server QUERY_STRING keeps the stored raw string, even if PHP reports a limit for the form body. Symfony's getQueryString() always normalises the server query string: it parses it, sorts the keys and re-encodes with RFC 3986. fullUrl() uses that normalised query. The model's query attribute keeps the original raw string in all cases.

This can affect rows stored before the upgrade or accepted by a web server whose PHP limits are higher than the queue worker's. Keep both limits in step in the web server's and worker's php.ini files, usually PHP-FPM and CLI respectively. You cannot raise these per-directory settings with ini_set() at run time.

Both paths call resolveWebhookEvent() on the rebuilt request and use webhookHandlers() to select a handler. A mapped event calls its handler. An event with no matching entry in a non-empty handler map is ignored. Otherwise, the provider's handleWebhook() is called. Replay does not verify the signature again or change the stored webhook's status.

Deliveries stored before the method and query columns were added are rebuilt as POST requests with no query string. See the upgrade guide.

Recovering stranded webhooks ​

A webhook can be left with no job to process it:

  • A queue worker died while processing it. The webhook stays processing.
  • Its job was lost before a worker picked it up, for example when the queue store was flushed. The webhook stays pending.
  • Processing failed, for example because the handler threw an exception. The webhook is failed.

integrations:recover-webhooks dispatches a new job for each webhook that has been processing for longer than webhook.processing_timeout (default 30 minutes) or pending for longer than webhook.pending_timeout (default 1 hour):

bash
php artisan integrations:recover-webhooks

If the first job of a pending webhook is still queued, only one of the two jobs can claim the webhook, so the handler runs once. The command dispatches at most one extra job per webhook per webhook.pending_timeout, even when two runs of the command overlap.

Failed webhooks are not retried by default. A retry runs the handler again from the start, so raise webhook.max_attempts above 1 only if every handler is idempotent. With a higher value, the command moves a failed webhook back to pending and dispatches a job when both of these conditions are true:

  • The webhook has at least 1 attempt and fewer than max_attempts. A job increments attempts each time it claims the webhook. A webhook with 0 attempts, such as one that failed before 6.4, is never retried.
  • The backoff for the webhook's last attempt has elapsed since that attempt failed. The backoff after attempt N is entry N of webhook.retry_backoff. Past the end of the list, the last entry is used.

A failed webhook is retried on the first run of the command after its backoff has elapsed. Add the command to your scheduler:

php
Schedule::command('integrations:recover-webhooks')->everyFiveMinutes();

Configuration ​

php
// config/integrations.php
'webhook' => [
    'prefix' => 'integrations',
    'queue' => 'default',
    'max_payload_bytes' => 1_048_576,  // 1 MB for body + raw query string
    'processing_timeout' => 1800,      // 30 minutes
    'pending_timeout' => 3600,         // 1 hour
    'max_attempts' => 1,               // no retries
    'retry_backoff' => [60, 300, 1800, 7200, 21600],
    'middleware' => [],
],