Skip to main content

Payment Webhook Idempotency & Order Reconciliation Engineering

Eliminate lost orders and double emails with Razorpay/Stripe HMAC verification, SQL idempotency locks, and scheduled paid-link recovery.

Category: Web Development | By DreamWebCrafts Engineering | Published Nov 13, 2026

Nothing erodes buyer confidence faster than watching money debit from a UPI or card account while the merchant dashboard leaves an order stuck in pending—or worse, processing a retried gateway webhook twice and firing duplicate confirmation emails, stock deductions, and shipping labels. Inside DreamCore storefronts and bespoke DreamWebCrafts checkout pipelines, payment reliability rests on constant-time HMAC signature checks, database-enforced idempotency ledgers, minor-unit integer verification, and scheduled paid-link reconciliation.

What to Choose: Combine raw-body server-to-server webhooks verified with hash_hmac('sha256', ...) plus hash_equals(), an atomic SQL idempotency claim table keyed by (provider, external_event_id) paired with lockForUpdate() row guards, strict minor-unit amount comparison, and a 10-minute reconciliation scheduler recovering mobile UPI browser drop-offs.

1. Why Browser Return Callbacks & Gateway Webhooks Race

Modern mobile checkouts bounce buyers across external banking apps, UPI intent switches, and 3-D Secure challenge frames. Roughly 8% to 14% of mobile shoppers close the browser tab immediately after receiving their bank SMS confirmation without ever completing the redirect back to /checkout/status. Meanwhile, payment gateways deliver asynchronous webhooks on separate retry schedules—sometimes arriving 300 milliseconds before the browser redirect, sometimes 90 seconds later, and occasionally three times in parallel when an upstream worker returns HTTP 504.

Treating the frontend return URL as authoritative creates silent lost orders, while processing every incoming webhook blindly without an atomic ledger lock corrupts inventory counts and spams customers with duplicate receipts.

Orthogonal Order Fulfillment & Payment State Machines

Never overload a single status column to represent both payment settlement and warehouse dispatch. Separate payment_status (unpaid → authorized → paid → partially_refunded / refunded) from fulfillment status (pending → confirmed → packed → shipped → delivered / cancelled). Keeping both axes orthogonal prevents a partial refund or late dispute event from overwriting carrier shipment tracking numbers.

Payment Failure Mode Root Cause in Naive Checkouts Production Engineering Fix Recovery Window & SLA
Debited UPI Stuck in pending Buyer kills browser during UPI app switch and webhook hits stale preview or fails DNS Scheduled command polls unpaid orders via detail API and replays confirmation idempotently Auto-recovered within 10–15 minutes
Duplicate Emails on 504 Retry Gateway retries webhook 5 times; app sends 5 buyer and merchant emails Unique (provider, external_event_id) lock plus DB::afterCommit() notification dedupe key Strictly one email per confirmed payment transition
Razorpay List API payments: [] Quirk Calling list endpoint GET /v1/payment_links omits nested captured payment objects Always fetch detail endpoint GET /v1/payment_links/{id} when status === 'paid' Zero false negatives on paid-link polling
Late Settlement After Auto-Cancel Cart sweeper cancels order at 30 minutes before delayed NEFT/UPI capture arrives Transition cancelled orders safely back to confirmed with cycle-scoped notification keys Recovered automatically or flagged for ops review
Minor-Unit Partial Tampering Floating-point comparisons or trusting client cart amount lets partial payment mark paid Enforce integer settledMinor >= grandTotalMinor inside locked transaction Zero underpaid orders released to fulfillment

2. Designing an Atomic Idempotency Ledger & Constant-Time HMAC Gate

Every gateway webhook pipeline requires two orthogonal defenses before mutating order state: cryptographic authenticity of the raw HTTP payload and single-winner concurrency control in SQL.

Verifying Raw Payload Signatures Before JSON Decoding

Never compute HMAC signatures against re-serialized PHP arrays (json_encode($request->all())). Frameworks normalize whitespace, reorder keys, and cast decimal strings into floats—causing valid signatures to fail unpredictably. Always verify the exact raw byte stream from $request->getContent() against the gateway's signature header using constant-time hash_equals() before parsing JSON, and persist an idempotency record backed by a database UNIQUE constraint.

