A Laravel payment webhook should be idempotent: receiving the same event twice must not charge, credit, fulfil or notify twice. The reliable starting point is a database table with a unique constraint on the provider's event ID. Insert that ID and update the order in the **same database transaction**. A unique index protects concurrent requests in a way that a simple `exists()` check cannot.
A second safeguard is equally important: treat changing an order from `pending` to `paid` as a one-time business transition. Different webhook event IDs can sometimes describe the same payment or order, so event deduplication alone is not enough.
Why payment providers deliver duplicate webhooks
Payment providers usually deliver webhooks at least once, not exactly once. A provider may retry when your endpoint times out, returns an error or fails to acknowledge a successful delivery. Two copies can arrive close together and be handled by separate PHP workers.
In a simple example, both requests read the same order and set its status to `paid`. That particular update may produce the same final status, but any additional action—sending an email, issuing a licence, posting a ledger entry or dispatching goods—could run twice.
The solution must be safe under concurrency, not merely safe when requests arrive one after another.
Why checking the event ID first is insufficient
This pattern has a race condition:
if (!DB::table('webhook_events')->where('event_id', $id)->exists()) {
// Process the payment.
DB::table('webhook_events')->insert(['event_id' => $id]);
}Two requests can both observe that the ID does not exist. They may then process the payment before either inserts the event record. Moving the check earlier does not remove that gap.
Instead, let MySQL enforce uniqueness. A unique index on `(provider, event_id)` allows only one request to insert that pair successfully. The transaction must include the event insert **and** the resulting order update. If processing fails, the transaction rolls back and a later delivery can retry.
1. Create the event and outbox tables
The example assumes Laravel 8 or later with MySQL/InnoDB and an existing `orders` table. For this sample, each order has `id`, `status`, `payment_reference`, `amount_minor` and `currency` columns. Adapt those names to your actual order schema. Amounts use integer minor units rather than floating-point money values.
Create a migration:
php artisan make:migration create_webhook_events_and_outbox_messagesUse this migration body. Its outbox table records work that must happen after payment, without sending an email or making an external API request inside the database transaction.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateWebhookEventsAndOutboxMessages extends Migration
{
public function up(): void
{
Schema::create('webhook_events', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('provider', 32);
$table->string('event_id', 120);
$table->string('event_type', 100);
$table->unsignedBigInteger('order_id')->nullable();
$table->timestamp('processed_at')->nullable();
$table->timestamps();
$table->unique(['provider', 'event_id']);
});
Schema::create('outbox_messages', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('event_key', 160)->unique();
$table->string('event_type', 80);
$table->json('payload');
$table->timestamp('processed_at')->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('outbox_messages');
Schema::dropIfExists('webhook_events');
}
}Run the migration with `php artisan migrate` in the appropriate environment. Review migrations and take a backup before changing a production database.
The unique event key is scoped to a provider, because separate providers could issue identical-looking event IDs. A multi-account integration may also need to include the provider account identifier in its uniqueness rule.
2. Verify the webhook before trusting its contents
**Never mark an order as paid from an unverified HTTP request.** Validate the provider's signature against the raw request body before decoding or acting on the payload. The exact signing algorithm and headers depend on the payment provider.
For a self-contained illustration, assume a fictional provider named ExamplePay signs the raw JSON body with HMAC-SHA256 and sends the lowercase hexadecimal digest in `X-ExamplePay-Signature`. **Use this verifier only if your real provider documents exactly that contract.** Otherwise use its official SDK or documented signature-verification procedure, including any timestamp and replay-window requirements.
Add the secret to protected environment configuration:
EXAMPLEPAY_WEBHOOK_SECRET=replace-with-secret-from-providerAdd the service entry to `config/services.php`:
'examplepay' => [
'webhook_secret' => env('EXAMPLEPAY_WEBHOOK_SECRET'),
],This example does not rely on session authentication or a browser CSRF token. A provider must be able to POST directly to the webhook route; a valid provider signature authenticates the payload.
3. Complete Laravel webhook controller
Create `app/Http/Controllers/PaymentWebhookController.php`. This implementation uses Laravel's query builder, MySQL's duplicate-key error code and a transactional row lock. It intentionally handles only `payment.completed`; expand the state machine for refunds, disputes and other event types.
<?php
namespace App\Http\Controllers;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use JsonException;
use RuntimeException;
class DuplicateWebhookEvent extends RuntimeException {}
class PaymentWebhookController extends Controller
{
public function handle(Request $request)
{
$body = $request->getContent();
$secret = config('services.examplepay.webhook_secret');
$signature = $request->header('X-ExamplePay-Signature', '');
if (!is_string($secret) || $secret === '') {
throw new RuntimeException('Webhook secret not configured.');
}
$expected = hash_hmac('sha256', $body, $secret);
if (!is_string($signature) ||
!preg_match('/\A[a-f0-9]{64}\z/D', $signature) ||
!hash_equals($expected, $signature)) {
return response()->json(['error' => 'Invalid signature'], 401);
}
try {
$event = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
return response()->json(['error' => 'Invalid JSON'], 400);
}
if (!is_array($event)) {
return response()->json(['error' => 'Invalid event'], 400);
}
$eventId = $event['id'] ?? null;
$type = $event['type'] ?? null;
if (!is_string($eventId) || $eventId === '' ||
strlen($eventId) > 120 || !is_string($type)) {
return response()->json(['error' => 'Invalid event fields'], 400);
}
// This controller implements one supported event type.
if ($type !== 'payment.completed') {
return response()->json(['received' => true]);
}
$data = $event['data'] ?? null;
if (!is_array($data)) {
return response()->json(['error' => 'Missing payment data'], 400);
}
$orderId = $data['order_id'] ?? null;
$paymentRef = $data['payment_reference'] ?? null;
$amountMinor = $data['amount_minor'] ?? null;
$currency = $data['currency'] ?? null;
if (!is_int($orderId) || $orderId < 1 ||
!is_string($paymentRef) || $paymentRef === '' ||
!is_int($amountMinor) || $amountMinor < 0 ||
!is_string($currency) ||
!preg_match('/\A[A-Z]{3}\z/D', $currency)) {
return response()->json(['error' => 'Invalid payment data'], 400);
}
try {
DB::transaction(function () use (
$eventId, $type, $orderId,
$paymentRef, $amountMinor, $currency
) {
try {
DB::table('webhook_events')->insert([
'provider' => 'examplepay',
'event_id' => $eventId,
'event_type' => $type,
'order_id' => $orderId,
'created_at' => now(),
'updated_at' => now(),
]);
} catch (QueryException $e) {
// MySQL duplicate key on the event table's unique pair.
if ((int) ($e->errorInfo[1] ?? 0) === 1062) {
throw new DuplicateWebhookEvent();
}
throw $e;
}
$order = DB::table('orders')
->where('id', $orderId)
->lockForUpdate()
->first();
if ($order === null) {
throw new RuntimeException('Order not found.');
}
// Match the payment to the expected order, not just its ID.
if ((string) $order->payment_reference !== $paymentRef ||
(int) $order->amount_minor !== $amountMinor ||
(string) $order->currency !== $currency) {
throw new RuntimeException('Payment does not match order.');
}
if ($order->status === 'pending') {
DB::table('orders')->where('id', $orderId)->update([
'status' => 'paid',
'updated_at' => now(),
]);
// Insert one durable follow-up task per paid order.
DB::table('outbox_messages')->insert([
'event_key' => 'order-paid:' . $orderId,
'event_type' => 'order.paid',
'payload' => json_encode([
'order_id' => $orderId,
], JSON_THROW_ON_ERROR),
'created_at' => now(),
'updated_at' => now(),
]);
} elseif ($order->status !== 'paid') {
// Do not resurrect refunded or cancelled orders.
throw new RuntimeException('Unexpected order state.');
}
DB::table('webhook_events')
->where('provider', 'examplepay')
->where('event_id', $eventId)
->update([
'processed_at' => now(),
'updated_at' => now(),
]);
}, 3);
} catch (DuplicateWebhookEvent $e) {
// The original transaction has committed its work.
return response()->json(['received' => true], 200);
}
return response()->json(['received' => true], 200);
}
}The implementation assumes the provider's event has an integer `order_id`, integer `amount_minor`, three-letter uppercase `currency`, and a stable `payment_reference`. Adapt those fields to the provider's actual signed payload. If the original API supplies a value such as `49.99`, use its documented decimal representation and convert it safely; do not compare floating-point amounts for financial decisions.
In a real payment integration, also verify that the provider reports the payment as genuinely settled or completed under its documented state model. The signed `type` alone may not be sufficient if the provider has asynchronous settlement, test/live modes or multiple merchant accounts.
4. Register the endpoint
Add the route to `routes/api.php`:
<?php
use App\Http\Controllers\PaymentWebhookController;
use Illuminate\Support\Facades\Route;
Route::post('/webhooks/examplepay', [
PaymentWebhookController::class, 'handle'
]);Under Laravel's default API route prefix, the endpoint is `/api/webhooks/examplepay`. Configure that exact HTTPS URL with the payment provider. API routes normally do not use the browser session CSRF middleware; signature validation is mandatory here.
5. What happens with two concurrent requests?
Suppose request A and request B carry the same provider event ID.
Request A inserts `(examplepay, evt_12345)` into `webhook_events` and holds the transaction open while updating the order. Request B attempts the same insert. InnoDB's unique constraint prevents both inserts from succeeding; B generally waits for A's transaction to commit or roll back.
If A commits, B receives a duplicate-key error, its transaction rolls back and the controller acknowledges the duplicate with HTTP 200. If A rolls back, B can insert the ID and attempt processing. This is why the database constraint—and placing it in the same transaction as the order update—is essential.
A basic application-level `exists()` check cannot provide that guarantee.
6. Different event IDs can refer to the same payment
Deduplicating by event ID prevents replaying the *same delivery event*, but some providers produce multiple distinct events for one underlying payment. The sample therefore locks the order row and only changes a `pending` order to `paid` once.
The `outbox_messages.event_key` uniqueness rule adds another safeguard: there can be only one `order-paid:1001` message in the example. Do not use a broad key such as `payment.completed` plus order ID as a replacement for provider event identity unless your actual event model guarantees that combination is unique and represents only one business transition.
Likewise, blindly recording an event as processed before updating the order can permanently lose work if the process crashes. The event insert and order change must commit together.
7. How to send emails or fulfil orders safely
Avoid calling email services, payment APIs or stock-fulfilment integrations *inside* the SQL transaction. MySQL cannot undo an email already sent or an external HTTP call made before a rollback.
Instead, the example writes an outbox message in the same transaction as the order's status change. A separate scheduled or queued worker can read unprocessed outbox rows, perform the work and mark them completed. That worker still needs retries, failure handling and ideally an idempotency key supported by the downstream service: a crash after sending but before recording completion can cause redelivery.
Laravel's `afterCommit()` dispatch features are useful when dispatching jobs after a successful transaction, but a durable outbox is preferable when you must not lose a follow-up task between the database commit and queue dispatch.
8. What HTTP response should duplicates receive?
Once the original event has completed successfully, return a normal 2xx acknowledgement for later copies. Most providers treat a successful acknowledgement as a reason to stop retrying that delivery.
If your database is unavailable or payment processing fails before the transaction commits, return an error so the provider can retry according to its delivery policy. Do **not** catch every `QueryException` and return success: a deadlock, connection failure or invalid schema is not evidence of a duplicate event.
In this MySQL example, error 1062 is recognised specifically around the `webhook_events` insert. Other database errors propagate normally.
9. Test duplicate delivery and rollback
Before deployment, test these cases with signed payloads supplied by the provider's official webhook testing tools or with a test provider whose signing contract you control:
- Deliver the identical event twice; the order should transition once and only one outbox message should exist.
- Deliver the identical event concurrently from two connections; the unique event key must still prevent double processing.
- Force a database failure after the event insert; the transaction should roll back so a retry can process it.
- Deliver two different event IDs for one payment; the order transition and outbox message should still happen once.
- Submit an invalid signature or altered body; the endpoint must reject it before updating anything.
- Submit a mismatched amount, currency or payment reference; no order should be marked paid.
Keep event and diagnostic logs free of secrets, full payment payloads and unnecessary customer information. Retain event IDs long enough to cover the provider's retry and replay windows; a short expiry can allow an old event to run again. See the Laravel database transaction documentation and Laravel queue documentation for related behaviour.
Final recommendation
For Laravel payment webhooks, use three layers: **verify the provider's signature**, **insert the provider event ID under a database unique constraint inside the same transaction as the order update**, and **make the business transition itself idempotent**. Queue or outbox any follow-up work and make that processing retry-safe too.
This design remains dependable when the payment provider retries events and when multiple PHP workers receive the same webhook simultaneously.
