Guide

How to receive webhooks in Laravel PHP receiver + reliable processing

A minimal Laravel endpoint is easy to add. Production reliability (verification, retries, idempotency, backpressure) is the hard part — and Hooque makes that part simple.

Prefer the “no framework” version? Read receive webhooks in PHP.

TL;DR

  • Treat “receive webhooks in Laravel (PHP)” as an ops problem, not just a route handler.
  • Verify the request before parsing/side effects (use a verifySignature(...) stub, then implement provider verification).
  • Return 2xx quickly; move work to a worker/queue to avoid timeouts and retries.
  • Assume retries and design idempotency (dedupe by event id + unique constraints).
  • Log + store raw payloads for replayable debugging.
  • If you need one workflow across many providers, centralize ingest + standardize consumption.

Want the standard-library version and shared pitfalls? Read receive webhooks in PHP .

Anti-patterns

  • Doing business logic inline in the Laravel (PHP) request handler.
  • Parsing/transforming the body before verification (breaks signing inputs).
  • Returning 2xx before authenticity is proven.
  • Skipping idempotency (retries become double side effects).

Need deeper implementation details? Start with Webhook API.

Why it's hard in production

Frameworks help you build endpoints. They don’t solve retries, replay attacks, or backpressure by default.

Verify authenticity + stop replays

Use a verifySignature(...) stub here, then implement real verification + replay defense for each provider.

Read the guide

Assume retries (duplicates are optional)

Treat every delivery as at-least-once and make side effects idempotent (DB constraints, dedupe keys).

Read the guide

Don’t do work in the request path

Ack fast, process async. Otherwise timeouts, deploys, and spikes turn into missed webhooks.

Read the guide

Debug with real payloads

Save the exact body + headers so you can replay deterministically after a fix.

Read the guide

Add monitoring + alerts early

Track delivered vs rejected, processing latency, queue depth, and error rates.

Read the guide

Iterate locally without losing events

Tunnels help, but durable capture + replay removes the “my laptop was asleep” problem.

Read the guide

Minimal receiver (Laravel)

Keep verification as a stub here, then implement provider-specific verification + replay protection in the webhook security guide . For the standard-library version and shared pitfalls, see receive webhooks in PHP .

<?php
// Controller method (minimal)
use Illuminate\\Http\\Request;

function verifySignature(array $headers, string $body): void {
}

function processData(string $body): void {
  // TODO: your business logic (DB writes, external API calls, etc.)
}

public function webhooks(Request $request) {
  $body = $request->getContent(); // raw string
  verifySignature($request->headers->all(), $body);
  // What happens if it fails or times out? Providers retry -> duplicates unless idempotent.
  processData($body);
  return response("ok", 200);
}

Hooque turns any webhook into a reliable queue.

Non-obvious scenario: you can’t expose a port

In real deployments, the hardest part is often “where does this endpoint run?” (NAT, corporate networks, locked-down environments, short-lived preview deployments). Hooque decouples inbound receiving from processing so your Laravel app doesn’t need to be the public receiver.

The easy path: receive with Hooque + consume forever

Receive once (durably), then process from a queue. Your Laravel app doesn’t have to be the public receiver.

  • Centralize provider-specific verification and reduce “raw body” pitfalls.
  • Buffer spikes and deployments so you don’t drop deliveries.
  • Use explicit Ack / Nack / Reject to control retries.
  • Replay from the UI after a fix (no guessing what payload was sent).

Want the generic patterns? Read Webhook API and migrate to queue-based processing.

Hooque REST polling loop (runs forever)

Poll the queue forever and handle each event outside the provider’s request path.

<?php
// PHP 8+ (cURL)
// Runs forever: poll /next, ack/nack/reject explicitly.

$nextUrl = getenv("HOOQUE_QUEUE_NEXT_URL") ?: "https://app.hooque.io/queues/<consumerId>/next";
$token = getenv("HOOQUE_TOKEN") ?: "hq_tok_replace_me";