For gateways supplying signed timestamps (such as Stripe's t= header field), reject payloads older than 300 seconds to narrow replay windows, support dual active/previous webhook secrets during zero-downtime key rotation, and normalize Razorpay paise, Stripe cents, and UPI settlement identifiers into a single immutable GatewayPaymentEvent DTO before touching core domain logic.

SQLdatabase/migrations/2026_05_01_payment_webhook_ledger.sqlCopy
CREATE TABLE payment_webhook_events (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    store_id BIGINT UNSIGNED NOT NULL,
    provider VARCHAR(32) NOT NULL,
    external_event_id VARCHAR(120) NOT NULL,
    order_id BIGINT UNSIGNED NULL,
    payload_sha256 CHAR(64) NOT NULL,
    settled_minor BIGINT UNSIGNED NOT NULL DEFAULT 0,
    processing_state VARCHAR(32) NOT NULL DEFAULT 'claimed',
    processed_at TIMESTAMP NULL DEFAULT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY uq_payment_webhook_provider_event (provider, external_event_id),
    KEY idx_payment_webhook_store_order (store_id, order_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
PHP 8.3app/Modules/Storefront/Http/Controllers/RazorpayWebhookController.phpCopy
<?php

declare(strict_types=1);

namespace App\Modules\Storefront\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Storefront\Services\PaymentWebhookProcessor;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

final class RazorpayWebhookController extends Controller
{
    public function __invoke(Request $request, PaymentWebhookProcessor $processor): JsonResponse
    {
        $rawBody = $request->getContent();
        $signature = (string) $request->header('X-Razorpay-Signature', '');
        $secret = (string) config('services.razorpay.webhook_secret');

        $expected = hash_hmac('sha256', $rawBody, $secret);
        if ($signature === '' || $secret === '' || ! hash_equals($expected, $signature)) {
            return response()->json(['ok' => false, 'error' => 'Invalid webhook signature.'], 401);
        }

        $payload = json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR);
        $eventId = (string) ($request->header('X-Razorpay-Event-Id') ?: data_get($payload, 'payload.payment.entity.id', ''));
        $orderId = (int) data_get($payload, 'payload.payment.entity.notes.stc_order_id', 0);
        $settledMinor = (int) data_get($payload, 'payload.payment.entity.amount', 0);

        if ($eventId === '' || $orderId <= 0) {
            return response()->json(['ok' => true, 'ignored' => true]);
        }

        $transitioned = $processor->markOrderPaidIdempotently(
            orderId: $orderId,
            provider: 'razorpay',
            eventId: $eventId,
            settledMinor: $settledMinor,
            payloadHash: hash('sha256', $rawBody),
        );

        return response()->json(['ok' => true, 'transitioned' => $transitioned]);
    }
}
Critical Pitfall — Never Dispatch Side Effects Inside an Uncommitted Transaction: Sending confirmation emails, decrementing external warehouse APIs, or pushing shipping-label jobs inside DB::transaction() before commit triggers phantom notifications whenever a deadlock forces a rollback. Always wrap emails and fulfillment jobs inside DB::afterCommit() and guard each side effect with an atomic notification dedupe key (notify:paid-buyer:{order_id}:{payment_cycle}). Constant-time signature gates, unique event ledger claims, and row-level locks collapse concurrent webhook bursts into exactly-once order transitions.

3. Row-Level Locking, Minor-Unit Math & Late-Settlement Recovery

Even with a unique event key, two distinct gateway events for the same order—such as payment.captured and payment_link.paid—frequently arrive concurrently with different event IDs. Locking the parent order row via lockForUpdate() inside the same ACID transaction guarantees that only the first transaction flips payment_status to paid and emits downstream notifications.

Handling Out-of-Order Events & Cancelled-Order Reopening Safely

Real-world storefronts also encounter late settlements: an unpaid order times out after 30 minutes and transitions to cancelled, yet a delayed UPI clearing event arrives 45 minutes later confirming captured funds. Instead of silently dropping the paid webhook, inspect whether the order is currently pending or cancelled inside the locked row transaction, reopen eligible orders cleanly to confirmed, increment a reconciliation cycle counter so notification dedupe keys remain distinct, and record an append-only ledger entry rather than mutating historical amounts.

Whenever stock deduction occurs at confirmation rather than cart hold, lock matching stc_product_variants rows in deterministic ascending primary-key order before updating inventory counts, flagging oversold late-settled orders for immediate merchant refund or replacement dispatch instead of silently emitting negative stock.

PHP 8.3app/Modules/Storefront/Services/PaymentWebhookProcessor.phpCopy
<?php

declare(strict_types=1);

namespace App\Modules\Storefront\Services;

use App\Modules\Storefront\Jobs\DispatchOrderFulfillmentEffects;
use App\Modules\Storefront\Models\StcOrder;
use Illuminate\Support\Facades\DB;
use RuntimeException;

final class PaymentWebhookProcessor
{
    public function markOrderPaidIdempotently(
        int $orderId,
        string $provider,
        string $eventId,
        int $settledMinor,
        string $payloadHash,
    ): bool {
        return DB::transaction(static function () use ($orderId, $provider, $eventId, $settledMinor, $payloadHash): bool {
            /** @var StcOrder|null $order */
            $order = StcOrder::query()->lockForUpdate()->find($orderId);
            if ($order === null) {
                return false;
            }

            // Unique (provider, external_event_id) blocks concurrent duplicate webhook retries
            $inserted = DB::table('payment_webhook_events')->insertOrIgnore([
                'store_id' => $order->store_id,
                'provider' => $provider,
                'external_event_id' => $eventId,
                'order_id' => $order->id,
                'payload_sha256' => $payloadHash,
                'settled_minor' => $settledMinor,
                'processing_state' => 'applied',
                'processed_at' => now(),
                'created_at' => now(),
            ]);

            if ($inserted === 0 || $order->payment_status === 'paid') {
                return false;
            }

            $expectedMinor = (int) $order->getRawOriginal('grand_total');
            if ($settledMinor < $expectedMinor) {
                throw new RuntimeException("Settled minor {$settledMinor} below order total {$expectedMinor}.");
            }

            $nextStatus = in_array($order->status, ['pending', 'cancelled'], true)
                ? 'confirmed'
                : $order->status;

            $order->forceFill([
                'payment_status' => 'paid',
                'status' => $nextStatus,
                'paid_at' => now(),
            ])->save();

            DB::afterCommit(static function () use ($order): void {
                DispatchOrderFulfillmentEffects::dispatch($order->store_id, $order->id);
            });

            return true;
        });
    }
}

Webhooks alone are never 100% immune to transient firewall drops, misconfigured merchant webhook secrets during onboarding, or provider outage backlogs. Running an automated reconciliation command every 10–15 minutes closes the loop by scanning unpaid recent orders created within the last 48 hours and querying the gateway directly.

Bypassing the Razorpay List API Empty-Payments Bug

Teams relying on bulk list endpoints like GET /v1/payment_links frequently discover a subtle trap in production: list responses can return status: "paid" while leaving the nested payments: [] array completely empty, starving amount and payment-ID checks. Whenever reconciliation encounters a paid link or open recent order, explicitly query the individual detail endpoint (GET /v1/payment_links/{id}), sum captured payment minor units directly from the hydrated detail payload, and route settled orders straight into markOrderPaidIdempotently().

PHP 8.3app/Console/Commands/ReconcileStorefrontPaymentsCommand.phpCopy
<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Modules\Storefront\Models\StcOrder;
use App\Modules\Storefront\Services\PaymentWebhookProcessor;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;

final class ReconcileStorefrontPaymentsCommand extends Command
{
    protected $signature = 'storefront:reconcile-payments {--hours=48}';
    protected $description = 'Poll gateway payment-link detail endpoints for unpaid orders and recover missed webhooks.';

    public function handle(PaymentWebhookProcessor $processor): int
    {
        $cutoff = now()->subHours((int) $this->option('hours'));
        $recovered = 0;

        StcOrder::query()
            ->withoutGlobalScopes()
            ->where('payment_status', '!=', 'paid')
            ->whereNotNull('gateway_payment_link_id')
            ->where('created_at', '>=', $cutoff)
            ->chunkById(50, function ($orders) use ($processor, &$recovered): void {
                foreach ($orders as $order) {
                    $detail = Http::withBasicAuth(
                        (string) config('services.razorpay.key'),
                        (string) config('services.razorpay.secret'),
                    )
                        ->timeout(8)
                        ->get("https://api.razorpay.com/v1/payment_links/{$order->gateway_payment_link_id}")
                        ->throw()
                        ->json();

                    if (($detail['status'] ?? '') !== 'paid') {
                        continue;
                    }

                    $capturedMinor = collect($detail['payments'] ?? [])
                        ->where('status', 'captured')
                        ->sum(static fn (array $item): int => (int) ($item['amount'] ?? 0));
                    $settledMinor = $capturedMinor > 0 ? $capturedMinor : (int) ($detail['amount_paid'] ?? 0);

                    $applied = $processor->markOrderPaidIdempotently(
                        orderId: (int) $order->id,
                        provider: 'razorpay_reconcile',
                        eventId: "link:{$order->gateway_payment_link_id}:paid",
                        settledMinor: $settledMinor,
                        payloadHash: hash('sha256', (string) json_encode($detail)),
                    );

                    if ($applied) {
                        $recovered++;
                    }
                }
            });

        $this->info("Reconciliation complete. Recovered {$recovered} paid orders.");

        return self::SUCCESS;
    }
}

5. Checkout Return Polling & Post-Settlement Fulfillment Triggers

When a buyer returns to /checkout/status/{orderRef} after approving a UPI mandate, the signed webhook may still be 1 to 3 seconds behind the browser redirect. Showing an error banner prematurely causes terrified buyers to pay twice. Instead, render a calm verification state backed by bounded exponential backoff with jitter, polling your lightweight status endpoint up to eight times before transitioning gracefully to an "Awaiting bank confirmation — receipt will email automatically" screen.

Bounded Exponential Backoff & Idempotent Label Generation

Once DB::afterCommit() dispatches fulfillment effects, generate GST tax invoices strictly from stored minor-unit integers (splitting CGST, SGST, and IGST components using deterministic largest-remainder paise rounding so individual line taxes always sum back to the exact invoice total) and render 4×6 thermal shipping label PDFs idempotently so retrying a crashed queue worker produces the identical tracking document without creating duplicate courier manifests.

Route unmatched gateway exceptions—such as captured funds arriving below expected order minor totals or orphaned transactions after manual cancellation—into a dead-letter ops alert queue so finance teams inspect discrepancies within minutes rather than discovering unfulfilled payments in monthly bank statements.

TypeScriptresources/js/composables/usePaymentStatusPoll.tsCopy
import axios from 'axios';
import { onUnmounted, ref } from 'vue';

export type PaymentUiState = 'pending' | 'paid' | 'failed' | 'delayed';

export function usePaymentStatusPoll(statusUrl: string) {
  const status = ref<PaymentUiState>('pending');
  const controller = new AbortController();

  async function waitForConfirmation(maxAttempts = 8): Promise<void> {
    for (let attempt = 0; attempt < maxAttempts; attempt++) {
      if (controller.signal.aborted) return;

      const { data } = await axios.get<{ payment_status: string }>(statusUrl, {
        signal: controller.signal,
      });

      if (data.payment_status === 'paid') {
        status.value = 'paid';
        return;
      }
      if (data.payment_status === 'failed') {
        status.value = 'failed';
        return;
      }

      const jitterMs = Math.floor(Math.random() * 250);
      const delayMs = Math.min(4500, 750 + attempt * 500) + jitterMs;
      await new Promise((resolve) => setTimeout(resolve, delayMs));
    }

    status.value = 'delayed';
  }

  onUnmounted(() => controller.abort());
  return { status, waitForConfirmation };
}
Where to Harden Commerce Payments: Enforce UNIQUE(provider, external_event_id) inside database migrations, keep Razorpay and Stripe keys encrypted per tenant via Laravel 'encrypted' model casts, trigger buyer and merchant emails strictly inside DB::afterCommit() via deduped OrderNotificationEffects jobs, and generate thermal 4×6 shipping labels only after payment_status === 'paid' settles. How to Guarantee Zero Lost Paid Orders on Your Storefront:
  1. Verify webhook HMAC signatures against raw unparsed request bytes with hash_equals() and log failures without printing secrets.
  2. Enforce integer minor-unit comparisons (settledMinor >= grand_total) inside lockForUpdate() transactions before flipping order state.
  3. Schedule storefront:reconcile-payments every 10–15 minutes using detail endpoints rather than summary lists so mobile UPI drop-offs recover automatically.
  4. Test concurrent duplicate webhooks, out-of-order captures, and late-settlement reopening in automated PHPUnit checkout suites.
  5. Need bulletproof checkout reconciliation and multi-gateway reliability? Explore DreamWebCrafts commerce engineering or consult our checkout architects.
Frequently Asked Question: How long should we retain payment webhook audit logs and what gets redacted?

Retain sanitized webhook event metadata—provider, external_event_id, payload_sha256, HTTP verification outcome, and settled minor-unit amount—for at least 90 days to troubleshoot merchant support disputes, while stripping raw cardholder PII, API secrets, and authorization headers prior to persistence.

Related Engineering Articles