Skip to content

Webhooks ​

Webhooks tell other systems when something happens in your API, such as an order being created, instead of them asking over and over. Fusion Stack signs every delivery, queues and retries it, and sends it in the API version each endpoint is pinned to, so a breaking change never reaches a receiver until it upgrades.

Events ​

An event is a class with a type and the resource it is about. Rust has no event classes: an event is webhooks::Event::new with its type and the resource's document from ApiQuery::document.

php
use FusionStack\Laravel\Webhooks\WebhookEvent;

/** Sent when an order is cancelled. */
final class OrderCancelled extends WebhookEvent
{
    public string $type = 'order.cancelled';

    // Related resources to add to `included`.
    public array $include = ['customer'];

    public function __construct(public Order $order) {}

    public function resource(): JsonApiResource
    {
        return new OrderResource($this->order);
    }
}
rust
use fusion_stack::webhooks::Event;

/// Sent when an order is cancelled.
async fn order_cancelled(request: &Request, order: i64) -> laravel::Result<Event> {
    // Related resources to add to `included`.
    let document = orders().document(request, order, &["customer"]).await?;
    Ok(Event::new("order.cancelled", document))
}

Dispatch it where the thing happens:

php
$order->update(['status' => 'cancelled']);
OrderCancelled::dispatch($order);
rust
db::table("orders")
    .filter(col("id").eq(order.id))
    .update(values! { status: "cancelled", updated_at: laravel::now().timestamp() })
    .await?;
order_cancelled(&request, order.id).await?.dispatch().await?;

Each endpoint subscribed to order.cancelled gets a JSON:API document of the resource, wrapped in the event:

json
{
  "id": "evt_01m8rd2a7d3k5yq9w0c8h6v4tf",
  "type": "order.cancelled",
  "created_at": "2026-12-01T09:05:12+00:00",
  "api_version": "2026-11-30.atlas",
  "data": {
    "id": "16",
    "type": "orders",
    "attributes": {
      "reference": "ORD-AUBHDUBY",
      "status": "cancelled"
    },
    "relationships": {
      "customer": {
        "data": {
          "id": "1",
          "type": "customers"
        }
      }
    }
  },
  "included": [
    {
      "id": "1",
      "type": "customers",
      "attributes": {
        "full_name": "Katelynn Connelly"
      }
    }
  ]
}

The payload is built once, when the event is dispatched, in the latest version's shape. When versioning is on, each endpoint gets it through its version's version changes, the same ones API responses go through, with the version in api_version.

Who gets an event ​

By default an event goes to every endpoint that subscribes to it. When endpoints belong to your customers, such as teams, return the owner from owner() so each team only gets its own events. In Rust, name the owner's type and ID with Event::owner:

php
public function owner(): ?Model
{
    return $this->order->team;
}
rust
// The owner type and ID its endpoints are stored with.
Event::new("order.cancelled", document).owner("teams", order.team_id)

Endpoints ​

Register an endpoint from the command line:

sh
php artisan api:webhook:create https://example.com/hooks --event="order.*" --description="Fulfilment"
sh
laravel api:webhook:create https://example.com/hooks --event "order.*" --description "Fulfilment"
text
   INFO  Registered webhook endpoint 1. Use this secret to verify its signatures:

whsec_…
  Events ........................................................... order.*

Or in code, such as from a settings page. Rust's webhooks::register takes no owner, so set the owner columns on the new endpoint yourself:

php
$endpoint = WebhookEndpoint::register('https://example.com/hooks', ['order.*'], attributes: [
    'owner_id' => $team->id,
    'owner_type' => Team::class,
]);

$endpoint->secret;          // show it once, to the receiver
$endpoint->rotateSecret();  // after a leak; the receiver must switch to the new one
rust
use fusion_stack::webhooks;

// Pinned to the latest version; the third argument names another.
let endpoint = webhooks::register("https://example.com/hooks", &["order.*"], None, None).await?;
db::table("webhook_endpoints")
    .filter(col("id").eq(endpoint))
    .update(values! { owner_id: team.id, owner_type: "teams" })
    .await?;

webhooks::secret(endpoint).await?;         // show it once, to the receiver
webhooks::rotate_secret(endpoint).await?;  // after a leak; the receiver must switch to the new one
  • --event takes patterns: order.*, or * for everything, which is the default.
  • When versioning is on, an endpoint is pinned to the latest version, or the one --pin gives.

Delivery and retries ​

Deliveries are queued on webhooks.connection and webhooks.queue (Config::webhook_queue in Rust), so run a worker: php artisan queue:work, or laravel queue:work in Rust. Each one is a POST with these headers:

http
Content-Type: application/json
Webhook-Id: evt_01m8rd2a7d3k5yq9w0c8h6v4tf
Webhook-Signature: t=1796115912,v1=5f2c…
User-Agent: Fusion Stack Webhooks

A 2xx response within webhooks.timeout seconds (10) counts as delivered. Anything else is retried after each delay in webhooks.backoff (Rust sets both, and disable_after, with Config::webhook_delivery); the default makes 8 attempts over about 23 hours. Each attempt is recorded in webhook_deliveries, with its status, response code, time taken and error, for debugging.

After webhooks.disable_after deliveries in a row fail (5), the endpoint is disabled and WebhookEndpointDisabled is dispatched, so you can tell its owner. Rust has no such event: it only marks the endpoint inactive, with disabled_at set. $endpoint->enable(), or webhooks::enable(endpoint) in Rust, turns it back on.

The sync queue cannot delay jobs, so with it each delivery is tried only once.

Where deliveries may go ​

An endpoint's URL often comes from a user, so a delivery must not reach what only your server can, such as localhost, a private network or a cloud metadata service:

  • A delivery is only sent to an address on the public internet. A URL whose host is, or resolves to, any other address fails with The endpoint's host [...] is not on the public internet, so the webhook was not sent., and counts as a failed delivery.
  • The request connects only to the addresses that were checked, so a second DNS answer cannot move it.
  • Redirects are not followed: a 3xx response is a failed delivery.

To deliver to localhost in development, or to your own internal services, turn on webhooks.allow_private_addresses (Config::webhook_private_addresses(true) in Rust). Redirects stay off.

Http::fake() answers before the check in PHP, so tests can use any URL. In Rust, client::fake() answers before a host name is checked, but a URL with a private IP address, such as http://127.0.0.1/hooks, is refused even when faked.

Receiving webhooks ​

Receivers should check the signature, so they know a request came from you and was not changed. It is an HMAC-SHA256 of <timestamp>.<body> with the endpoint's secret. Check it against the raw body, exactly as received: parsing and re-encoding the JSON changes it.

php
use FusionStack\Laravel\Webhooks\Signer;

if (! Signer::verify($request->getContent(), $request->header('Webhook-Signature'), $secret)) {
    abort(400);
}
rust
use fusion_stack::webhooks::Signer;

request.load_input().await?;
let body = request
    .content()
    .map(|bytes| String::from_utf8_lossy(bytes).into_owned())
    .unwrap_or_default();
let now = laravel::now().timestamp().as_second();
// 300: how many seconds old a signature may be.
if !Signer::verify(&body, request.header(Signer::HEADER), &secret, 300, now) {
    return Ok(Response::new(StatusCode::BAD_REQUEST));
}
ts
import { verifyWebhook } from '@fusion-stack/client';

const valid = await verifyWebhook(await request.text(), request.headers.get('Webhook-Signature'), secret);

All three reject signatures more than five minutes old, so a captured request cannot be replayed later. A retry can deliver an event twice, so use Webhook-Id to skip events you have already handled.

Released under the MIT License.