Book a call
Menu

Two Callers, One Payment: Sharing Licence Activation Between Razorpay Checkout and the Webhook in Laravel

Happy Coders team5 Dec 202615 min read
Two Callers, One Payment: Sharing Licence Activation Between Razorpay Checkout and the Webhook in Laravel

A Razorpay integration in a Laravel SaaS usually starts with one path. The browser opens Checkout, the customer pays, Checkout hands back three values, and the browser posts them to your server, which checks a signature and grants the plan. It works in every demo. It has one hole, and closing that hole creates a second, quieter problem: two different code paths that can both turn the same payment into a licence.

This is how we arranged it in Happy Tracker’s billing, which sells yearly per-user plans and add-on seats in rupees. The interesting part is not the webhook itself. It is making the browser path and the webhook path share one piece of activation code that is safe to call twice, at the same moment, for the same payment.

The browser-only flow

// The browser path, before the webhook existed.
POST /subscription/order     -> server computes the amount, creates a Razorpay order,
                                stores a subscription row with status 'created'
Razorpay Checkout (browser)  -> customer pays by card, UPI or netbanking
POST /subscription/verify    -> HMAC of "order_id|payment_id" checked,
                                row flipped to 'paid', licence granted

Two details in the first step matter later. The amount is computed on the server from the plan, the seats and, for upgrades and add-ons, proration. The request never says how much to charge. And the subscription row is written with status created before the customer has paid, holding the Razorpay order id. That row is the thing both paths will later look up.

// order(): the amount is never taken from the request.
$amount = $this->proratedCharge($organization, $plan, $data['seats'], $data['kind'], $chargeWhen, $currency)['amount'];

$resp = Http::withBasicAuth(config('services.razorpay.key_id'), config('services.razorpay.key_secret'))
    ->asJson()->post('https://api.razorpay.com/v1/orders', [
        'amount'   => (int) round($amount * 100),          // paise
        'currency' => $currency,
        'receipt'  => $prefix.'-'.$organization->id.'-'.now()->timestamp,
    ]);
abort_unless($resp->successful() && $resp->json('id'), 502, 'Could not start the payment. Please try again.');

$subscription = $this->withReferenceRetry(fn () => $organization->subscriptions()->create([
    'kind'              => $data['kind'],               // 'plan' or 'addon'
    'reference'         => $this->nextReference($organization, $prefix),
    'seats'             => $data['seats'],
    'amount'            => $amount,
    'status'            => 'created',                   // pending payment
    'razorpay_order_id' => $resp->json('id'),
    // plan_id, starts_at, expires_at ...
]));

The verify step is the standard Razorpay check: an HMAC-SHA256 of order_id|payment_id using your key secret, compared with hash_equals. If it matches, the payment is genuine and belongs to that order.

The hole: the browser is not reliable

The only thing that turns a captured payment into a licence, in that design, is a request from the customer’s browser. If the tab is closed, the laptop sleeps, the mobile network drops, or the verify request fails, then in the second between Razorpay capturing the money and that request arriving, the customer has paid and has nothing. Nobody is told. The subscription row sits at created forever.

When we audited this, we found eight rows stuck at created. On checking each against Razorpay, none had been paid: some were made under old test keys, the rest were abandoned at the payment screen. No customer had been hurt. But nothing in the system would have told us if one had been.

The fix is the one every gateway recommends: a server-to-server webhook. Razorpay calls your endpoint from its own servers when payment.captured fires, and keeps retrying until it gets a 2xx. It does not depend on the customer’s browser at all.

The new problem: two activators, one payment

Adding the webhook does not remove the verify call. You still want the browser path, because it gives the customer an immediate answer on the same screen. So now, for a normal successful payment, two requests arrive at almost the same time: the SPA’s verify and Razorpay’s webhook. In practice the webhook often wins.

