Laravel webhooks: verify, deduplicate and queue them
Cache::add to drop duplicate deliveries and a queued job for the real work. With feature tests, and a script that checks the running app.By the HookWatcher team · Updated
What you'll build
The endpoint receives GitHub webhooks, but the pattern is the same for any provider that signs with HMAC-SHA256. In order, the Laravel handler:
- verifies
X-Hub-Signature-256over the raw body bytes, before anything parses them, and answers401if it doesn't match; - requires an
X-GitHub-DeliveryID and parses the JSON (400if either is missing or broken); - skips a delivery ID it has already processed with a
200, so GitHub records success and the event runs once; - answers
202straight away and does the work after the response, because GitHub gives up after 10 seconds.
| Request | Status | Body |
|---|---|---|
| Valid signature, new delivery | 202 | accepted |
| Same delivery ID again | 200 | duplicate |
| Missing or wrong signature, or body changed after signing | 401 | invalid signature |
| Valid signature, no delivery ID or not JSON | 400 | missing delivery id / invalid JSON |
Written for Laravel 13, which needs PHP 8.3 or later. The only version-specific line is the CSRF exception; the note in that section covers Laravel 11 and 12.
Set up the project
composer create-project laravel/laravel github-webhooks cd github-webhooks php artisan make:middleware VerifyGitHubSignature php artisan make:controller GitHubWebhookController --invokable php artisan make:job ProcessGitHubWebhook
Add the secret to .env and expose it through a config file. Read it with config() in code, never env(): after php artisan config:cache, Laravel stops loading .env during requests.
# .env GITHUB_WEBHOOK_SECRET="paste the secret from the GitHub webhook settings"
// config/services.php: add inside the returned array
'github' => [
'webhook_secret' => env('GITHUB_WEBHOOK_SECRET'),
],Verify the signature
A plain PHP class with no framework dependencies, so it's trivial to unit test. hash_equals is PHP's constant-time string comparison; an empty secret is refused so a missing config value can't accept forged requests.
<?php
namespace App\Support;
final class GitHubSignature
{
/** True when $header is "sha256=" + the hex HMAC-SHA256 of the raw body. */
public static function verify(string $payload, ?string $header, string $secret): bool
{
if ($secret === '' || $header === null || !str_starts_with($header, 'sha256=')) {
return false;
}
return hash_equals('sha256=' . hash_hmac('sha256', $payload, $secret), $header);
}
}<?php
namespace Tests\Unit;
use App\Support\GitHubSignature;
use PHPUnit\Framework\TestCase;
class GitHubSignatureTest extends TestCase
{
// GitHub's published test values (docs: Validating webhook deliveries).
private const SECRET = "It's a Secret to Everybody";
private const SIGNATURE = 'sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17';
public function test_accepts_githubs_test_signature(): void
{
$this->assertTrue(GitHubSignature::verify('Hello, World!', self::SIGNATURE, self::SECRET));
}
public function test_rejects_changes(): void
{
$this->assertFalse(GitHubSignature::verify('Hello, World?', self::SIGNATURE, self::SECRET));
$this->assertFalse(GitHubSignature::verify('Hello, World!', self::SIGNATURE, 'another secret'));
$this->assertFalse(GitHubSignature::verify('Hello, World!', substr(self::SIGNATURE, 0, -1), self::SECRET));
$this->assertFalse(GitHubSignature::verify('Hello, World!', null, self::SECRET));
}
}Middleware and route
$request->getContent() returns the raw body exactly as received. Don't verify $request->all() or json_encode($request->json()->all()): PHP re-encodes JSON differently (it escapes / as \/ by default, for one), so the bytes no longer match.
<?php
namespace App\Http\Middleware;
use App\Support\GitHubSignature;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class VerifyGitHubSignature
{
public function handle(Request $request, Closure $next): Response
{
$valid = GitHubSignature::verify(
$request->getContent(), // the raw body, byte for byte
$request->header('X-Hub-Signature-256'),
(string) config('services.github.webhook_secret'),
);
if (!$valid) {
return response('invalid signature', 401)->header('Content-Type', 'text/plain');
}
return $next($request);
}
}<?php
// routes/web.php
use App\Http\Controllers\GitHubWebhookController;
use App\Http\Middleware\VerifyGitHubSignature;
use Illuminate\Support\Facades\Route;
Route::post('/webhooks/github', GitHubWebhookController::class)
->middleware(VerifyGitHubSignature::class);Routes in web.php get CSRF protection, and GitHub can't send a token, so exclude the webhook path:
// bootstrap/app.php
->withMiddleware(function (Middleware $middleware): void {
// GitHub can't send a CSRF token; the signature check protects this route instead.
$middleware->preventRequestForgery(except: [
'webhooks/*',
]);
})Controller and job
Cache::add stores the key only if it doesn't exist and returns false otherwise. Laravel documents it as atomic, so two simultaneous redeliveries can't both be queued. The three-day TTL matches GitHub's redelivery window. Use a cache store every server shares (database or Redis, not array or file on several machines).
<?php
namespace App\Http\Controllers;
use App\Jobs\ProcessGitHubWebhook;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use JsonException;
use Symfony\Component\HttpFoundation\Response;
class GitHubWebhookController extends Controller
{
public function __invoke(Request $request): Response
{
$delivery = (string) $request->header('X-GitHub-Delivery', '');
if ($delivery === '') {
return response('missing delivery id', 400)->header('Content-Type', 'text/plain');
}
try {
$payload = json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException) {
return response('invalid JSON', 400)->header('Content-Type', 'text/plain');
}
// add() stores the key only if it's missing, atomically: a second delivery gets false.
if (!Cache::add("github-delivery:{$delivery}", true, now()->addDays(3))) {
return response('duplicate', 200)->header('Content-Type', 'text/plain');
}
ProcessGitHubWebhook::dispatch((string) $request->header('X-GitHub-Event'), $payload);
return response('accepted', 202)->header('Content-Type', 'text/plain');
}
}<?php
namespace App\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;
class ProcessGitHubWebhook implements ShouldQueue
{
use Queueable;
public function __construct(public string $event, public mixed $payload) {}
public function handle(): void
{
Log::info('GitHub webhook', [
'event' => $this->event,
'action' => $this->payload['action'] ?? null,
'repository' => $this->payload['repository']['full_name'] ?? null,
]);
}
}Dispatching puts the job on the queue and the request returns 202 immediately. A worker has to be running to process it: php artisan queue:work, or set QUEUE_CONNECTION=sync while developing to run jobs inline.
Feature tests
$this->call() takes the raw body as its last argument and sends it unchanged, which is what a signature test needs. (postJson() encodes an array for you, so you'd have to sign its encoding.) Headers go in the server array with an HTTP_ prefix. Queue::fake() checks the job is queued exactly once without running it.
<?php
namespace Tests\Feature;
use App\Jobs\ProcessGitHubWebhook;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;
class GitHubWebhookTest extends TestCase
{
private const SECRET = 'test-secret';
protected function setUp(): void
{
parent::setUp();
config(['services.github.webhook_secret' => self::SECRET]);
Queue::fake();
}
private function deliver(string $body, ?string $signature, string $delivery = 'd-1')
{
$server = ['CONTENT_TYPE' => 'application/json', 'HTTP_X_GITHUB_EVENT' => 'issues', 'HTTP_X_GITHUB_DELIVERY' => $delivery];
if ($signature !== null) {
$server['HTTP_X_HUB_SIGNATURE_256'] = $signature;
}
// call() sends $body as the raw request body, unchanged.
return $this->call('POST', '/webhooks/github', [], [], [], $server, $body);
}
private function sign(string $body): string
{
return 'sha256=' . hash_hmac('sha256', $body, self::SECRET);
}
public function test_valid_delivery_is_queued_once(): void
{
$body = '{"action":"opened"}';
$this->deliver($body, $this->sign($body))->assertStatus(202);
$this->deliver($body, $this->sign($body))->assertStatus(200);
Queue::assertPushed(ProcessGitHubWebhook::class, 1);
}
public function test_invalid_requests_are_rejected(): void
{
$this->deliver('{"action":"opened"}', $this->sign('{"action":"closed"}'), 'd-2')->assertStatus(401);
$this->deliver('{"action":"opened"}', null, 'd-3')->assertStatus(401);
$this->deliver('not json', $this->sign('not json'), 'd-4')->assertStatus(400);
Queue::assertNothingPushed();
}
}php artisan test # unit and feature tests
Run it and test it
php artisan serve # http://127.0.0.1:8000 php artisan queue:work # in another terminal, to run the jobs
In a second terminal, save this script as test-webhook.sh. It signs requests with openssl exactly like GitHub does and checks each status code against the table above. It's the same script for every tutorial in this series, so it also tells you whether a port to another framework behaves the same.
#!/usr/bin/env bash
# Sends five deliveries to a GitHub webhook handler and checks each status code.
# Usage: GITHUB_WEBHOOK_SECRET='...' ./test-webhook.sh http://localhost:3000/webhooks/github
set -u
URL="${1:?usage: test-webhook.sh URL}"
SECRET="${GITHUB_WEBHOOK_SECRET:?set GITHUB_WEBHOOK_SECRET}"
BODY='{"action":"opened","issue":{"number":1347,"title":"Found a bug"},"repository":{"full_name":"octocat/Hello-World"}}'
ID="test-$(date +%s)-$$"
FAILED=0
sign() { printf '%s' "$1" | openssl dgst -sha256 -hmac "$SECRET" | sed 's/^.*= //'; }
send() { # body, signature ("" = none), delivery ID
local args=(-s -o /dev/null -w '%{http_code}' -X POST "$URL"
-H 'Content-Type: application/json' -H 'X-GitHub-Event: issues' -H "X-GitHub-Delivery: $3")
[ -n "$2" ] && args+=(-H "X-Hub-Signature-256: sha256=$2")
curl "${args[@]}" --data-binary "$1"
}
check() { # name, status received, status expected
if [ "$2" = "$3" ]; then echo "ok $1 ($2)"; else echo "FAIL $1: expected $3, got $2"; FAILED=1; fi
}
SIG=$(sign "$BODY")
check "valid delivery" "$(send "$BODY" "$SIG" "$ID")" 202
check "same delivery again" "$(send "$BODY" "$SIG" "$ID")" 200
check "body changed after signing" "$(send "${BODY/1347/1348}" "$SIG" "$ID-b")" 401
check "no signature" "$(send "$BODY" "" "$ID-c")" 401
check "signed but not JSON" "$(send "not json" "$(sign "not json")" "$ID-d")" 400
exit $FAILEDchmod +x test-webhook.sh GITHUB_WEBHOOK_SECRET="It's a test secret" ./test-webhook.sh http://127.0.0.1:8000/webhooks/github
ok valid delivery (202) ok same delivery again (200) ok body changed after signing (401) ok no signature (401) ok signed but not JSON (400)
The server logs issues opened octocat/Hello-World once, after the first response. A FAIL line names the check that broke; the mistakes table below lists what usually causes each one.
Receive real GitHub deliveries on localhost
GitHub won't send webhooks to localhost. Give it a HookWatcher endpoint instead, and let hwcli deliver each capture to your server byte for byte:
- Create a free HookWatcher account (or sign in) and create an endpoint; hwcli works with the endpoints in your account. Its URL looks like
https://hookwatcher.com/<endpoint-id>. - In the repository on GitHub, open Settings → Webhooks → Add webhook. Use the endpoint URL as the payload URL,
application/jsonas the content type, and the same secret your server reads fromGITHUB_WEBHOOK_SECRET. - Run hwcli on your machine.
--include-sensitivematters here: without it, signature headers are left out of local deliveries and every request fails with401.
hwcli login hwcli listen <endpoint-id> --to http://127.0.0.1:8000/webhooks/github --include-sensitive
GitHub's ping arrives as soon as the webhook is saved, and your handler answers 202. To send a capture again, run hwcli replay <request-id>: it keeps the original X-GitHub-Delivery, so your handler should answer 200 duplicate. That's your deduplication tested with a real delivery. GitHub's signature has no timestamp, so replayed bytes still verify.
Common mistakes in Laravel webhook handlers
| Symptom | Cause | Fix |
|---|---|---|
| 419 Page Expired | CSRF protection on a web route | Exclude the path in bootstrap/app.php (above) or use an API route |
| Every request is 401 after deploying | env() called outside config files returns nothing once config is cached | Read config('services.github.webhook_secret') and run php artisan config:clear after changing .env |
| 401 although the secret is right | The signature is computed over $request->all() or re-encoded JSON | Verify $request->getContent() |
| Jobs never run | No queue worker, so jobs wait on the queue | Run php artisan queue:work (Supervisor in production) or use sync locally |
| Duplicates processed on several servers | A cache store that isn't shared (file, array) | Use the database or Redis cache store |
| 301 or 404 instead of your controller | Trailing slash or http → https redirects in front of the app | Use the exact final URL as the payload URL: a redirect isn't a successful delivery |
See the exact bytes your middleware must verify
$request->getContent() receives them.Frequently asked questions
Should I use a package for Laravel webhooks?
You can; packages add storage and retry tables. The code here is the core of what they do, and short enough to own. For Stripe, Laravel Cashier ships its own webhook controller with signature verification.
Why middleware instead of checking in the controller?
It keeps unauthenticated requests out of your application code entirely, and the same middleware protects any other route from the same provider.
How do I verify Stripe or Shopify webhooks in Laravel?
Replace GitHubSignature with the provider's scheme. Shopify sends a base64 HMAC-SHA256 of the body in X-Shopify-Hmac-Sha256; Stripe signs timestamp.body and needs a tolerance check (details). The signature generator produces test values for each.
Is an in-memory set of delivery IDs enough in production?
No. It's empty after a restart and separate in every process or server. Store processed IDs where all instances see them: a database table with a unique key on the delivery ID (insert, and treat a unique-constraint error as a duplicate) or Redis SET key value NX EX 259200. Three days covers GitHub's redelivery window.
Sources
- Laravel 13: CSRF protection (excluding URIs)
- Laravel 13: Middleware
- Laravel 13: Cache (atomic add)
- Laravel 13: Configuration (config caching)
- Laravel 13: Queues
- PHP: hash_equals
- GitHub Docs: Validating webhook deliveries
More on GitHub webhooks
Headers, form-encoded payloads and delivery errors: GitHub webhook testing.