while (true) {
  $msg = getNextMessage($nextUrl, $token);
  if ($msg === null) {
    sleep_ms(1000);
    continue;
  }

  try {
    processData($msg["payload"], $msg["meta"]);
    ack($msg, $token);
  } catch (Throwable $e) {
    nack($msg, $token, $e);
  }
}

function getNextMessage(string $url, string $token): ?array {
  try {
    [$status, $headersRaw, $body] = httpGet($url, $token);
    if ($status === 204) return null;
    if ($status >= 400) { error_log("next() failed: $status $body"); sleep_ms(2000); return null; }

    $meta = json_decode(headerValue($headersRaw, "X-Hooque-Meta") ?: "{}", true) ?: [];
    return ["payload" => $body, "meta" => $meta];
  } catch (Throwable $netErr) {
    error_log("Worker connection err: " . $netErr->getMessage());
    sleep_ms(2000);
    return null;
  }
}

function processData(string $payload, array $meta): void {
  // Example real-life task: run a script on webhook events.
  error_log("event: " . ($meta["messageId"] ?? $meta["deliveryId"] ?? "unknown"));
}

function ack(array $msg, string $token): void {
  if (isset($msg["meta"]["ackUrl"])) httpPost($msg["meta"]["ackUrl"], $token, null);
}

function nack(array $msg, string $token, Throwable $e): void {
  $errUrl = $msg["meta"]["nackUrl"] ?? $msg["meta"]["rejectUrl"] ?? null;
  if ($errUrl) httpPost($errUrl, $token, ["reason" => $e->getMessage()]);
}

function sleep_ms(int $ms): void { usleep($ms * 1000); }

function httpGet(string $url, string $token): array {
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $token"]);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HEADER, true);
  $raw = curl_exec($ch);
  if ($raw === false) {
    $err = curl_error($ch);
    curl_close($ch);
    throw new Exception("cURL error: $err");
  }
  $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  curl_close($ch);
  return [$status, substr($raw, 0, $headerSize), substr($raw, $headerSize)];
}

function httpPost(string $url, string $token, ?array $json): void {
  $ch = curl_init($url);
  $headers = ["Authorization: Bearer $token"];
  if ($json !== null) $headers[] = "Content-Type: application/json";
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_POST, true);
  if ($json !== null) curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json));
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  curl_exec($ch);
  curl_close($ch);
}

function headerValue(string $headersRaw, string $name): ?string {
  foreach (explode("\r\n", $headersRaw) as $line) {
    if (stripos($line, $name . ":") === 0) return trim(substr($line, strlen($name) + 1));
  }
  return null;
}

Hooque SSE stream consumer (runs forever)

Stream events in real time and reconnect forever on disconnects.

<?php
// PHP 8+ — SSE consumer (cURL)
// Runs forever: connect to /stream, handle "message" events, ack/nack/reject explicitly.
$streamUrl = getenv("HOOQUE_QUEUE_STREAM_URL") ?: "https://app.hooque.io/queues/<consumerId>/stream";
$token = getenv("HOOQUE_TOKEN") ?: "hq_tok_replace_me";

while (true) {
  getMessageStream($streamUrl, $token, function($msg) use ($token) {
    try {
      processData($msg["payload"] ?? "", $msg["meta"]);
      ack($msg, $token);
    } catch (Throwable $e) {
      nack($msg, $token, $e);
    }
  });

  error_log("Stream dropped, reconnecting...");
  sleep(2);
}

