If you sell something that may or may not be delivered, charging up front and refunding later works, but it is ugly. We run an SMS verification service, and a number that never receives its code used to leave two lines in the customer's history: a purchase and, minutes later, a refund. The money came back, but customers still saw "deductions" for things they never got and asked why they were charged.
So we switched to authorize, then capture: buying a number only puts the price on hold, and the charge happens when the code arrives. This post shows the pattern in Laravel with a ledger-based wallet. It is small, but there are a few traps.
The model
Two numbers per user instead of one:
-
balance: money the customer owns. It changes only on deposits, charges and refunds, and always equals the sum of the ledger. -
held_balance: money reserved for orders that are still waiting. It is not in the ledger.
What the customer can spend is balance - held_balance. Each order remembers its own hold:
Schema::table('users', fn (Blueprint $t) => $t->decimal('held_balance', 14, 4)->default(0)); Schema::table('orders', function (Blueprint $t) { $t->decimal('held_amount', 12, 4)->nullable(); // null = older order, charged at purchase $t->timestamp('charged_at')->nullable(); // when the hold became a charge }); The nullable held_amount matters: orders created before the change were charged up front, and they must keep the old refund behaviour. Never migrate money semantics in place.
Three wallet operations
All three lock the user row, so two parallel purchases can't both pass the balance check.
public function hold(User $user, string $amount): void { DB::transaction(function () use ($user, $amount) { $u = User::whereKey($user->id)->lockForUpdate()->firstOrFail(); $available = bcsub($u->balance, $u->held_balance, 4); if (bccomp($available, $amount, 4) < 0) { throw new InsufficientBalance; } $u->forceFill(['held_balance' => bcadd($u->held_balance, $amount, 4)])->save(); }); } public function release(User $user, string $amount): void { // same lock; held_balance = max(0, held_balance - amount); no ledger entry } public function capture(User $user, string $amount, string $key, Model $ref): LedgerEntry { // ONE ledger entry (purchase, -amount) and the hold released in the same transaction return $this->post($user, "-{$amount}", 'purchase', $key, $ref, allowNegative: true, releaseHeld: $amount); } capture() goes through the same post() that writes every ledger entry, so it inherits the idempotency key check. That is the most important line in the whole feature (see below).
Every other debit, such as rentals or add-ons, must now check balance - held_balance instead of balance. Otherwise a customer with $1 can hold $0.70 for a number and still spend the full $1 elsewhere.
Wiring it into the order lifecycle
// buy $this->wallet->hold($user, $price); try { return $this->acquireNumberFromSuppliers(...); // creates the order with held_amount = $price } catch (\Throwable $e) { $this->wallet->release($user, $price); // no number: nothing happened throw $e; } // first valid SMS stored if ($order->held_amount !== null && $order->charged_at === null) { $this->wallet->capture($order->user, $order->held_amount, "order:{$order->uuid}", $order); $order->forceFill(['charged_at' => now()])->save(); } // cancel or expiry without a code if ($order->held_amount !== null) { $this->wallet->release($order->user, $order->held_amount); // new orders } else { $this->wallet->credit($order->user, $order->price, 'refund', "refund:order:{$order->id}"); // old ones } The traps
1. Parallel pollers. Our SMS poller can run twice for the same order. Both see "first code arrived" and both call capture(). Because the capture uses the order's purchase key (order:{uuid}), the second call finds the existing ledger entry and returns it before touching the balance. So the hold is released once and the customer is charged once. Without the idempotency key you would double-charge.
2. The catch must be broad. The supplier loop throws a business exception when no number is available, but a timeout or a bug throws something else. If you only release the hold on your own exception, an unexpected error leaves money frozen forever. Catch Throwable, release, rethrow.
3. Filtered messages are not codes. We keep SMS that fail validation (wrong app, no code) for the admin, but they must not trigger the capture. Only count delivered messages.
4. Moving an order between users. Our admins can move a number to another account. With holds, you move the hold (hold on the new owner first, so it can fail cleanly, then release on the old one), not a charge.
5. Show the hold. If the balance doesn't drop, customers try to buy more and hit "not enough balance". We show "$0.70 on hold" under the balance, and the API's get_balance returns balance (spendable) and on_hold.
Tests worth writing
A handful of feature tests made this safe to ship:
- buy → balance unchanged,
held_balance= price, no purchase entry - code arrives twice (same SMS, two polls) → exactly one purchase entry
- cancel / expire / no supplier → hold gone, no purchase, no refund
- $1.00 customer holds $0.70 → a $0.50 rental is refused
- an old, pre-change order still gets its refund
Seven existing tests also failed after the change, because they asserted "charged then refunded". That is good: they documented the old behaviour, and each one had to be rewritten on purpose.
Result
Customers now see one deduction per code they received, and nothing at all for numbers that never got one. The ledger stays append-only and still adds up to the balance.
Disclosure: I work on receive-smss.net, a virtual number service for SMS verification, where this change shipped. The code above is simplified from our implementation.