If each path has its own copy of the activation logic, three things go wrong over time:

  • Double grants. Both read the row as created, both create a licence. For an add-on, the seats are added twice.
  • A false error. The verify path, written when it was the only path, looks for a created row. If the webhook already flipped it to paid, verify returns 404 to a customer who has just paid. They see “No pending order found” and assume the payment failed.
  • Drift. Someone fixes a renewal edge case in one copy and not the other.

We have written before about the general rules for making a payment webhook idempotent. This post is about the specific shape when the webhook is not the only caller.

One activator, safe to call twice

The SPA verify call and the Razorpay webhook both reaching one activator
Whichever request gets the row lock first does the work. The other finds the row already paid.

The activation logic moved out of the controller into a small service that both paths call. It has three layers of protection, and each one does a different job.

class SubscriptionActivator
{
    /**
     * Idempotent: a subscription that is already paid is left alone and false is
     * returned, so a webhook retry cannot grant the same thing twice.
     */
    public function activate(Subscription $subscription, string $paymentId, string $source, ?User $actor = null): bool
    {
        if ($subscription->status !== 'created') {
            return false;                                // cheap early exit
        }

        $organization = $subscription->organization;

        DB::transaction(function () use ($organization, $subscription, $paymentId) {
            // Re-read inside the transaction and lock, so the SPA's /verify and the
            // webhook arriving together cannot both pass the status check.
            $fresh = Subscription::whereKey($subscription->getKey())->lockForUpdate()->first();
            if (! $fresh || $fresh->status !== 'created') {
                return;
            }

            $fresh->update(['status' => 'paid', 'razorpay_payment_id' => $paymentId]);

            if ($fresh->kind === 'addon') {
                $organization->usableLicense()?->increment('seats', $fresh->seats);
                return;
            }

            // A future start date means a booked renewal: replace only a prior scheduled
            // plan. Otherwise it is an immediate change: replace the current one.
            $isRenewal = $fresh->starts_at->isAfter(now()->startOfDay());
            $query = $organization->licenses()->where('status', 'active');
            if ($isRenewal) {
                $query->whereDate('starts_at', '>', now()->toDateString());
            }
            $query->update(['status' => 'superseded']);

            $organization->licenses()->create([
                'plan_id'    => $fresh->plan_id,
                'seats'      => $fresh->seats,
                'starts_at'  => $fresh->starts_at->toDateString(),
                'expires_at' => $fresh->expires_at->toDateString(),
                'status'     => 'active',
            ]);
        });

        $subscription->refresh();
        if ($subscription->status !== 'paid') {
            return false;                                // another request won the lock
        }

        AuditLog::record($organization, $actor, 'subscription.paid', $subscription->reference, [
            'payment_id' => $paymentId,
            'source'     => $source,                     // 'checkout' or 'webhook'
        ]);

        return true;
    }
}

The early status check is an optimisation. The second caller, arriving after the first has finished, returns immediately without opening a transaction.

The locked re-read inside the transaction is the real guarantee. lockForUpdate() takes a row lock, so if both requests got past the early check at the same moment, one waits for the other’s transaction to commit. When it gets the lock, it re-reads the row, sees paid, and returns without doing anything. An if outside a lock is a hope; the lock makes it a guarantee.

The refresh after the transaction decides the return value and the audit entry. Only the request that actually did the work writes subscription.paid to the audit log, tagged with its source, checkout or webhook. That tag turned out to be the most useful line in the whole change. It tells you how often the webhook is the one that activates, which is how often the browser would have failed you without it.

The two kinds of purchase activate differently. An add-on increments the seats on the current usable licence. A plan supersedes the current active licence (or, for a booked renewal whose start date is in the future, only a previously scheduled one) and creates a new licence for its own term. Keeping that branching in one place is the main reason for the service. It is exactly the kind of logic that drifts when it is copied.

Verify, adjusted for a world where it can lose the race