function getMessageStream(string $url, string $token, callable $onMessage): void {
  $event = null;
  $dataLines = [];
  $buffer = "";

  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $token", "Accept: text/event-stream"]);
  
  curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $chunk) use (&$buffer, &$event, &$dataLines, $onMessage) {
    $buffer .= $chunk;
    while (($pos = strpos($buffer, "\n")) !== false) {
      $line = rtrim(substr($buffer, 0, $pos), "\r");
      $buffer = substr($buffer, $pos + 1);

      if (str_starts_with($line, ":")) continue;
      if ($line === "") {
        if ($event === "message" && count($dataLines) > 0) {
          $msg = json_decode(implode("\n", $dataLines), true);
          if ($msg !== null) {
            $onMessage([
              "payload" => $msg["payload"] ?? "",
              "meta" => $msg["meta"] ?? []
            ]);
          }
        }
        $event = null;
        $dataLines = [];
        continue;
      }
      if (str_starts_with($line, "event:")) $event = trim(substr($line, 6));
      if (str_starts_with($line, "data:")) $dataLines[] = ltrim(substr($line, 5));
    }
    return strlen($chunk);
  });
  curl_setopt($ch, CURLOPT_TIMEOUT, 0);
  curl_exec($ch);
  curl_close($ch);
}

function processData(string $payload, array $meta): void {
  error_log("event: " . ($meta["messageId"] ?? $meta["deliveryId"] ?? "unknown"));
}

function ack(array $msg, string $token): void {
  if (isset($msg["meta"]["ackUrl"])) postUrl($msg["meta"]["ackUrl"], $token, null);
}

function nack(array $msg, string $token, Throwable $e): void {
  $errUrl = $msg["meta"]["nackUrl"] ?? $msg["meta"]["rejectUrl"] ?? null;
  if ($errUrl) postUrl($errUrl, $token, ["reason" => $e->getMessage()]);
}

function postUrl(string $url, string $token, ?array $json): void {
  $ch = curl_init($url);
  $headers = ["Authorization: Bearer $token"];
  if ($json !== null) $headers[] = "Content-Type: application/json";
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_POST, true);
  if ($json !== null) curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json));
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  curl_exec($ch);
  curl_close($ch);
}

FAQ

Answers tailored to Laravel, plus shared webhook production guidance.

How do I get the raw request body in Laravel?

General: Signature verification typically requires the raw body bytes (before JSON parsing). Ensure your middleware stack does not transform the body before verification.

How Hooque helps: With Hooque, provider delivery goes to a managed ingest endpoint. Your worker consumes from a queue using REST or SSE, so the “raw body vs parsed body” pitfall is mostly confined to ingest configuration.

What status code should I return for webhooks in Laravel (PHP)?

General: Usually return a fast 2xx after validating authenticity and basic schema. Timeouts and 5xx commonly trigger retries.

How Hooque helps: Hooque acknowledges ingest immediately and persists the payload. Your worker acks/nacks/rejects explicitly after processing.

Do I need signature verification in Laravel (PHP)?

General: Yes, unless the sender is fully trusted and on a private network. A public endpoint without verification is easy to forge and easy to replay.

How Hooque helps: Hooque can verify at ingest for supported providers or using generic strategies. Either way, your worker receives a normalized meta object and can stay focused on processing.

Why do I see duplicate webhook events in Laravel (PHP)?

General: Retries are normal: timeouts, transient network failures, and 5xx responses all produce duplicates. Design idempotency around event ids and side-effect boundaries.

How Hooque helps: Hooque makes delivery outcomes explicit (ack/nack/reject) and provides replay/inspection so you can fix issues without guessing what was received.

How do I test webhooks locally in Laravel (PHP)?

General: You can use a tunnel, but local dev still breaks on sleep, VPNs, clock skew, and signature-byte mismatches.

How Hooque helps: With Hooque you can avoid inbound locally: receive events into a durable queue and pull/stream to your laptop, then replay from the UI after changes.

Should I use REST polling or SSE streaming for webhook processing?

General: Use REST polling for simple batch workers and environments without long-lived connections. Use SSE for low-latency “process as it arrives” flows.

How Hooque helps: Hooque supports both: `GET /next` for polling and `GET /stream` for streaming. Both include meta with ready-to-call ack/nack/reject URLs.

Start processing webhooks reliably

Use Laravel for your app, and keep webhook processing as a simple run-forever consumer loop with explicit ack/nack/reject control.

No credit card required