public function verify(Request $request): JsonResponse
{
    $organization = $this->currentOrganization($request);
    $this->requireRole($organization, $request, ['owner']);

    $data = $request->validate([
        'razorpay_order_id'   => ['required', 'string'],
        'razorpay_payment_id' => ['required', 'string'],
        'razorpay_signature'  => ['required', 'string'],
    ]);

    $expected = hash_hmac('sha256',
        $data['razorpay_order_id'].'|'.$data['razorpay_payment_id'],
        (string) config('services.razorpay.key_secret'));
    abort_unless(hash_equals($expected, $data['razorpay_signature']), 422, 'Payment verification failed.');

    // 'paid' is accepted as well as 'created': the webhook fires on the same payment
    // and often wins. If it did, report success instead of a 404 at a customer who
    // has just paid.
    $subscription = $organization->subscriptions()
        ->where('razorpay_order_id', $data['razorpay_order_id'])
        ->whereIn('status', ['created', 'paid'])->first();
    abort_unless($subscription, 404, 'No pending order found for this payment.');

    app(SubscriptionActivator::class)->activate($subscription, $data['razorpay_payment_id'], 'checkout', $request->user());

    // ... return the fresh licence, seat cap and seats used
}

The one-word change is whereIn('status', ['created', 'paid']). Before the webhook existed, looking only for created was correct. With the webhook, a paid row for this order means the work is already done, and the customer should get the same success response either way. The signature check still runs first, so this does not let anyone confirm an order they did not pay for.

The lookup is still scoped to the current organization and requires the owner role, so one company cannot verify another company’s order even with valid Razorpay values.

The webhook endpoint

// routes/api.php: public and unauthenticated by necessity, throttled,
// and authenticated by the HMAC inside the controller instead.
Route::post('webhooks/razorpay', RazorpayWebhookController::class)->middleware('throttle:120,1');
public function __invoke(Request $request, SubscriptionActivator $activator): JsonResponse
{
    $secret = (string) config('services.razorpay.webhook_secret');
    if ($secret === '') {
        // 503, not 200: Razorpay keeps retrying instead of discarding a real payment.
        Log::error('Razorpay webhook arrived but the webhook secret is not set.');
        return response()->json(['error' => 'Webhook secret not configured.'], 503);
    }

    // The signature covers the RAW body. Re-encoding the parsed JSON changes the bytes.
    $raw      = $request->getContent();
    $given    = (string) $request->header('X-Razorpay-Signature', '');
    $expected = hash_hmac('sha256', $raw, $secret);
    if (! hash_equals($expected, $given)) {
        return response()->json(['error' => 'Invalid signature.'], 401);
    }

    $event     = (string) $request->input('event');
    $payment   = (array) $request->input('payload.payment.entity', []);
    $orderId   = (string) ($payment['order_id'] ?? '');
    $paymentId = (string) ($payment['id'] ?? '');

    // Anything else is acknowledged so Razorpay stops retrying it.
    if ($event !== 'payment.captured' || $orderId === '' || $paymentId === '') {
        return response()->json(['status' => 'ignored', 'event' => $event]);
    }

    $subscription = Subscription::with('organization')->where('razorpay_order_id', $orderId)->first();
    if (! $subscription) {
        // Money taken against an order we have no row for. Needs a human: log loudly,
        // but acknowledge, because a retry will not create the row.
        Log::error('Razorpay webhook: paid order has no matching subscription.', ['order_id' => $orderId]);
        return response()->json(['status' => 'unmatched'], 200);
    }

    $activated = $activator->activate($subscription, $paymentId, 'webhook');

    return response()->json(['status' => $activated ? 'activated' : 'already_paid']);
}

Each status code is a decision about what Razorpay should do next:

  • 503 when the webhook secret is not configured. The obvious choice is to return 200 and ignore events until the secret is set. That silently throws away real payment events. A 503 makes Razorpay keep retrying, so once the secret is in place, the backlog is processed. We deployed the endpoint before the secret was entered in the dashboard, and this is what made that safe.
  • 401 on a bad signature. The endpoint is public by necessity. The HMAC over the raw body is its authentication. The raw body matters: Laravel will happily give you parsed input, and re-encoding that will not reproduce the bytes Razorpay signed.
  • 200 “ignored” for any other event. If you subscribe to more events later, or Razorpay sends one you do not handle, acknowledging it stops pointless retries.
  • 200 “unmatched” for a paid order with no row. This should never happen. If it does, a person has to look at it, so it is logged at error level. Retrying will not make the row appear, so it is acknowledged.

Note that the webhook uses a separate secret from the API key secret. Razorpay sets it per webhook in the dashboard, and it is what you verify against. Mixing the two up is a common reason every webhook signature fails.

Two older holes found on the way

A purchase path that never charged

Before real payments existed, the app had simulated purchase endpoints for demos: they marked a subscription paid and granted a licence immediately. They were still routed after the live keys went in. Since anyone can sign up and become the owner of a new workspace, one request could have granted any plan, any number of seats, for nothing.

/** Refuse the no-payment purchase paths wherever real payments are switched on. */
private function assertSimulatedPurchaseAllowed(): void
{
    abort_if($this->razorpayConfigured(), 422,
        'Online payments are enabled — please complete the payment through checkout.');
}

private function razorpayConfigured(): bool
{
    $id     = (string) config('services.razorpay.key_id');
    $secret = (string) config('services.razorpay.key_secret');

    return str_starts_with($id, 'rzp_') && $secret !== '' && $secret !== 'CHANGE_ME';
}

The guard keeps the demo path alive where no keys are configured (local development, demos) and refuses it with a 422 everywhere else. A test asserts that the real order path still works with the guard in place, so the fix cannot quietly break checkout.

A reference number that was unique in the wrong scope

Subscriptions get human-readable references, SUB-0001 for a company’s first plan purchase, ADD-0001 for its first add-on, numbered per organization. The database column, though, had a global unique index. The first company to buy got SUB-0001. Every other company’s first purchase tried to insert SUB-0001 too, hit a duplicate-key error, and returned a 500. The Razorpay popup never opened.

The fix was to make the unique index match the numbering scope, (organization_id, reference), and to retry the insert if two people in the same company buy at the same moment:

/** SUB-0001 / ADD-0002: max sequence for THIS organization + 1. */
private function nextReference(Organization $organization, string $prefix): string
{
    $maxSeq = (int) Subscription::where('organization_id', $organization->id)
        ->lockForUpdate()->pluck('reference')
        ->map(fn ($r) => (int) preg_replace('/\D/', '', (string) $r))->max();

    return $prefix.'-'.str_pad((string) ($maxSeq + 1), 4, '0', STR_PAD_LEFT);
}

/** Retry if two people in the SAME company bought at the same moment. */
private function withReferenceRetry(callable $callback): Subscription
{
    $attempt = 0;
    while (true) {
        $attempt++;
        try {
            return DB::transaction($callback);
        } catch (UniqueConstraintViolationException $e) {
            if ($attempt >= 3) {
                throw $e;
            }
        }
    }
}

One side effect worth knowing: the Razorpay order is created before the row is inserted, so each failed attempt left an orphaned order at Razorpay. They are harmless and expire, but they are noise when you reconcile.

What the Razorpay webhook endpoint returns in each case
Each status code tells Razorpay whether to retry.

The amount is the server’s business

Everything above assumes the amount on the Razorpay order is right. In a per-seat, yearly product with upgrades and add-ons mid-term, “right” takes some working out, and it is tempting to let the front end do it, because the front end already shows the customer a price. Do not. If the browser sends the amount, the browser can change it.

The same function computes the price in two places: the quote endpoint the purchase screen calls to show its review lines, and the order endpoint that creates the Razorpay order. The customer sees exactly what will be charged, and nothing they send can alter it.

/**
 * What the org actually pays now. Returns ['full', 'credit', 'amount'].
 *  - plan, now      -> full price minus the unused value of the current plan
 *  - plan, renewal  -> full price (the new year starts later, nothing overlaps)
 *  - addon          -> extra seats billed only for the days left on the plan
 */
private function proratedCharge(Organization $organization, Plan $plan, int $seats, string $kind, string $when, string $currency): array
{
    $per  = $currency === 'INR' ? (float) $plan->price_inr : (float) $plan->price_usd;
    $full = round($per * $seats, 2);

    if ($kind === 'addon') {
        $amount = round($per * $seats * $this->remainingFraction($organization->usableLicense()), 2);
    } else {
        $credit = $when === 'now' ? $this->remainingCredit($organization, $currency) : 0.0;
        $amount = max(0.0, round($full - $credit, 2));
    }

    return ['full' => $full, 'credit' => round($full - $amount, 2), 'amount' => $amount];
}

Three cases, three rules. An upgrade that starts now credits the unused value of the current plan and starts a fresh twelve months. A booked renewal starts when the current term ends, so nothing overlaps and nothing is credited. An add-on runs to the same end date as the plan, so it is billed for the remaining fraction of the term only. The remaining fraction is days left over total days of the current licence, clamped between 0 and 1, so an expired licence gives no credit rather than a negative one.

Validation sits next to it. A plan purchase must cover at least the workspace’s active members and no more than the plan’s maximum. Add-ons require a paid plan to attach to. Both are checked in order, before any money is asked for, so the activator never has to deal with a purchase that should not have been allowed.

Reconciling what is stuck at created

A webhook closes most of the gap, not all of it. Webhooks can be misconfigured, the secret can be rotated in the dashboard and not in your environment, or the endpoint can be down for longer than Razorpay keeps retrying. The audit we ran before building the webhook is worth turning into a habit: list the subscription rows that have been at created for more than a day, and ask Razorpay’s orders API what happened to each one.

The answers fall into three groups. An order Razorpay does not recognise was made under different keys and can be ignored. An order with nothing paid was abandoned at the payment screen. An order that shows a captured payment while your row says created is the one that matters: a customer who paid and got nothing. Feed that one through the same activator, with its own source tag, and it gets exactly the same treatment, locks and idempotency included, as the other two paths. Three callers, still one activator.

Testing without your real keys

The simulated-purchase guard immediately broke seven existing tests, on one developer’s machine only. The reason: the local .env held real Razorpay keys, so razorpayConfigured() returned true during tests and the guard refused the demo path the tests used. That is a test-environment bug, not an application bug, and it is the kind that wastes an afternoon.

<!-- phpunit.xml: never let a developer's real keys into the test run -->
<php>
    <env name="RAZORPAY_KEY_ID" value=""/>
    <env name="RAZORPAY_KEY_SECRET" value=""/>
</php>

Pinning the keys to empty strings in phpunit.xml means no developer’s keys leak into the test run, and the suite behaves the same on every machine and in CI. Tests that need payments switched on set the config explicitly for themselves. Before trusting any failing subscription test, check which keys the test actually saw.

For the race itself, the useful test calls the activator twice for the same subscription and asserts exactly one licence and one audit entry. A test cannot easily reproduce the true concurrent arrival, but the lock is what covers that. The test proves that the second call is a no-op, which is the property both paths rely on.

What we would do from the start next time

  • Build the webhook and the activation service on day one, even if the browser path ships first. The browser path is the convenience; the webhook is the guarantee.
  • Make every activation idempotent with a row lock, not a status check alone.
  • Have the browser path accept an already-completed state as success.
  • Return 503 from the webhook when it cannot authenticate, so events wait instead of vanishing.
  • Tag the source of every activation in an audit log. It is cheap and it answers “is the webhook actually doing anything?” without guesswork.
  • Delete or hard-guard any demo payment path before the first live key goes in.
  • Check that every unique index matches the scope of the value it protects.

None of this is specific to Razorpay. Any gateway that offers both a client callback and a server webhook gives you two callers for one payment. Decide early that they share one activator, and most of the rest follows.

Happy Coders builds web apps, SaaS products and payment integrations. Tell us what you are building.

Keep reading

Related articles