From 7f76fad825d5790391470f640fb5429d0597512b Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 07:32:31 +0000 Subject: [PATCH 01/32] build: depend on the Lunar alpha.9 split packages instead of the monorepo Drop lunarphp/lunarmono from require and the lunarphp/lunar VCS repository, so consuming apps no longer have to install the monorepo. Tests pull lunarphp/panel, lunarphp/stripe and lunarphp/table-rate-shipping from Packagist at ^2.0@alpha. Remove the README advice to test against a local path repository, since core is now released on Packagist. --- README.md | 11 ----------- composer.json | 10 +++------- 2 files changed, 3 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index e4781fe..880510f 100644 --- a/README.md +++ b/README.md @@ -342,17 +342,6 @@ composer test # pest + phpstan vendor/bin/pint # code style ``` -While Lunar v2 is in alpha, `lunarphp/core` on Packagist can lag behind the -contracts this package builds against. To test against a local monorepo -checkout, point Composer at it (not committed, both paths are local to you): - -```bash -composer config repositories.lunar '{"type":"path","url":"../lunar/packages/core","options":{"symlink":true}}' -composer require "lunarphp/core:2.x-dev" -W -``` - -Revert with `git checkout -- composer.json && composer update lunarphp/core`. - ### Known follow-ups - The suite runs serially in CI. Two files reach for helpers and fake gateway diff --git a/composer.json b/composer.json index 8f2dbf6..3a55bd5 100644 --- a/composer.json +++ b/composer.json @@ -20,22 +20,18 @@ "homepage": "https://lunarphp.io/" } ], - "repositories": [ - { - "type": "vcs", - "url": "https://github.com/lunarphp/lunar" - } - ], "require": { "php": "^8.4", "inertiajs/inertia-laravel": "^2.0|^3.0", "lunarphp/core": "^2.0@dev", - "lunarphp/lunarmono": "dev-checkout-deps as 2.x-dev", "spatie/laravel-data": "^4.23" }, "require-dev": { "larastan/larastan": "^3.0", "laravel/pint": "1.29.0", + "lunarphp/panel": "^2.0@alpha", + "lunarphp/stripe": "^2.0@alpha", + "lunarphp/table-rate-shipping": "^2.0@alpha", "mockery/mockery": "^1.6.9", "orchestra/testbench": "^10.0|^11.0", "pestphp/pest": "^3.0|^4.0", From 3965831bd6f2866a1ef6e4025af2b6d4efb32445 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 07:54:24 +0000 Subject: [PATCH 02/32] refactor(payments): reconcile intents through ReconcilesPaymentIntents Lunar 2.0.0-alpha.9 replaced SupportsPaymentIntents with ReconcilesPaymentIntents. fetchIntent, voidIntent and refundIntent now take the Cart first, fetchIntent returns a nullable PaymentIntentSnapshot, and a refund amount is a PriceValue. Load the session's cart at each call site and pass it through. A cart that no longer exists, or a null snapshot (the driver did not create the reference for that cart), is an unknowable outcome: reconcile counts an attempt, release answers `unconfirmed`, and invalidation refuses to cancel. CreatesPaymentIntents now extends the reconciliation contract, so the test gateways that only create intents gain verbs that throw, which keeps their sessions unresolved as before. The Pending status and the hold calls follow in their own commits. --- src/Actions/InvalidateCheckoutSession.php | 6 +- src/Actions/ReconcileCheckoutSession.php | 61 +++++++++++------ src/Http/Controllers/CheckoutController.php | 14 ++-- src/Support/PaymentIntentGateway.php | 8 +-- tests/Feature/CheckoutErrorContractTest.php | 3 + tests/Feature/CompletionFailureRefundTest.php | 16 +++-- tests/Feature/DraftOrderAtPayGateTest.php | 14 ++-- tests/Feature/PayBoundaryTest.php | 9 +++ tests/Feature/PaymentIntentReuseTest.php | 3 + tests/Feature/PaymentRecordingTest.php | 14 ++-- tests/Feature/PaymentReleaseTest.php | 68 ++++++++++++++++--- tests/Feature/WebhookFirstPlacementTest.php | 3 + tests/Utils/FakeIntents.php | 24 +++++++ tests/Utils/WithoutIntentReconciliation.php | 31 +++++++++ 14 files changed, 213 insertions(+), 61 deletions(-) create mode 100644 tests/Utils/FakeIntents.php create mode 100644 tests/Utils/WithoutIntentReconciliation.php diff --git a/src/Actions/InvalidateCheckoutSession.php b/src/Actions/InvalidateCheckoutSession.php index 9c27e0e..cc3d4ce 100644 --- a/src/Actions/InvalidateCheckoutSession.php +++ b/src/Actions/InvalidateCheckoutSession.php @@ -10,6 +10,7 @@ use Lunar\Checkout\States\CheckoutSession\Open; use Lunar\Checkout\States\CheckoutSession\PaymentProcessing; use Lunar\Checkout\Support\PaymentIntentGateway; +use Lunar\Core\Models\Cart; /** * Void-first invalidation (spec 0010 §F). No transition to `Cancelled` ever @@ -28,13 +29,14 @@ public function execute(CheckoutSession $session, string $reason): bool { if ($reference = $session->payment_intent_ref) { $gateway = $this->gateways->for($session); + $cart = Cart::query()->find((int) $session->cart_reference); - if ($gateway === null) { + if ($gateway === null || $cart === null) { return false; } try { - $gateway->voidIntent($reference); + $gateway->voidIntent($cart, $reference); } catch (\Throwable) { // Unknown outcome is not a void — the charge may still land. return false; diff --git a/src/Actions/ReconcileCheckoutSession.php b/src/Actions/ReconcileCheckoutSession.php index 7a13ffa..9558182 100644 --- a/src/Actions/ReconcileCheckoutSession.php +++ b/src/Actions/ReconcileCheckoutSession.php @@ -17,10 +17,12 @@ use Lunar\Checkout\States\CheckoutSession\Open; use Lunar\Checkout\States\CheckoutSession\PaymentProcessing; use Lunar\Checkout\Support\PaymentIntentGateway; +use Lunar\Core\Contracts\ReconcilesPaymentIntents; use Lunar\Core\Contracts\SupportsPaymentHolds; -use Lunar\Core\Contracts\SupportsPaymentIntents; +use Lunar\Core\DataObjects\PriceValue; use Lunar\Core\Enums\PaymentIntentStatus; use Lunar\Core\Exceptions\PaymentIntentException; +use Lunar\Core\Models\Cart; use Lunar\Core\Models\Order; /** @@ -50,28 +52,32 @@ public function execute(CheckoutSession $session, ?string $resolve = null): stri $gateway = $this->gateways->for($session); $reference = $session->payment_intent_ref; + $cart = Cart::query()->find((int) $session->cart_reference); if ($resolve !== null) { - return $this->resolveByOperator($session, $gateway, $reference, $resolve); + return $this->resolveByOperator($session, $gateway, $cart, $reference, $resolve); } - if ($gateway === null || $reference === null) { + if ($gateway === null || $cart === null || $reference === null) { return $this->recordAttempt($session); } try { - $status = $gateway->fetchIntent($reference); + $status = $gateway->fetchIntent($cart, $reference)?->status; } catch (PaymentIntentException) { return $this->recordAttempt($session); } return match ($status) { + // Not an intent the gateway created for this cart: unknowable. + null => $this->recordAttempt($session), + // Legitimately still in flight (slow methods) — reschedule // without consuming an attempt (spec 0010 §F). PaymentIntentStatus::Pending => 'pending', PaymentIntentStatus::Captured, - PaymentIntentStatus::RequiresCapture => $this->completeOrRefund($session, $gateway, $reference, $status), + PaymentIntentStatus::RequiresCapture => $this->completeOrRefund($session, $gateway, $cart, $reference, $status), PaymentIntentStatus::Voided, PaymentIntentStatus::Failed => $this->reopen($session, 'intent_'.$status->value), @@ -91,22 +97,28 @@ public function release(CheckoutSession $session): string // An intent exists, so money may exist. Reopen only on the // gateway's word that it was not captured; anything unknowable // stays frozen and the reconciliation sweep owns it. - if ($gateway === null) { + $cart = Cart::query()->find((int) $session->cart_reference); + + if ($gateway === null || $cart === null) { return 'unconfirmed'; } try { - $status = $gateway->fetchIntent($reference); + $status = $gateway->fetchIntent($cart, $reference)?->status; } catch (PaymentIntentException) { return 'unconfirmed'; } + if ($status === null) { + return 'unconfirmed'; + } + if (in_array($status, [PaymentIntentStatus::Captured, PaymentIntentStatus::RequiresCapture], true)) { // An authorise-only hold at RequiresCapture is not money // moved: the customer may keep editing and re-confirm, so // reopen with the hold intact instead of forcing completion. if (! ($session->isHoldMode() && $status === PaymentIntentStatus::RequiresCapture)) { - return $this->completeOrRefund($session, $gateway, $reference, $status); + return $this->completeOrRefund($session, $gateway, $cart, $reference, $status); } } } @@ -134,7 +146,8 @@ public function release(CheckoutSession $session): string */ private function completeOrRefund( CheckoutSession $session, - SupportsPaymentIntents $gateway, + ReconcilesPaymentIntents $gateway, + Cart $cart, string $reference, PaymentIntentStatus $status, ): string { @@ -182,7 +195,7 @@ private function completeOrRefund( } } - return $this->moneyBack($session, $gateway, $reference, $holdCaptured || $status === PaymentIntentStatus::Captured); + return $this->moneyBack($session, $gateway, $cart, $reference, $holdCaptured || $status === PaymentIntentStatus::Captured); } /** @@ -195,11 +208,12 @@ private function completeOrRefund( */ private function moneyBack( CheckoutSession $session, - SupportsPaymentIntents $gateway, + ReconcilesPaymentIntents $gateway, + Cart $cart, string $reference, bool $captured, ): string { - [$outcome, $event] = $session->getConnection()->transaction(function () use ($session, $gateway, $reference, $captured): array { + [$outcome, $event] = $session->getConnection()->transaction(function () use ($session, $gateway, $cart, $reference, $captured): array { $locked = CheckoutSession::query()->whereKey($session->getKey())->lockForUpdate()->firstOrFail(); if ($locked->status instanceof Completed) { @@ -233,7 +247,7 @@ private function moneyBack( // misconfiguration); voiding is still the safe answer. if (! $captured) { try { - $gateway->voidIntent($reference); + $gateway->voidIntent($cart, $reference); } catch (PaymentIntentException) { return ['void-failed', new CheckoutCompletionFailed($session, 'void-failed')]; } @@ -246,8 +260,9 @@ private function moneyBack( try { $refund = $gateway->refundIntent( + $cart, $reference, - $session->amount_total, + $this->pinnedAmount($session, $cart), 'lunar-checkout-refund:'.$reference, ); } catch (PaymentIntentException) { @@ -275,14 +290,15 @@ private function moneyBack( private function resolveByOperator( CheckoutSession $session, - ?SupportsPaymentIntents $gateway, + ?ReconcilesPaymentIntents $gateway, + ?Cart $cart, ?string $reference, string $resolve, ): string { return match ($resolve) { 'complete' => $this->completeForOperator($session), - 'refund' => $gateway !== null && $reference !== null - ? $this->completeOrRefundByForce($session, $gateway, $reference) + 'refund' => $gateway !== null && $cart !== null && $reference !== null + ? $this->completeOrRefundByForce($session, $gateway, $cart, $reference) : 'refund-failed', 'cancel' => $this->cancelForOperator($session), default => throw new \InvalidArgumentException("Unknown resolution [{$resolve}]."), @@ -302,12 +318,14 @@ private function completeForOperator(CheckoutSession $session): string */ private function completeOrRefundByForce( CheckoutSession $session, - SupportsPaymentIntents $gateway, + ReconcilesPaymentIntents $gateway, + Cart $cart, string $reference, ): string { $refund = $gateway->refundIntent( + $cart, $reference, - $session->amount_total, + $this->pinnedAmount($session, $cart), 'lunar-checkout-refund:'.$reference, ); @@ -370,6 +388,11 @@ private function reopenKeepingIntent(CheckoutSession $session, string $reason): return $reason; } + private function pinnedAmount(CheckoutSession $session, Cart $cart): PriceValue + { + return new PriceValue((int) $session->amount_total, $cart->currency); + } + private function recordAttempt(CheckoutSession $session): string { $maxAttempts = (int) config('lunar.checkout.reconciliation.max_attempts', 5); diff --git a/src/Http/Controllers/CheckoutController.php b/src/Http/Controllers/CheckoutController.php index 42cc549..e837774 100644 --- a/src/Http/Controllers/CheckoutController.php +++ b/src/Http/Controllers/CheckoutController.php @@ -42,8 +42,8 @@ use Lunar\Checkout\States\CheckoutSession\PaymentProcessing; use Lunar\Checkout\Support\PickupPoints; use Lunar\Core\Contracts\CreatesPaymentIntents; +use Lunar\Core\Contracts\ReconcilesPaymentIntents; use Lunar\Core\Contracts\SupportsPaymentHolds; -use Lunar\Core\Contracts\SupportsPaymentIntents; use Lunar\Core\Contracts\SyncsPaymentIntents; use Lunar\Core\DataObjects\HoldDescription; use Lunar\Core\Enums\HoldAdjustment; @@ -1013,9 +1013,9 @@ public function storePaymentIntent(Request $request, CheckoutSessionModel $sessi // Re-authorisation (payment change, or a hold the rail could not // stretch): release the old hold FIRST, so the customer is never // double-held. A void the gateway cannot confirm aborts the renewal. - if ($holdMode && ($data['renew'] ?? false) && $session->payment_intent_ref !== null && $gateway instanceof SupportsPaymentIntents) { + if ($holdMode && ($data['renew'] ?? false) && $session->payment_intent_ref !== null && $gateway instanceof ReconcilesPaymentIntents) { try { - $gateway->voidIntent($session->payment_intent_ref); + $gateway->voidIntent($cart, $session->payment_intent_ref); } catch (\Throwable $e) { report($e); @@ -1041,9 +1041,9 @@ public function storePaymentIntent(Request $request, CheckoutSessionModel $sessi if (! $holdMode && $session->isHoldMode() && $session->payment_intent_ref !== null) { $previousGateway = Payments::driver((string) ($session->meta['payment_method'] ?? '')); - if ($previousGateway instanceof SupportsPaymentIntents) { + if ($previousGateway instanceof ReconcilesPaymentIntents) { try { - $previousGateway->voidIntent($session->payment_intent_ref); + $previousGateway->voidIntent($cart, $session->payment_intent_ref); } catch (\Throwable $e) { report($e); @@ -1219,9 +1219,9 @@ public function pay(Request $request, CheckoutSessionModel $session, CheckoutDri if ($session->isHoldMode() && $session->payment_intent_ref !== null) { $holdGateway = Payments::driver((string) ($session->meta['payment_method'] ?? '')); - if ($holdGateway instanceof SupportsPaymentIntents) { + if ($holdGateway instanceof ReconcilesPaymentIntents) { try { - $holdGateway->voidIntent($session->payment_intent_ref); + $holdGateway->voidIntent($cart, $session->payment_intent_ref); } catch (\Throwable $e) { report($e); } diff --git a/src/Support/PaymentIntentGateway.php b/src/Support/PaymentIntentGateway.php index 55812c7..429f426 100644 --- a/src/Support/PaymentIntentGateway.php +++ b/src/Support/PaymentIntentGateway.php @@ -3,12 +3,12 @@ namespace Lunar\Checkout\Support; use Lunar\Checkout\Models\CheckoutSession; -use Lunar\Core\Contracts\SupportsPaymentIntents; +use Lunar\Core\Contracts\ReconcilesPaymentIntents; use Lunar\Core\Managers\PaymentManager; /** * Resolves the gateway driver behind a session's in-flight intent, when that - * driver opted into the {@see SupportsPaymentIntents} capability. The payment + * driver opted into the {@see ReconcilesPaymentIntents} capability. The payment * method handle is recorded on `meta.payment_method` when the intent is * created. Null means the intent's outcome cannot be confirmed — callers treat * that as "unabortable" and leave the session for reconciliation (0010 §F). @@ -19,7 +19,7 @@ public function __construct( private PaymentManager $payments, ) {} - public function for(CheckoutSession $session): ?SupportsPaymentIntents + public function for(CheckoutSession $session): ?ReconcilesPaymentIntents { $handle = $session->meta['payment_method'] ?? null; @@ -33,6 +33,6 @@ public function for(CheckoutSession $session): ?SupportsPaymentIntents return null; } - return $driver instanceof SupportsPaymentIntents ? $driver : null; + return $driver instanceof ReconcilesPaymentIntents ? $driver : null; } } diff --git a/tests/Feature/CheckoutErrorContractTest.php b/tests/Feature/CheckoutErrorContractTest.php index 2d2b513..e51b2af 100644 --- a/tests/Feature/CheckoutErrorContractTest.php +++ b/tests/Feature/CheckoutErrorContractTest.php @@ -17,6 +17,7 @@ use Lunar\Tests\Checkout\Stubs\User; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; +use Lunar\Tests\Checkout\Utils\WithoutIntentReconciliation; uses(TestCase::class, RefreshDatabase::class); @@ -135,6 +136,8 @@ */ class FailingIntentGateway extends OfflinePayment implements CreatesPaymentIntents { + use WithoutIntentReconciliation; + public function createIntent(Cart $cart): PaymentIntentDescriptor { throw new RuntimeException('The amount must be greater than or equal to the minimum charge amount. See https://gateway.docs/internal'); diff --git a/tests/Feature/CompletionFailureRefundTest.php b/tests/Feature/CompletionFailureRefundTest.php index e092317..0a10ada 100644 --- a/tests/Feature/CompletionFailureRefundTest.php +++ b/tests/Feature/CompletionFailureRefundTest.php @@ -16,9 +16,10 @@ use Lunar\Checkout\States\CheckoutSession\Open; use Lunar\Checkout\States\CheckoutSession\PaymentProcessing; use Lunar\Core\Contracts\CreatesPaymentIntents; -use Lunar\Core\Contracts\SupportsPaymentIntents; use Lunar\Core\DataObjects\PaymentIntentDescriptor; +use Lunar\Core\DataObjects\PaymentIntentSnapshot; use Lunar\Core\DataObjects\PaymentRefund; +use Lunar\Core\DataObjects\PriceValue; use Lunar\Core\Enums\PaymentIntentStatus; use Lunar\Core\Exceptions\PaymentIntentException; use Lunar\Core\Facades\CartSession; @@ -28,10 +29,11 @@ use Lunar\Core\PaymentTypes\OfflinePayment; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; +use Lunar\Tests\Checkout\Utils\FakeIntents; uses(TestCase::class, RefreshDatabase::class); -class CapturedIntentGateway extends OfflinePayment implements CreatesPaymentIntents, SupportsPaymentIntents +class CapturedIntentGateway extends OfflinePayment implements CreatesPaymentIntents { /** @var array */ public static array $refunds = []; @@ -43,20 +45,20 @@ public function createIntent(Cart $cart): PaymentIntentDescriptor return new PaymentIntentDescriptor('pi_captured_'.$cart->id); } - public function fetchIntent(string $reference): PaymentIntentStatus + public function fetchIntent(Cart $cart, string $reference): ?PaymentIntentSnapshot { - return PaymentIntentStatus::Captured; + return FakeIntents::snapshot($cart, PaymentIntentStatus::Captured); } - public function voidIntent(string $reference): void {} + public function voidIntent(Cart $cart, string $reference): void {} - public function refundIntent(string $reference, int $amountMinor, string $idempotencyKey): PaymentRefund + public function refundIntent(Cart $cart, string $reference, PriceValue $amount, string $idempotencyKey): PaymentRefund { if (static::$refundFails) { throw new PaymentIntentException('gateway refund failed'); } - static::$refunds[] = ['reference' => $reference, 'amount' => $amountMinor]; + static::$refunds[] = ['reference' => $reference, 'amount' => $amount->value]; return new PaymentRefund(success: true, reference: 'refund_'.$reference); } diff --git a/tests/Feature/DraftOrderAtPayGateTest.php b/tests/Feature/DraftOrderAtPayGateTest.php index e278aca..4f9f7de 100644 --- a/tests/Feature/DraftOrderAtPayGateTest.php +++ b/tests/Feature/DraftOrderAtPayGateTest.php @@ -15,10 +15,11 @@ use Lunar\Checkout\States\CheckoutSession\Open; use Lunar\Checkout\States\CheckoutSession\PaymentProcessing; use Lunar\Core\Contracts\CreatesPaymentIntents; -use Lunar\Core\Contracts\SupportsPaymentIntents; use Lunar\Core\DataObjects\PaymentAuthorize; use Lunar\Core\DataObjects\PaymentIntentDescriptor; +use Lunar\Core\DataObjects\PaymentIntentSnapshot; use Lunar\Core\DataObjects\PaymentRefund; +use Lunar\Core\DataObjects\PriceValue; use Lunar\Core\Enums\PaymentIntentStatus; use Lunar\Core\Facades\CartSession; use Lunar\Core\Facades\Payments; @@ -27,6 +28,7 @@ use Lunar\Core\PaymentTypes\OfflinePayment; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; +use Lunar\Tests\Checkout\Utils\FakeIntents; uses(TestCase::class, RefreshDatabase::class); @@ -34,7 +36,7 @@ * A card gateway that records captured money as a Transaction row on the * order it authorises against, the way Stripe's UpdateOrderFromIntent does. */ -class DraftAtPinGateway extends OfflinePayment implements CreatesPaymentIntents, SupportsPaymentIntents +class DraftAtPinGateway extends OfflinePayment implements CreatesPaymentIntents { /** @var array */ public static array $refunds = []; @@ -44,14 +46,14 @@ public function createIntent(Cart $cart): PaymentIntentDescriptor return new PaymentIntentDescriptor('pi_draft_'.$cart->id); } - public function fetchIntent(string $reference): PaymentIntentStatus + public function fetchIntent(Cart $cart, string $reference): ?PaymentIntentSnapshot { - return PaymentIntentStatus::Captured; + return FakeIntents::snapshot($cart, PaymentIntentStatus::Captured); } - public function voidIntent(string $reference): void {} + public function voidIntent(Cart $cart, string $reference): void {} - public function refundIntent(string $reference, int $amountMinor, string $idempotencyKey): PaymentRefund + public function refundIntent(Cart $cart, string $reference, PriceValue $amount, string $idempotencyKey): PaymentRefund { static::$refunds[] = $reference; diff --git a/tests/Feature/PayBoundaryTest.php b/tests/Feature/PayBoundaryTest.php index 42cd038..4043f29 100644 --- a/tests/Feature/PayBoundaryTest.php +++ b/tests/Feature/PayBoundaryTest.php @@ -11,12 +11,14 @@ use Lunar\Checkout\States\CheckoutSession\Open; use Lunar\Checkout\States\CheckoutSession\PaymentProcessing; use Lunar\Core\Contracts\SyncsPaymentIntents; +use Lunar\Core\DataObjects\PaymentIntentDescriptor; use Lunar\Core\Facades\Payments; use Lunar\Core\Models\Cart; use Lunar\Core\Models\Order; use Lunar\Core\PaymentTypes\OfflinePayment; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; +use Lunar\Tests\Checkout\Utils\WithoutIntentReconciliation; uses(TestCase::class, RefreshDatabase::class); @@ -90,8 +92,15 @@ public function requiresIntent(): bool */ class SyncingTestGateway extends OfflinePayment implements SyncsPaymentIntents { + use WithoutIntentReconciliation; + public static ?int $syncedAmount = null; + public function createIntent(Cart $cart): PaymentIntentDescriptor + { + return new PaymentIntentDescriptor('pi_sync_'.$cart->id); + } + public function syncIntent(Cart $cart): void { static::$syncedAmount = $cart->calculate()->total->value; diff --git a/tests/Feature/PaymentIntentReuseTest.php b/tests/Feature/PaymentIntentReuseTest.php index c18af72..d9ee52e 100644 --- a/tests/Feature/PaymentIntentReuseTest.php +++ b/tests/Feature/PaymentIntentReuseTest.php @@ -14,6 +14,7 @@ use Lunar\Core\PaymentTypes\OfflinePayment; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; +use Lunar\Tests\Checkout\Utils\WithoutIntentReconciliation; uses(TestCase::class, RefreshDatabase::class); @@ -23,6 +24,8 @@ */ class ReusedIntentGateway extends OfflinePayment implements CreatesPaymentIntents { + use WithoutIntentReconciliation; + public function createIntent(Cart $cart): PaymentIntentDescriptor { return new PaymentIntentDescriptor('pi_reused_'.$cart->id, 'secret_'.$cart->id); diff --git a/tests/Feature/PaymentRecordingTest.php b/tests/Feature/PaymentRecordingTest.php index d339ee3..f6f0b8b 100644 --- a/tests/Feature/PaymentRecordingTest.php +++ b/tests/Feature/PaymentRecordingTest.php @@ -9,10 +9,11 @@ use Lunar\Checkout\States\CheckoutSession\Completed; use Lunar\Checkout\States\CheckoutSession\PaymentProcessing; use Lunar\Core\Contracts\CreatesPaymentIntents; -use Lunar\Core\Contracts\SupportsPaymentIntents; use Lunar\Core\DataObjects\PaymentAuthorize; use Lunar\Core\DataObjects\PaymentIntentDescriptor; +use Lunar\Core\DataObjects\PaymentIntentSnapshot; use Lunar\Core\DataObjects\PaymentRefund; +use Lunar\Core\DataObjects\PriceValue; use Lunar\Core\Enums\PaymentIntentStatus; use Lunar\Core\Facades\CartSession; use Lunar\Core\Facades\Payments; @@ -21,6 +22,7 @@ use Lunar\Core\PaymentTypes\OfflinePayment; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; +use Lunar\Tests\Checkout\Utils\FakeIntents; uses(TestCase::class, RefreshDatabase::class); @@ -31,7 +33,7 @@ * checkout driver ran the shared authorize() path itself (spec 0002 §E) * instead of leaving it to a webhook. */ -class RecordingGateway extends OfflinePayment implements CreatesPaymentIntents, SupportsPaymentIntents +class RecordingGateway extends OfflinePayment implements CreatesPaymentIntents { /** @var array}> */ public static array $authorizeCalls = []; @@ -43,14 +45,14 @@ public function createIntent(Cart $cart): PaymentIntentDescriptor return new PaymentIntentDescriptor('pi_recording_'.$cart->id); } - public function fetchIntent(string $reference): PaymentIntentStatus + public function fetchIntent(Cart $cart, string $reference): ?PaymentIntentSnapshot { - return PaymentIntentStatus::Captured; + return FakeIntents::snapshot($cart, PaymentIntentStatus::Captured); } - public function voidIntent(string $reference): void {} + public function voidIntent(Cart $cart, string $reference): void {} - public function refundIntent(string $reference, int $amountMinor, string $idempotencyKey): PaymentRefund + public function refundIntent(Cart $cart, string $reference, PriceValue $amount, string $idempotencyKey): PaymentRefund { return new PaymentRefund(success: true, reference: 'refund_'.$reference); } diff --git a/tests/Feature/PaymentReleaseTest.php b/tests/Feature/PaymentReleaseTest.php index 640b969..87620f6 100644 --- a/tests/Feature/PaymentReleaseTest.php +++ b/tests/Feature/PaymentReleaseTest.php @@ -1,18 +1,23 @@ */ + public static array $fetchedCartIds = []; + + public function fetchIntent(Cart $cart, string $reference): ?PaymentIntentSnapshot { + static::$fetchedCartIds[] = $cart->id; + if (static::$throwOnFetch) { throw new PaymentIntentException('gateway unreachable'); } - return static::$status; + return static::$status ? FakeIntents::snapshot($cart, static::$status) : null; } - public function voidIntent(string $reference): void {} + public function voidIntent(Cart $cart, string $reference): void {} - public function refundIntent(string $reference, int $amountMinor, string $idempotencyKey): PaymentRefund + public function refundIntent(Cart $cart, string $reference, PriceValue $amount, string $idempotencyKey): PaymentRefund { return new PaymentRefund(success: true, reference: 're_test'); } @@ -59,8 +70,32 @@ function pinnedSession(array $overrides = []) beforeEach(function () { Payments::extend('release-test', fn () => app(ReleaseTestGateway::class)); - ReleaseTestGateway::$status = PaymentIntentStatus::Pending; + ReleaseTestGateway::$status = PaymentIntentStatus::Processing; ReleaseTestGateway::$throwOnFetch = false; + ReleaseTestGateway::$fetchedCartIds = []; +}); + +it('counts an attempt when the gateway did not create the reference for the cart', function () { + ReleaseTestGateway::$status = null; + + $session = pinnedSession(); + + expect(app(ReconcilesCheckoutSession::class)->execute($session))->toBe('retry'); + + $session->refresh(); + + expect($session->status)->toBeInstanceOf(PaymentProcessing::class) + ->and($session->reconciliation_attempts)->toBe(1); +}); + +it('counts an attempt without asking the gateway when the cart is gone', function () { + ReleaseTestGateway::$status = PaymentIntentStatus::Captured; + + $session = pinnedSession(['cart_reference' => '999999']); + + expect(app(ReconcilesCheckoutSession::class)->execute($session))->toBe('retry') + ->and($session->refresh()->reconciliation_attempts)->toBe(1) + ->and(ReleaseTestGateway::$fetchedCartIds)->toBeEmpty(); }); it('reopens a pinned session when the gateway holds no captured money', function () { @@ -107,6 +142,19 @@ function pinnedSession(array $overrides = []) expect($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class); }); +it('stays frozen when the gateway did not create the reference for the cart', function () { + ReleaseTestGateway::$status = null; + + $session = pinnedSession(); + + $this->postJson(route('lunar.checkout.payment-release', $session->uuid)) + ->assertOk() + ->assertJsonPath('outcome', 'unconfirmed') + ->assertJsonPath('released', false); + + expect($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class); +}); + it('is a no-op on a session that is not pinned', function () { $session = CheckoutCart::session(CheckoutCart::orderable()); @@ -209,7 +257,7 @@ function pinnedSession(array $overrides = []) }); it('processing renders the polling page while the outcome is in flight', function () { - ReleaseTestGateway::$status = PaymentIntentStatus::Pending; + ReleaseTestGateway::$status = PaymentIntentStatus::Processing; $session = pinnedSession(); @@ -222,7 +270,7 @@ function pinnedSession(array $overrides = []) }); it('processing shows the same merchant name as the checkout', function () { - ReleaseTestGateway::$status = PaymentIntentStatus::Pending; + ReleaseTestGateway::$status = PaymentIntentStatus::Processing; config(['lunar.checkout.merchant' => 'Edwardes Bros', 'app.name' => 'Lunar Store']); $session = pinnedSession(); diff --git a/tests/Feature/WebhookFirstPlacementTest.php b/tests/Feature/WebhookFirstPlacementTest.php index 52c5988..f483479 100644 --- a/tests/Feature/WebhookFirstPlacementTest.php +++ b/tests/Feature/WebhookFirstPlacementTest.php @@ -23,12 +23,15 @@ use Lunar\Core\PaymentTypes\OfflinePayment; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; +use Lunar\Tests\Checkout\Utils\WithoutIntentReconciliation; uses(TestCase::class, RefreshDatabase::class); /** A Stripe-like gateway: the browser gets an intent it can confirm directly. */ class WebhookFirstIntentGateway extends OfflinePayment implements CreatesPaymentIntents { + use WithoutIntentReconciliation; + public function createIntent(Cart $cart): PaymentIntentDescriptor { return new PaymentIntentDescriptor('pi_webhook_first_'.$cart->id, 'secret_'.$cart->id); diff --git a/tests/Utils/FakeIntents.php b/tests/Utils/FakeIntents.php new file mode 100644 index 0000000..ea527f4 --- /dev/null +++ b/tests/Utils/FakeIntents.php @@ -0,0 +1,24 @@ + new PriceValue($value, $cart->currency); + + return new PaymentIntentSnapshot( + status: $status, + amount: $price($amount), + captured: $price($status === PaymentIntentStatus::Captured ? $amount : 0), + refunded: $price(0), + walletLabel: $walletLabel, + ); + } +} diff --git a/tests/Utils/WithoutIntentReconciliation.php b/tests/Utils/WithoutIntentReconciliation.php new file mode 100644 index 0000000..c86cd31 --- /dev/null +++ b/tests/Utils/WithoutIntentReconciliation.php @@ -0,0 +1,31 @@ + Date: Thu, 12 Nov 2026 07:54:25 +0000 Subject: [PATCH 03/32] refactor(payments): treat RequiresAction and Processing intents as pending Core split PaymentIntentStatus::Pending into RequiresAction and Processing. Both keep the old Pending behaviour: reconcile answers `pending` and reschedules without consuming an attempt, release reopens the session with its intent intact, and the processing page keeps polling. --- src/Actions/ReconcileCheckoutSession.php | 8 +++--- tests/Feature/PaymentReleaseTest.php | 32 ++++++++++++++++++++---- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/src/Actions/ReconcileCheckoutSession.php b/src/Actions/ReconcileCheckoutSession.php index 9558182..0f12e67 100644 --- a/src/Actions/ReconcileCheckoutSession.php +++ b/src/Actions/ReconcileCheckoutSession.php @@ -72,9 +72,11 @@ public function execute(CheckoutSession $session, ?string $resolve = null): stri // Not an intent the gateway created for this cart: unknowable. null => $this->recordAttempt($session), - // Legitimately still in flight (slow methods) — reschedule - // without consuming an attempt (spec 0010 §F). - PaymentIntentStatus::Pending => 'pending', + // Legitimately still in flight (the customer has yet to act, or + // a slow method has yet to settle): reschedule without consuming + // an attempt (spec 0010 §F). + PaymentIntentStatus::RequiresAction, + PaymentIntentStatus::Processing => 'pending', PaymentIntentStatus::Captured, PaymentIntentStatus::RequiresCapture => $this->completeOrRefund($session, $gateway, $cart, $reference, $status), diff --git a/tests/Feature/PaymentReleaseTest.php b/tests/Feature/PaymentReleaseTest.php index 87620f6..fb7fd74 100644 --- a/tests/Feature/PaymentReleaseTest.php +++ b/tests/Feature/PaymentReleaseTest.php @@ -75,6 +75,26 @@ function pinnedSession(array $overrides = []) ReleaseTestGateway::$fetchedCartIds = []; }); +dataset('in-flight intent statuses', [ + 'waiting on the customer' => [PaymentIntentStatus::RequiresAction], + 'gateway still deciding' => [PaymentIntentStatus::Processing], +]); + +it('reconciles an in-flight intent to pending without consuming an attempt', function (PaymentIntentStatus $status) { + ReleaseTestGateway::$status = $status; + + $session = pinnedSession(); + + expect(app(ReconcilesCheckoutSession::class)->execute($session))->toBe('pending'); + + $session->refresh(); + + expect($session->status)->toBeInstanceOf(PaymentProcessing::class) + ->and($session->reconciliation_attempts)->toBe(0) + ->and($session->payment_intent_ref)->toBe('pi_test_123') + ->and(ReleaseTestGateway::$fetchedCartIds)->toBe([(int) $session->cart_reference]); +})->with('in-flight intent statuses'); + it('counts an attempt when the gateway did not create the reference for the cart', function () { ReleaseTestGateway::$status = null; @@ -98,7 +118,9 @@ function pinnedSession(array $overrides = []) ->and(ReleaseTestGateway::$fetchedCartIds)->toBeEmpty(); }); -it('reopens a pinned session when the gateway holds no captured money', function () { +it('reopens a pinned session when the gateway holds no captured money', function (PaymentIntentStatus $status) { + ReleaseTestGateway::$status = $status; + $session = pinnedSession(); $this->postJson(route('lunar.checkout.payment-release', $session->uuid)) @@ -113,7 +135,7 @@ function pinnedSession(array $overrides = []) // payment element is still bound to it. expect($session->status)->toBeInstanceOf(Open::class) ->and($session->payment_intent_ref)->toBe('pi_test_123'); -}); +})->with('in-flight intent statuses'); it('completes instead of releasing when the money was captured', function () { ReleaseTestGateway::$status = PaymentIntentStatus::Captured; @@ -256,8 +278,8 @@ function pinnedSession(array $overrides = []) expect($session->refresh()->status)->toBeInstanceOf(Open::class); }); -it('processing renders the polling page while the outcome is in flight', function () { - ReleaseTestGateway::$status = PaymentIntentStatus::Processing; +it('processing renders the polling page while the outcome is in flight', function (PaymentIntentStatus $status) { + ReleaseTestGateway::$status = $status; $session = pinnedSession(); @@ -267,7 +289,7 @@ function pinnedSession(array $overrides = []) ->assertJsonPath('props.pollUrl', route('lunar.checkout.processing', $session->uuid)); expect($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class); -}); +})->with('in-flight intent statuses'); it('processing shows the same merchant name as the checkout', function () { ReleaseTestGateway::$status = PaymentIntentStatus::Processing; From bbf7997d72f22985041ce86aa38f28d827673db1 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 07:54:25 +0000 Subject: [PATCH 04/32] refactor(payments): read the client secret from the intent's client payload PaymentIntentDescriptor dropped `clientSecret` for an opaque `clientPayload`. The payment-intent response keeps its `clientSecret` key, which the Stripe components and the host apps read, and fills it from `clientPayload['client_secret']`. Two test gateways passed the secret as the second positional argument, which now binds to `redirectUrl`. They use the named argument, and a test asserts the response carries the payload's secret. --- src/Http/Controllers/CheckoutController.php | 2 +- tests/Feature/PaymentIntentReuseTest.php | 17 ++++++++++++++++- tests/Feature/WebhookFirstPlacementTest.php | 2 +- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/Http/Controllers/CheckoutController.php b/src/Http/Controllers/CheckoutController.php index e837774..a6eb033 100644 --- a/src/Http/Controllers/CheckoutController.php +++ b/src/Http/Controllers/CheckoutController.php @@ -1116,7 +1116,7 @@ public function storePaymentIntent(Request $request, CheckoutSessionModel $sessi return response()->json([ 'intent' => $descriptor->reference, - 'clientSecret' => $descriptor->clientSecret, + 'clientSecret' => $descriptor->clientPayload['client_secret'] ?? null, ]); } diff --git a/tests/Feature/PaymentIntentReuseTest.php b/tests/Feature/PaymentIntentReuseTest.php index d9ee52e..998afab 100644 --- a/tests/Feature/PaymentIntentReuseTest.php +++ b/tests/Feature/PaymentIntentReuseTest.php @@ -28,7 +28,7 @@ class ReusedIntentGateway extends OfflinePayment implements CreatesPaymentIntent public function createIntent(Cart $cart): PaymentIntentDescriptor { - return new PaymentIntentDescriptor('pi_reused_'.$cart->id, 'secret_'.$cart->id); + return new PaymentIntentDescriptor('pi_reused_'.$cart->id, clientPayload: ['client_secret' => 'secret_'.$cart->id]); } } @@ -66,6 +66,21 @@ function registerReusedIntentGateway(): void app(PaymentMethodRegistry::class)->add(ReusedIntentMethod::class); } +it('hands the browser the intent reference and the client secret from the gateway payload', function () { + registerReusedIntentGateway(); + + $cart = CheckoutCart::orderable(); + CartSession::use($cart); + $session = CheckoutCart::session($cart); + + $this->postJson(route('lunar.checkout.payment-intent.store', $session->uuid), [ + 'payment_method' => 'reused-card', + ])->assertOk()->assertExactJson([ + 'intent' => 'pi_reused_'.$cart->id, + 'clientSecret' => 'secret_'.$cart->id, + ]); +}); + it('lets a successor session take over the intent reference a dead session still holds', function () { registerReusedIntentGateway(); diff --git a/tests/Feature/WebhookFirstPlacementTest.php b/tests/Feature/WebhookFirstPlacementTest.php index f483479..5d83403 100644 --- a/tests/Feature/WebhookFirstPlacementTest.php +++ b/tests/Feature/WebhookFirstPlacementTest.php @@ -34,7 +34,7 @@ class WebhookFirstIntentGateway extends OfflinePayment implements CreatesPayment public function createIntent(Cart $cart): PaymentIntentDescriptor { - return new PaymentIntentDescriptor('pi_webhook_first_'.$cart->id, 'secret_'.$cart->id); + return new PaymentIntentDescriptor('pi_webhook_first_'.$cart->id, clientPayload: ['client_secret' => 'secret_'.$cart->id]); } } From 0dfd7124a581aa3169a1b574b9d749af205e8090 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 07:54:26 +0000 Subject: [PATCH 05/32] refactor(payments): verify and adjust holds through the intent snapshot Core removed describeHold() and HoldDescription. The confirm page now verifies a hold with fetchIntent() and reads the authorised amount and wallet label from the snapshot. adjustHold() and captureHold() take the Cart and a PriceValue in the cart's currency. NeedsReauthorization still rejects the pay attempt with `hold_reauthorization_required` while the session stays Open. --- src/Actions/ReconcileCheckoutSession.php | 2 +- src/Http/Controllers/CheckoutController.php | 23 ++--- tests/Feature/ConfirmPageTest.php | 33 ++++--- tests/Feature/ExpressCollectFlowTest.php | 24 ++--- tests/Feature/ExpressProjectionTest.php | 23 ++--- tests/Feature/PaymentHoldTest.php | 103 ++++++++++++-------- 6 files changed, 115 insertions(+), 93 deletions(-) diff --git a/src/Actions/ReconcileCheckoutSession.php b/src/Actions/ReconcileCheckoutSession.php index 0f12e67..4e8cc73 100644 --- a/src/Actions/ReconcileCheckoutSession.php +++ b/src/Actions/ReconcileCheckoutSession.php @@ -163,7 +163,7 @@ private function completeOrRefund( if ($session->isHoldMode() && $gateway instanceof SupportsPaymentHolds) { try { - $gateway->captureHold($reference, (int) $session->amount_total); + $gateway->captureHold($cart, $reference, $this->pinnedAmount($session, $cart)); $holdCaptured = true; } catch (PaymentIntentException $e) { report($e); diff --git a/src/Http/Controllers/CheckoutController.php b/src/Http/Controllers/CheckoutController.php index a6eb033..4f7062f 100644 --- a/src/Http/Controllers/CheckoutController.php +++ b/src/Http/Controllers/CheckoutController.php @@ -45,7 +45,8 @@ use Lunar\Core\Contracts\ReconcilesPaymentIntents; use Lunar\Core\Contracts\SupportsPaymentHolds; use Lunar\Core\Contracts\SyncsPaymentIntents; -use Lunar\Core\DataObjects\HoldDescription; +use Lunar\Core\DataObjects\PaymentIntentSnapshot; +use Lunar\Core\DataObjects\PriceValue; use Lunar\Core\Enums\HoldAdjustment; use Lunar\Core\Enums\PaymentIntentStatus; use Lunar\Core\Facades\CartSession; @@ -288,7 +289,7 @@ public function confirm(CheckoutSessionModel $session, CheckoutDriver $checkoutD [ 'elements' => $this->projectElements($session), 'hold' => [ - 'amountAuthorised' => $hold->amountMinor, + 'amountAuthorised' => $hold->amount->value, 'walletLabel' => $hold->walletLabel, ], ], @@ -312,27 +313,28 @@ public function confirm(CheckoutSessionModel $session, CheckoutDriver $checkoutD * in this controller: a session whose window has closed but whose row * has not yet been transitioned still reads `Open` and must not render. */ - private function liveHold(CheckoutSessionModel $session): ?HoldDescription + private function liveHold(CheckoutSessionModel $session): ?PaymentIntentSnapshot { if (! $session->status instanceof Open || $session->isExpired() || ! $session->isHoldMode() || $session->payment_intent_ref === null) { return null; } $gateway = Payments::driver((string) ($session->meta['payment_method'] ?? '')); + $cart = Cart::query()->find((int) $session->cart_reference); - if (! $gateway instanceof SupportsPaymentHolds) { + if (! $gateway instanceof SupportsPaymentHolds || $cart === null) { return null; } try { - $description = $gateway->describeHold($session->payment_intent_ref); + $snapshot = $gateway->fetchIntent($cart, $session->payment_intent_ref); } catch (\Throwable $e) { report($e); return null; } - return $description?->status === PaymentIntentStatus::RequiresCapture ? $description : null; + return $snapshot?->status === PaymentIntentStatus::RequiresCapture ? $snapshot : null; } /** @@ -1162,17 +1164,16 @@ public function pay(Request $request, CheckoutSessionModel $session, CheckoutDri * customer is looking at BEFORE the pin, so a fingerprint rejection * costs nothing and a confirmed charge is never the stale figure. * - * A confirmed hold cannot be synced like an unconfirmed intent - * (Task 3 unit note: `$amountTotal` is Lunar minor units, equal to - * Stripe's for GBP): it stretches (incremental authorization) or it - * does not, so hold-mode sessions branch to adjustHold() instead of + * A confirmed hold cannot be synced like an unconfirmed intent: it + * stretches (incremental authorization) or it does not, so hold-mode + * sessions branch to adjustHold() instead of * SyncsPaymentIntents::syncIntent(). */ if ($method->requiresIntent() && $amountTotal > 0) { $gateway = Payments::driver($method->driver()); if ($session->isHoldMode() && $gateway instanceof SupportsPaymentHolds && $session->payment_intent_ref !== null) { - $adjustment = $gateway->adjustHold($session->payment_intent_ref, $amountTotal); + $adjustment = $gateway->adjustHold($cart, $session->payment_intent_ref, new PriceValue($amountTotal, $cart->currency)); if ($adjustment === HoldAdjustment::NeedsReauthorization) { // Session still Open: nothing to unpin. The client diff --git a/tests/Feature/ConfirmPageTest.php b/tests/Feature/ConfirmPageTest.php index 70c17af..0a00756 100644 --- a/tests/Feature/ConfirmPageTest.php +++ b/tests/Feature/ConfirmPageTest.php @@ -2,7 +2,6 @@ use Illuminate\Foundation\Testing\RefreshDatabase; use Lunar\Checkout\Models\CheckoutSession; -use Lunar\Core\DataObjects\HoldDescription; use Lunar\Core\Enums\PaymentIntentStatus; use Lunar\Core\Facades\CartSession; use Lunar\Tests\Checkout\TestCase; @@ -11,7 +10,10 @@ uses(TestCase::class, RefreshDatabase::class); beforeEach(function () { - FakeHoldGateway::$describeOutcome = null; + FakeHoldGateway::$fetchStatus = PaymentIntentStatus::RequiresCapture; + FakeHoldGateway::$fetchScript = []; + FakeHoldGateway::$holdAmount = 0; + FakeHoldGateway::$walletLabel = null; }); /** @@ -68,11 +70,8 @@ function mintOpenSessionWithStandardIntent(): CheckoutSession it('renders the confirm page for a session with a live hold', function () { $session = mintOpenHoldSession(); - FakeHoldGateway::$describeOutcome = new HoldDescription( - status: PaymentIntentStatus::RequiresCapture, - amountMinor: 2000, - walletLabel: 'Apple Pay', - ); + FakeHoldGateway::$holdAmount = 2000; + FakeHoldGateway::$walletLabel = 'Apple Pay'; $this->get(route('lunar.checkout.confirm', $session->uuid), ['X-Inertia' => 'true']) ->assertOk() @@ -97,9 +96,16 @@ function mintOpenSessionWithStandardIntent(): CheckoutSession it('redirects when the gateway does not verify requires-capture', function () { $session = mintOpenHoldSession(); - FakeHoldGateway::$describeOutcome = new HoldDescription( - status: PaymentIntentStatus::Voided, amountMinor: 2000, walletLabel: null, - ); + FakeHoldGateway::$fetchStatus = PaymentIntentStatus::Voided; + FakeHoldGateway::$holdAmount = 2000; + + $this->get(route('lunar.checkout.confirm', $session->uuid)) + ->assertRedirect(route('lunar.checkout.show', $session->uuid)); +}); + +it('redirects when the gateway did not create the hold for the cart', function () { + $session = mintOpenHoldSession(); + FakeHoldGateway::$fetchScript = [null]; $this->get(route('lunar.checkout.confirm', $session->uuid)) ->assertRedirect(route('lunar.checkout.show', $session->uuid)); @@ -107,11 +113,8 @@ function mintOpenSessionWithStandardIntent(): CheckoutSession it('redirects an unswept expired session even though its row still reads Open', function () { $session = mintOpenHoldSession(); - FakeHoldGateway::$describeOutcome = new HoldDescription( - status: PaymentIntentStatus::RequiresCapture, - amountMinor: 2000, - walletLabel: 'Apple Pay', - ); + FakeHoldGateway::$holdAmount = 2000; + FakeHoldGateway::$walletLabel = 'Apple Pay'; // Expiry is swept lazily: backdate expires_at directly, without // transitioning `status` away from Open, the way a real session sits diff --git a/tests/Feature/ExpressCollectFlowTest.php b/tests/Feature/ExpressCollectFlowTest.php index 6c78221..ff39b18 100644 --- a/tests/Feature/ExpressCollectFlowTest.php +++ b/tests/Feature/ExpressCollectFlowTest.php @@ -9,10 +9,10 @@ use Lunar\Checkout\States\CheckoutSession\Completed; use Lunar\Core\Contracts\CreatesPaymentIntents; use Lunar\Core\Contracts\SupportsPaymentHolds; -use Lunar\Core\Contracts\SupportsPaymentIntents; -use Lunar\Core\DataObjects\HoldDescription; use Lunar\Core\DataObjects\PaymentIntentDescriptor; +use Lunar\Core\DataObjects\PaymentIntentSnapshot; use Lunar\Core\DataObjects\PaymentRefund; +use Lunar\Core\DataObjects\PriceValue; use Lunar\Core\Enums\HoldAdjustment; use Lunar\Core\Enums\PaymentIntentStatus; use Lunar\Core\Facades\CartSession; @@ -22,6 +22,7 @@ use Lunar\Core\PaymentTypes\OfflinePayment; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; +use Lunar\Tests\Checkout\Utils\FakeIntents; use Lunar\Tests\Checkout\Utils\PickupPointsStub; uses(TestCase::class, RefreshDatabase::class); @@ -35,7 +36,7 @@ * cart gets is the wallet's billing address. Its own gateway and method * classes so nothing here collides with the other express suites'. */ -class CollectExpressGateway extends OfflinePayment implements CreatesPaymentIntents, SupportsPaymentHolds, SupportsPaymentIntents +class CollectExpressGateway extends OfflinePayment implements CreatesPaymentIntents, SupportsPaymentHolds { public function createHold(Cart $cart): PaymentIntentDescriptor { @@ -47,26 +48,21 @@ public function createIntent(Cart $cart): PaymentIntentDescriptor return new PaymentIntentDescriptor('pi_collect_'.$cart->id); } - public function describeHold(string $reference): ?HoldDescription - { - return null; - } - - public function adjustHold(string $reference, int $amountMinor): HoldAdjustment + public function adjustHold(Cart $cart, string $reference, PriceValue $amount): HoldAdjustment { return HoldAdjustment::Ok; } - public function captureHold(string $reference, int $amountMinor): void {} + public function captureHold(Cart $cart, string $reference, PriceValue $amount): void {} - public function fetchIntent(string $reference): PaymentIntentStatus + public function fetchIntent(Cart $cart, string $reference): ?PaymentIntentSnapshot { - return PaymentIntentStatus::RequiresCapture; + return FakeIntents::snapshot($cart, PaymentIntentStatus::RequiresCapture); } - public function voidIntent(string $reference): void {} + public function voidIntent(Cart $cart, string $reference): void {} - public function refundIntent(string $reference, int $amountMinor, string $idempotencyKey): PaymentRefund + public function refundIntent(Cart $cart, string $reference, PriceValue $amount, string $idempotencyKey): PaymentRefund { return new PaymentRefund(success: true, reference: 'refund_'.$reference); } diff --git a/tests/Feature/ExpressProjectionTest.php b/tests/Feature/ExpressProjectionTest.php index 3780876..b0dc554 100644 --- a/tests/Feature/ExpressProjectionTest.php +++ b/tests/Feature/ExpressProjectionTest.php @@ -7,9 +7,10 @@ use Lunar\Checkout\PaymentMethods\AbstractPaymentMethod; use Lunar\Core\Contracts\CreatesPaymentIntents; use Lunar\Core\Contracts\SupportsPaymentHolds; -use Lunar\Core\DataObjects\HoldDescription; use Lunar\Core\DataObjects\PaymentIntentDescriptor; +use Lunar\Core\DataObjects\PaymentIntentSnapshot; use Lunar\Core\DataObjects\PaymentRefund; +use Lunar\Core\DataObjects\PriceValue; use Lunar\Core\Enums\HoldAdjustment; use Lunar\Core\Enums\PaymentIntentStatus; use Lunar\Core\Facades\CartSession; @@ -18,6 +19,7 @@ use Lunar\Core\PaymentTypes\OfflinePayment; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; +use Lunar\Tests\Checkout\Utils\FakeIntents; uses(TestCase::class, RefreshDatabase::class); @@ -38,28 +40,23 @@ public function createIntent(Cart $cart): PaymentIntentDescriptor return new PaymentIntentDescriptor('pi_fake_'.$cart->id); } - public function describeHold(string $reference): ?HoldDescription - { - return null; - } - - public function adjustHold(string $reference, int $amountMinor): HoldAdjustment + public function adjustHold(Cart $cart, string $reference, PriceValue $amount): HoldAdjustment { return HoldAdjustment::Ok; } - public function captureHold(string $reference, int $amountMinor): void {} + public function captureHold(Cart $cart, string $reference, PriceValue $amount): void {} - // SupportsPaymentHolds extends SupportsPaymentIntents, so the release and + // SupportsPaymentHolds extends ReconcilesPaymentIntents, so the release and // reconciliation verbs come with it. - public function fetchIntent(string $reference): PaymentIntentStatus + public function fetchIntent(Cart $cart, string $reference): ?PaymentIntentSnapshot { - return PaymentIntentStatus::RequiresCapture; + return FakeIntents::snapshot($cart, PaymentIntentStatus::RequiresCapture); } - public function voidIntent(string $reference): void {} + public function voidIntent(Cart $cart, string $reference): void {} - public function refundIntent(string $reference, int $amountMinor, string $idempotencyKey): PaymentRefund + public function refundIntent(Cart $cart, string $reference, PriceValue $amount, string $idempotencyKey): PaymentRefund { return new PaymentRefund(success: true, reference: 'refund_express_'.$reference); } diff --git a/tests/Feature/PaymentHoldTest.php b/tests/Feature/PaymentHoldTest.php index 6ed8dce..ab7b7fb 100644 --- a/tests/Feature/PaymentHoldTest.php +++ b/tests/Feature/PaymentHoldTest.php @@ -2,6 +2,7 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Support\Arr; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\Exceptions; use Lunar\Checkout\Contracts\PaymentMethodRegistry; @@ -13,10 +14,10 @@ use Lunar\Checkout\States\CheckoutSession\PaymentProcessing; use Lunar\Core\Contracts\CreatesPaymentIntents; use Lunar\Core\Contracts\SupportsPaymentHolds; -use Lunar\Core\Contracts\SupportsPaymentIntents; -use Lunar\Core\DataObjects\HoldDescription; use Lunar\Core\DataObjects\PaymentIntentDescriptor; +use Lunar\Core\DataObjects\PaymentIntentSnapshot; use Lunar\Core\DataObjects\PaymentRefund; +use Lunar\Core\DataObjects\PriceValue; use Lunar\Core\Enums\HoldAdjustment; use Lunar\Core\Enums\PaymentIntentStatus; use Lunar\Core\Exceptions\PaymentIntentException; @@ -27,6 +28,7 @@ use Lunar\Core\PaymentTypes\OfflinePayment; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; +use Lunar\Tests\Checkout\Utils\FakeIntents; uses(TestCase::class, RefreshDatabase::class); @@ -37,7 +39,7 @@ * doesn't need to (it only asserts driver behaviour) but the hold-routing * assertions here do. */ -class FakeHoldGateway extends OfflinePayment implements CreatesPaymentIntents, SupportsPaymentHolds, SupportsPaymentIntents +class FakeHoldGateway extends OfflinePayment implements CreatesPaymentIntents, SupportsPaymentHolds { /** @var array */ public static array $createIntentCalls = []; @@ -48,10 +50,13 @@ class FakeHoldGateway extends OfflinePayment implements CreatesPaymentIntents, S /** @var array */ public static array $voidedReferences = []; - /** @var array}> */ + /** @var array */ + public static array $adjustCalls = []; + + /** @var array}> */ public static array $captureCalls = []; - /** @var array}> */ + /** @var array */ public static array $refundCalls = []; public static int $holdSequence = 0; @@ -65,11 +70,16 @@ class FakeHoldGateway extends OfflinePayment implements CreatesPaymentIntents, S public static bool $throwOnVoid = false; /** - * Verified against by the confirm-page guard: null (the default) means - * "gateway doesn't recognise this reference", exactly like a real driver - * would answer for a non-hold or unknown reference. + * Answers for successive fetches, taken ahead of `$fetchStatus`. Null is + * a reference the gateway did not create for the cart. + * + * @var array */ - public static ?HoldDescription $describeOutcome = null; + public static array $fetchScript = []; + + public static int $holdAmount = 0; + + public static ?string $walletLabel = null; public function createIntent(Cart $cart): PaymentIntentDescriptor { @@ -85,35 +95,41 @@ public function createHold(Cart $cart): PaymentIntentDescriptor return new PaymentIntentDescriptor('hold_fake_'.$cart->id.'_'.(++static::$holdSequence)); } - public function describeHold(string $reference): ?HoldDescription + public function adjustHold(Cart $cart, string $reference, PriceValue $amount): HoldAdjustment { - return static::$describeOutcome; - } + static::$adjustCalls[] = [ + 'cart' => $cart->id, + 'reference' => $reference, + 'amount' => $amount->value, + 'currency' => $amount->resolveCurrency()->code, + ]; - public function adjustHold(string $reference, int $amountMinor): HoldAdjustment - { return static::$adjustOutcome; } - public function captureHold(string $reference, int $amountMinor): void + public function captureHold(Cart $cart, string $reference, PriceValue $amount): void { if (static::$throwOnCapture) { throw new PaymentIntentException('fake gateway capture failed'); } static::$captureCalls[] = [ + 'cart' => $cart->id, 'reference' => $reference, - 'amount' => $amountMinor, + 'amount' => $amount->value, + 'currency' => $amount->resolveCurrency()->code, 'unplaced_orders' => Order::query()->whereNull('placed_at')->pluck('id')->all(), ]; } - public function fetchIntent(string $reference): PaymentIntentStatus + public function fetchIntent(Cart $cart, string $reference): ?PaymentIntentSnapshot { - return static::$fetchStatus; + $status = static::$fetchScript === [] ? static::$fetchStatus : array_shift(static::$fetchScript); + + return $status ? FakeIntents::snapshot($cart, $status, static::$holdAmount, static::$walletLabel) : null; } - public function voidIntent(string $reference): void + public function voidIntent(Cart $cart, string $reference): void { if (static::$throwOnVoid) { throw new PaymentIntentException('fake gateway void failed'); @@ -122,9 +138,9 @@ public function voidIntent(string $reference): void static::$voidedReferences[] = $reference; } - public function refundIntent(string $reference, int $amountMinor, string $idempotencyKey): PaymentRefund + public function refundIntent(Cart $cart, string $reference, PriceValue $amount, string $idempotencyKey): PaymentRefund { - static::$refundCalls[] = ['reference' => $reference, 'amount' => $amountMinor]; + static::$refundCalls[] = ['reference' => $reference, 'amount' => $amount->value]; return new PaymentRefund(success: true, reference: 'refund_fake_'.$reference); } @@ -132,19 +148,18 @@ public function refundIntent(string $reference, int $amountMinor, string $idempo /** * A gateway that can only create standard intents, no hold capability, the - * way most drivers will stay. Also implements {@see SupportsPaymentIntents} - * (fetch/void/refund) so it doubles as the "hold mode flagged on a session + * way most drivers will stay. Its fetch/void/refund double as the "hold mode flagged on a session * whose driver never actually supports holds" misconfiguration fixture: a * hold-mode session pinned against this gateway reaches completeOrRefund() * with an intent-capable-but-not-hold-capable driver, exercising the flavour * branch that must void rather than refund an uncaptured hold. */ -class IntentOnlyGateway extends OfflinePayment implements CreatesPaymentIntents, SupportsPaymentIntents +class IntentOnlyGateway extends OfflinePayment implements CreatesPaymentIntents { /** @var array */ public static array $voidedReferences = []; - /** @var array}> */ + /** @var array */ public static array $refundCalls = []; public static PaymentIntentStatus $fetchStatus = PaymentIntentStatus::RequiresCapture; @@ -154,19 +169,19 @@ public function createIntent(Cart $cart): PaymentIntentDescriptor return new PaymentIntentDescriptor('pi_intent_only_'.$cart->id); } - public function fetchIntent(string $reference): PaymentIntentStatus + public function fetchIntent(Cart $cart, string $reference): ?PaymentIntentSnapshot { - return static::$fetchStatus; + return FakeIntents::snapshot($cart, static::$fetchStatus); } - public function voidIntent(string $reference): void + public function voidIntent(Cart $cart, string $reference): void { static::$voidedReferences[] = $reference; } - public function refundIntent(string $reference, int $amountMinor, string $idempotencyKey): PaymentRefund + public function refundIntent(Cart $cart, string $reference, PriceValue $amount, string $idempotencyKey): PaymentRefund { - static::$refundCalls[] = ['reference' => $reference, 'amount' => $amountMinor]; + static::$refundCalls[] = ['reference' => $reference, 'amount' => $amount->value]; return new PaymentRefund(success: true, reference: 'refund_intent_only_'.$reference); } @@ -363,6 +378,7 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession FakeHoldGateway::$createIntentCalls = []; FakeHoldGateway::$createHoldCalls = []; FakeHoldGateway::$voidedReferences = []; + FakeHoldGateway::$adjustCalls = []; FakeHoldGateway::$captureCalls = []; FakeHoldGateway::$refundCalls = []; FakeHoldGateway::$holdSequence = 0; @@ -370,7 +386,9 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession FakeHoldGateway::$fetchStatus = PaymentIntentStatus::RequiresCapture; FakeHoldGateway::$throwOnCapture = false; FakeHoldGateway::$throwOnVoid = false; - FakeHoldGateway::$describeOutcome = null; + FakeHoldGateway::$fetchScript = []; + FakeHoldGateway::$holdAmount = 0; + FakeHoldGateway::$walletLabel = null; IntentOnlyGateway::$voidedReferences = []; IntentOnlyGateway::$refundCalls = []; IntentOnlyGateway::$fetchStatus = PaymentIntentStatus::RequiresCapture; @@ -510,8 +528,18 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession $this->get(route('lunar.checkout.processing', $session->uuid)); - expect(FakeHoldGateway::$captureCalls)->toHaveCount(1) - ->and(FakeHoldGateway::$captureCalls[0]['amount'])->toBe($session->refresh()->amount_total) + $session->refresh(); + + $expected = [ + 'cart' => (int) $session->cart_reference, + 'reference' => $session->payment_intent_ref, + 'amount' => $session->amount_total, + 'currency' => $session->currency_code, + ]; + + expect(FakeHoldGateway::$adjustCalls)->toBe([$expected]) + ->and(FakeHoldGateway::$captureCalls)->toHaveCount(1) + ->and(Arr::except(FakeHoldGateway::$captureCalls[0], 'unplaced_orders'))->toBe($expected) ->and($session->status)->toBeInstanceOf(Completed::class); }); @@ -734,11 +762,8 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession it('processing routes a reopened hold session to confirm, keeping the payment=failed flag', function () { $session = mintPinnedHoldSession(); FakeHoldGateway::$throwOnCapture = true; - FakeHoldGateway::$describeOutcome = new HoldDescription( - status: PaymentIntentStatus::RequiresCapture, - amountMinor: $session->amount_total, - walletLabel: 'Apple Pay', - ); + FakeHoldGateway::$holdAmount = $session->amount_total; + FakeHoldGateway::$walletLabel = 'Apple Pay'; $this->get(route('lunar.checkout.processing', $session->uuid)) ->assertRedirect(route('lunar.checkout.confirm', $session->uuid).'?payment=failed'); @@ -750,7 +775,7 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession it('processing falls back to show when a reopened hold no longer verifies', function () { $session = mintPinnedHoldSession(); FakeHoldGateway::$throwOnCapture = true; - FakeHoldGateway::$describeOutcome = null; + FakeHoldGateway::$fetchScript = [PaymentIntentStatus::RequiresCapture, null]; $this->get(route('lunar.checkout.processing', $session->uuid)) ->assertRedirect(route('lunar.checkout.show', $session->uuid).'?payment=failed'); From 38b419ba73cba2220b03fa8538a6fa9dc72f9125 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 07:59:30 +0000 Subject: [PATCH 06/32] refactor(validation): register PickupPointRequired through the Steps registry Core alpha.9 builds the order-create validation list from the Steps registry and throws RemovedStepConfigException as soon as any list is read while lunar.cart.validators exists. The provider wrote that key, so every cart calculation in an app using this package would have failed. The provider now appends PickupPointRequired to StepList::OrderCreateValidation in boot(). append() skips a step that is already listed, so a second boot registers it once. It stays in boot() because core binds the StepManifest in its own register(): registering here fails to resolve the manifest when the checkout provider is listed ahead of core, which a new test covers. Tests that injected closures through lunar.orders.pipelines.creation now prepend a small throwing step class, since the registry only takes class strings. The bare-validators test case modelled a host config that can no longer exist, so the test asserts the resolved list and the absence of the legacy key instead. --- src/CheckoutServiceProvider.php | 18 +++++-------- tests/Feature/CompletionFailureRefundTest.php | 17 ++++-------- tests/Feature/DraftOrderAtPayGateTest.php | 9 +++---- ...OrderCreateValidatorsProviderOrderTest.php | 14 ++++++++++ tests/Feature/OrderCreateValidatorsTest.php | 24 ++++++++++++----- tests/Feature/PaymentHoldTest.php | 9 +++---- tests/Feature/PickupPointValidationTest.php | 4 ++- tests/Utils/BareCartValidatorsTestCase.php | 22 ---------------- .../Utils/CheckoutFirstProvidersTestCase.php | 26 +++++++++++++++++++ tests/Utils/FailingOrderCreationStep.php | 26 +++++++++++++++++++ 10 files changed, 104 insertions(+), 65 deletions(-) create mode 100644 tests/Feature/OrderCreateValidatorsProviderOrderTest.php delete mode 100644 tests/Utils/BareCartValidatorsTestCase.php create mode 100644 tests/Utils/CheckoutFirstProvidersTestCase.php create mode 100644 tests/Utils/FailingOrderCreationStep.php diff --git a/src/CheckoutServiceProvider.php b/src/CheckoutServiceProvider.php index 7b2de3c..856d139 100644 --- a/src/CheckoutServiceProvider.php +++ b/src/CheckoutServiceProvider.php @@ -37,9 +37,10 @@ use Lunar\Checkout\States\CheckoutSession\DefaultCheckoutSessionStateConfig; use Lunar\Checkout\Support\CheckoutAssets; use Lunar\Checkout\Validation\Cart\PickupPointRequired; +use Lunar\Core\Enums\StepList; use Lunar\Core\Events\PaymentAttemptEvent; +use Lunar\Core\Facades\Steps; use Lunar\Core\Modifiers\ShippingModifiers; -use Lunar\Core\Validation\Cart\ValidateCartForOrderCreation; use Lunar\Shipping\Models\ShippingZone; class CheckoutServiceProvider extends ServiceProvider @@ -166,17 +167,10 @@ public function boot(): void $this->app->make(ShippingModifiers::class)->add(PickupPointModifier::class); // Spec 0013 §D: order creation refuses a collect cart with no chosen - // point through Lunar's own validator seam, so canCreateOrder() is - // the authority for every caller, not only this package's pay boundary. - // The default matches core's own fallback for a missing key: setting - // the key ends that fallback, so reading it as an empty list would - // silently replace core's validator with this package's alone. - config([ - 'lunar.cart.validators.order_create' => array_values(array_unique([ - ...config('lunar.cart.validators.order_create', [ValidateCartForOrderCreation::class]), - PickupPointRequired::class, - ])), - ]); + // point through core's step registry, so canCreateOrder() is the + // authority for every caller, not only this package's pay boundary. + // append() skips a step already listed, so a second boot is harmless. + Steps::for(StepList::OrderCreateValidation)->append(PickupPointRequired::class); $this->loadViewsFrom(__DIR__.'/../resources/views', 'lunar-checkout'); diff --git a/tests/Feature/CompletionFailureRefundTest.php b/tests/Feature/CompletionFailureRefundTest.php index 0a10ada..06404e1 100644 --- a/tests/Feature/CompletionFailureRefundTest.php +++ b/tests/Feature/CompletionFailureRefundTest.php @@ -29,6 +29,7 @@ use Lunar\Core\PaymentTypes\OfflinePayment; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; +use Lunar\Tests\Checkout\Utils\FailingOrderCreationStep; use Lunar\Tests\Checkout\Utils\FakeIntents; uses(TestCase::class, RefreshDatabase::class); @@ -121,9 +122,7 @@ function capturedSession(): CheckoutSession Exceptions::fake(); $session = capturedSession(); - config()->set('lunar.orders.pipelines.creation', [ - fn () => throw new RuntimeException('order pipeline down'), - ]); + FailingOrderCreationStep::register(); $outcome = app(ReconcilesCheckoutSession::class)->execute($session); @@ -140,9 +139,7 @@ function capturedSession(): CheckoutSession $failing = capturedSession(); $failing->forceFill(['payment_processing_at' => now()->subHours(2)])->save(); - config()->set('lunar.orders.pipelines.creation', [ - fn () => throw new RuntimeException('order pipeline down'), - ]); + FailingOrderCreationStep::register(); $this->artisan('lunar:checkout:reconcile')->assertSuccessful(); @@ -175,9 +172,7 @@ function capturedSession(): CheckoutSession Exceptions::fake(); $session = capturedSession(); - config()->set('lunar.orders.pipelines.creation', [ - fn () => throw new RuntimeException('SQLSTATE[40001]: Deadlock found when trying to get lock; try restarting transaction'), - ]); + FailingOrderCreationStep::register('SQLSTATE[40001]: Deadlock found when trying to get lock; try restarting transaction'); $outcome = app(ReconcilesCheckoutSession::class)->execute($session); @@ -207,9 +202,7 @@ function capturedSession(): CheckoutSession Exceptions::fake(); $session = capturedSession(); - config()->set('lunar.orders.pipelines.creation', [ - fn () => throw new RuntimeException('order pipeline down'), - ]); + FailingOrderCreationStep::register(); Event::listen(CheckoutCompletionFailed::class, fn () => throw new LogicException('listener down')); expect(fn () => app(ReconcilesCheckoutSession::class)->execute($session)) diff --git a/tests/Feature/DraftOrderAtPayGateTest.php b/tests/Feature/DraftOrderAtPayGateTest.php index 4f9f7de..cb517d5 100644 --- a/tests/Feature/DraftOrderAtPayGateTest.php +++ b/tests/Feature/DraftOrderAtPayGateTest.php @@ -28,6 +28,7 @@ use Lunar\Core\PaymentTypes\OfflinePayment; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; +use Lunar\Tests\Checkout\Utils\FailingOrderCreationStep; use Lunar\Tests\Checkout\Utils\FakeIntents; uses(TestCase::class, RefreshDatabase::class); @@ -240,9 +241,7 @@ function orderedQuantity(Order $order): int it('leaves the session open when the draft cannot be built', function () { $session = draftAtPinSession(); - config()->set('lunar.orders.pipelines.creation', [ - fn () => throw new RuntimeException('order pipeline down'), - ]); + FailingOrderCreationStep::register(); expect(fn () => app(CheckoutDriver::class)->assertReadyForPayment($session, CheckoutCart::fingerprint($session))) ->toThrow(RuntimeException::class, 'order pipeline down'); @@ -276,9 +275,7 @@ function orderedQuantity(Order $order): int pressPay($session)->assertSuccessful(); $draftId = Order::query()->sole()->id; - config()->set('lunar.orders.pipelines.creation', [ - fn () => throw new RuntimeException('order pipeline down'), - ]); + FailingOrderCreationStep::register(); $this->get(route('lunar.checkout.processing', $session->uuid)); diff --git a/tests/Feature/OrderCreateValidatorsProviderOrderTest.php b/tests/Feature/OrderCreateValidatorsProviderOrderTest.php new file mode 100644 index 0000000..e162c45 --- /dev/null +++ b/tests/Feature/OrderCreateValidatorsProviderOrderTest.php @@ -0,0 +1,14 @@ +all()) + ->toBe([ValidateCartForOrderCreation::class, PickupPointRequired::class]); +}); diff --git a/tests/Feature/OrderCreateValidatorsTest.php b/tests/Feature/OrderCreateValidatorsTest.php index be4e144..c17f446 100644 --- a/tests/Feature/OrderCreateValidatorsTest.php +++ b/tests/Feature/OrderCreateValidatorsTest.php @@ -1,14 +1,26 @@ all()) + ->toBe([ValidateCartForOrderCreation::class, PickupPointRequired::class]); +}); + +it('registers through the step registry and leaves the removed config key unset', function () { + expect(config()->has('lunar.cart.validators'))->toBeFalse(); +}); + +it('registers the validator once when the provider boots again', function () { + app()->getProvider(CheckoutServiceProvider::class)->boot(); - expect($validators)->toContain(ValidateCartForOrderCreation::class) - ->and($validators)->toContain(PickupPointRequired::class); + expect(Steps::for(StepList::OrderCreateValidation)->all()) + ->toBe([ValidateCartForOrderCreation::class, PickupPointRequired::class]); }); diff --git a/tests/Feature/PaymentHoldTest.php b/tests/Feature/PaymentHoldTest.php index ab7b7fb..f461f54 100644 --- a/tests/Feature/PaymentHoldTest.php +++ b/tests/Feature/PaymentHoldTest.php @@ -28,6 +28,7 @@ use Lunar\Core\PaymentTypes\OfflinePayment; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; +use Lunar\Tests\Checkout\Utils\FailingOrderCreationStep; use Lunar\Tests\Checkout\Utils\FakeIntents; uses(TestCase::class, RefreshDatabase::class); @@ -607,9 +608,7 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession $session = mintPinnedHoldSession(); FakeHoldGateway::$fetchStatus = PaymentIntentStatus::RequiresCapture; - config()->set('lunar.orders.pipelines.creation', [ - fn () => throw new RuntimeException('order pipeline down'), - ]); + FailingOrderCreationStep::register(); $this->get(route('lunar.checkout.processing', $session->uuid)); @@ -624,9 +623,7 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession $session = mintPinnedStandardSession(); FakeHoldGateway::$fetchStatus = PaymentIntentStatus::RequiresCapture; - config()->set('lunar.orders.pipelines.creation', [ - fn () => throw new RuntimeException('order pipeline down'), - ]); + FailingOrderCreationStep::register(); $this->get(route('lunar.checkout.processing', $session->uuid)); diff --git a/tests/Feature/PickupPointValidationTest.php b/tests/Feature/PickupPointValidationTest.php index c6c6196..8dac248 100644 --- a/tests/Feature/PickupPointValidationTest.php +++ b/tests/Feature/PickupPointValidationTest.php @@ -6,7 +6,9 @@ use Lunar\Checkout\DataTypes\PickupPoint; use Lunar\Checkout\Exceptions\PaymentConfirmationException; use Lunar\Checkout\Validation\Cart\PickupPointRequired; +use Lunar\Core\Enums\StepList; use Lunar\Core\Facades\CartSession; +use Lunar\Core\Facades\Steps; use Lunar\Core\Validation\Cart\ValidateCartForOrderCreation; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; @@ -82,6 +84,6 @@ }); it('appends the pickup point validator after core\'s own', function () { - expect(config('lunar.cart.validators.order_create')) + expect(Steps::for(StepList::OrderCreateValidation)->all()) ->toBe([ValidateCartForOrderCreation::class, PickupPointRequired::class]); }); diff --git a/tests/Utils/BareCartValidatorsTestCase.php b/tests/Utils/BareCartValidatorsTestCase.php deleted file mode 100644 index b6ed134..0000000 --- a/tests/Utils/BareCartValidatorsTestCase.php +++ /dev/null @@ -1,22 +0,0 @@ -set('lunar.cart.validators', []); - } -} diff --git a/tests/Utils/CheckoutFirstProvidersTestCase.php b/tests/Utils/CheckoutFirstProvidersTestCase.php new file mode 100644 index 0000000..56b0b4b --- /dev/null +++ b/tests/Utils/CheckoutFirstProvidersTestCase.php @@ -0,0 +1,26 @@ + $provider !== CheckoutServiceProvider::class && $provider !== LunarServiceProvider::class)), + LunarServiceProvider::class, + ]; + } +} diff --git a/tests/Utils/FailingOrderCreationStep.php b/tests/Utils/FailingOrderCreationStep.php new file mode 100644 index 0000000..9db2577 --- /dev/null +++ b/tests/Utils/FailingOrderCreationStep.php @@ -0,0 +1,26 @@ +prepend(self::class); + } + + public function handle(Order $order, Closure $next): mixed + { + throw new RuntimeException(self::$message); + } +} From b09a38ae09f8f2685f5467ee93ec80f7833a7096 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 07:59:33 +0000 Subject: [PATCH 07/32] refactor(shipping): read core's pickup option after the collection rename Core alpha.9 renamed ShippingOption::$collect to $pickup (and the order shipping line meta key collect to pickup). The package read the old property in its shipping modifier, fulfilment action, pickup point support and checkout driver, so a collect option was no longer recognised. Only core API names change. The package's own checkout mode string 'collect', its JSON projection key, routes, config and customer copy are untouched. Tests build options with pickup: and assert meta['pickup'] and the pickup property. --- src/Actions/SetFulfilment.php | 4 ++-- src/Drivers/LunarCheckoutDriver.php | 6 +++--- src/PaymentMethods/AbstractPaymentMethod.php | 2 +- src/PaymentMethods/Offline.php | 2 +- src/Shipping/PickupPointModifier.php | 2 +- src/Support/PickupPoints.php | 2 +- tests/Feature/CheckoutDriverFulfilmentTest.php | 2 +- tests/Feature/ExpressCollectFlowTest.php | 2 +- tests/Feature/PaymentMethodAvailabilityTest.php | 2 +- tests/Feature/PickupPointModifierTest.php | 8 ++++---- tests/Feature/PickupPointRoutesTest.php | 2 +- tests/Feature/SetFulfilmentTest.php | 2 +- tests/Utils/CheckoutCart.php | 2 +- 13 files changed, 19 insertions(+), 19 deletions(-) diff --git a/src/Actions/SetFulfilment.php b/src/Actions/SetFulfilment.php index aac38f6..3cd0d38 100644 --- a/src/Actions/SetFulfilment.php +++ b/src/Actions/SetFulfilment.php @@ -75,7 +75,7 @@ private function storeCollectOption(Cart $cart): void return; } - $collect = $this->shippingManifest->getOptions($cart)->first(fn (ShippingOption $option): bool => $option->collect); + $collect = $this->shippingManifest->getOptions($cart)->first(fn (ShippingOption $option): bool => $option->pickup); if ($collect === null || $cart->shippingAddress->shipping_option === $collect->getIdentifier()) { return; @@ -96,7 +96,7 @@ private function leaveCollectOption(Cart $cart): void return; } - $courier = $this->shippingManifest->getOptions($cart)->first(fn (ShippingOption $option): bool => ! $option->collect); + $courier = $this->shippingManifest->getOptions($cart)->first(fn (ShippingOption $option): bool => ! $option->pickup); if ($courier !== null) { $cart->setShippingOption($courier); diff --git a/src/Drivers/LunarCheckoutDriver.php b/src/Drivers/LunarCheckoutDriver.php index c7a2877..25794fa 100644 --- a/src/Drivers/LunarCheckoutDriver.php +++ b/src/Drivers/LunarCheckoutDriver.php @@ -516,9 +516,9 @@ public function setShippingOption(CheckoutSession $session, string $identifier): // Mode and option never disagree (spec 0013 §B): a courier chosen // while collecting drops the point; the collect option chosen while // delivering records collect and applies a single offered point. - $mode = $option->collect ? PickupPoints::COLLECT : PickupPoints::DELIVERY; + $mode = $option->pickup ? PickupPoints::COLLECT : PickupPoints::DELIVERY; - if (PickupPoints::fulfilment($cart) !== $mode || $option->collect) { + if (PickupPoints::fulfilment($cart) !== $mode || $option->pickup) { $cart = $this->setFulfilment->execute($cart->refresh(), $mode); } @@ -636,7 +636,7 @@ public function getShippingOptions(CheckoutSession $session): array 'name' => $option->name, 'description' => $option->description, 'price' => $option->getPrice()->value, - 'collect' => $option->collect, + 'collect' => $option->pickup, ]) ->values() ->all(); diff --git a/src/PaymentMethods/AbstractPaymentMethod.php b/src/PaymentMethods/AbstractPaymentMethod.php index 188d571..c907040 100644 --- a/src/PaymentMethods/AbstractPaymentMethod.php +++ b/src/PaymentMethods/AbstractPaymentMethod.php @@ -16,7 +16,7 @@ * * public function isAvailable(Cart $cart): bool * { - * return (bool) $cart->getShippingOption()?->collect; + * return (bool) $cart->getShippingOption()?->pickup; * } */ abstract class AbstractPaymentMethod implements PaymentMethod diff --git a/src/PaymentMethods/Offline.php b/src/PaymentMethods/Offline.php index d74948a..e890eb8 100644 --- a/src/PaymentMethods/Offline.php +++ b/src/PaymentMethods/Offline.php @@ -21,7 +21,7 @@ * * public function isAvailable(Cart $cart): bool * { - * return (bool) $cart->getShippingOption()?->collect; + * return (bool) $cart->getShippingOption()?->pickup; * } * } */ diff --git a/src/Shipping/PickupPointModifier.php b/src/Shipping/PickupPointModifier.php index 611d18f..fcbe6ac 100644 --- a/src/Shipping/PickupPointModifier.php +++ b/src/Shipping/PickupPointModifier.php @@ -28,7 +28,7 @@ public function handle(Cart $cart, Closure $next): mixed } foreach (app(ShippingManifest::class)->options as $option) { - if ($option instanceof ShippingOption && $option->collect) { + if ($option instanceof ShippingOption && $option->pickup) { $option->meta = array_merge($option->meta ?? [], [PickupPoints::POINT_KEY => $point]); } } diff --git a/src/Support/PickupPoints.php b/src/Support/PickupPoints.php index d138495..d56bd6a 100644 --- a/src/Support/PickupPoints.php +++ b/src/Support/PickupPoints.php @@ -125,6 +125,6 @@ public static function storedOptionCollects(Cart $cart): bool return false; } - return (bool) ShippingManifest::getOption($cart, $identifier)?->collect; + return (bool) ShippingManifest::getOption($cart, $identifier)?->pickup; } } diff --git a/tests/Feature/CheckoutDriverFulfilmentTest.php b/tests/Feature/CheckoutDriverFulfilmentTest.php index 8150599..b11b31f 100644 --- a/tests/Feature/CheckoutDriverFulfilmentTest.php +++ b/tests/Feature/CheckoutDriverFulfilmentTest.php @@ -31,7 +31,7 @@ function driverCart(): Cart identifier: 'collection', price: new PriceValue(0, Currency::query()->firstWhere('default', true)), taxClass: TaxClass::query()->firstWhere('default', true), - collect: true, + pickup: true, )); CartSession::use($cart); diff --git a/tests/Feature/ExpressCollectFlowTest.php b/tests/Feature/ExpressCollectFlowTest.php index ff39b18..305b675 100644 --- a/tests/Feature/ExpressCollectFlowTest.php +++ b/tests/Feature/ExpressCollectFlowTest.php @@ -186,7 +186,7 @@ function collectBasket(): Cart $line = $order->shippingLines()->firstOrFail(); expect($session->refresh()->status)->toBeInstanceOf(Completed::class) - ->and($line->meta['collect'])->toBeTrue() + ->and($line->meta['pickup'])->toBeTrue() ->and($line->meta['pickup_point']['handle'])->toBe('dartford') ->and($order->meta['fulfilment'])->toBe('collect') ->and($order->shippingAddress->contact_email)->toBe('terry@example.com') diff --git a/tests/Feature/PaymentMethodAvailabilityTest.php b/tests/Feature/PaymentMethodAvailabilityTest.php index e9a1ba5..4ccd57d 100644 --- a/tests/Feature/PaymentMethodAvailabilityTest.php +++ b/tests/Feature/PaymentMethodAvailabilityTest.php @@ -57,7 +57,7 @@ public function label(): string public function isAvailable(Cart $cart): bool { - return (bool) $cart->getShippingOption()?->collect; + return (bool) $cart->getShippingOption()?->pickup; } } diff --git a/tests/Feature/PickupPointModifierTest.php b/tests/Feature/PickupPointModifierTest.php index fa1b333..4c23013 100644 --- a/tests/Feature/PickupPointModifierTest.php +++ b/tests/Feature/PickupPointModifierTest.php @@ -21,7 +21,7 @@ $cart = app(SetsFulfilment::class)->execute($cart, 'collect'); $options = ShippingManifest::getOptions($cart); - $collect = $options->firstWhere('collect', true); + $collect = $options->firstWhere('pickup', true); expect($collect->meta['pickup_point'])->toBe([ 'handle' => 'dartford', @@ -31,13 +31,13 @@ 'location' => null, ]); - $options->where('collect', false)->each(fn ($option) => expect($option->meta['pickup_point'] ?? null)->toBeNull()); + $options->where('pickup', false)->each(fn ($option) => expect($option->meta['pickup_point'] ?? null)->toBeNull()); }); it('leaves option meta alone when no point is chosen', function () { $cart = CheckoutCart::orderable(collect: true); - $collect = ShippingManifest::getOptions($cart)->firstWhere('collect', true); + $collect = ShippingManifest::getOptions($cart)->firstWhere('pickup', true); expect($collect->meta['pickup_point'] ?? null)->toBeNull(); }); @@ -55,7 +55,7 @@ $order = Order::query()->firstOrFail(); $line = $order->shippingLines()->firstOrFail(); - expect($line->meta['collect'])->toBeTrue() + expect($line->meta['pickup'])->toBeTrue() ->and($line->meta['pickup_point']['handle'])->toBe('dartford') ->and($order->meta['pickup_point']['handle'])->toBe('dartford') ->and($order->meta['fulfilment'])->toBe('collect'); diff --git a/tests/Feature/PickupPointRoutesTest.php b/tests/Feature/PickupPointRoutesTest.php index e2c66c7..7a611e2 100644 --- a/tests/Feature/PickupPointRoutesTest.php +++ b/tests/Feature/PickupPointRoutesTest.php @@ -26,7 +26,7 @@ function routesCart(): Cart identifier: 'collection', price: new PriceValue(0, Currency::query()->firstWhere('default', true)), taxClass: TaxClass::query()->firstWhere('default', true), - collect: true, + pickup: true, )); return $cart->refresh(); diff --git a/tests/Feature/SetFulfilmentTest.php b/tests/Feature/SetFulfilmentTest.php index 05c5ba1..572fc02 100644 --- a/tests/Feature/SetFulfilmentTest.php +++ b/tests/Feature/SetFulfilmentTest.php @@ -32,7 +32,7 @@ function fulfilmentCart(): Cart identifier: 'collection', price: new PriceValue(0, Currency::query()->firstWhere('default', true)), taxClass: TaxClass::query()->firstWhere('default', true), - collect: true, + pickup: true, )); return $cart->refresh(); diff --git a/tests/Utils/CheckoutCart.php b/tests/Utils/CheckoutCart.php index 048ef0a..080c936 100644 --- a/tests/Utils/CheckoutCart.php +++ b/tests/Utils/CheckoutCart.php @@ -95,7 +95,7 @@ public static function orderable(int $unitPrice = 1000, bool $collect = false): identifier: $collect ? 'collection' : 'standard', price: new PriceValue(0, $currency), taxClass: $taxClass, - collect: $collect, + pickup: $collect, ); ShippingManifest::addOption($option); From a4be6f0510b16ada7f2d3af4f9993a563c2981ac Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 08:11:02 +0000 Subject: [PATCH 08/32] fix(payments): pin payment amounts from a fresh cart calculation Core alpha.9 caches cart totals: calculate() may serve a persisted snapshot up to lunar.cart.totals.ttl old, or the in-process memo, so a price changed outside the cart's revision went unseen at the pay boundary. Intent and hold creation, the session snapshot and fingerprint, the pay pin and completion's verify now recalculate. The checkout page reuses its snapshot's fingerprint instead of calculating the cart a second time. --- src/Drivers/LunarCheckoutDriver.php | 10 +- src/Http/Controllers/CheckoutController.php | 6 +- tests/Feature/FreshPaymentTotalsTest.php | 174 ++++++++++++++++++++ 3 files changed, 181 insertions(+), 9 deletions(-) create mode 100644 tests/Feature/FreshPaymentTotalsTest.php diff --git a/src/Drivers/LunarCheckoutDriver.php b/src/Drivers/LunarCheckoutDriver.php index 25794fa..a36f2de 100644 --- a/src/Drivers/LunarCheckoutDriver.php +++ b/src/Drivers/LunarCheckoutDriver.php @@ -75,7 +75,7 @@ public function createSession(mixed $source, array $attributes = []): CheckoutSe return $this->createCheckoutSession->execute( $source, - $this->buildSnapshot($source->calculate()), + $this->buildSnapshot($source->recalculate()), $attributes, ); } @@ -131,8 +131,7 @@ public function complete(CheckoutSession $session, ?string $confirmationToken = throw new CheckoutSessionNotOperableException('The session\'s source cart no longer exists.'); } - $cart->calculate(); - $live = $this->buildSnapshot($cart); + $live = $this->buildSnapshot($cart->recalculate()); $isSync = $session->status instanceof Open; @@ -304,7 +303,7 @@ private function recordPayment(CheckoutSession $session, Order $order): void public function snapshot(CheckoutSession $session): CartSnapshot { - return $this->buildSnapshot($this->resolveCart($session)->calculate()); + return $this->buildSnapshot($this->resolveCart($session)->recalculate()); } public function fingerprint(CheckoutSession $session): string @@ -336,8 +335,7 @@ public function assertReadyForPayment(CheckoutSession $session, string $confirme throw new CheckoutSessionNotOperableException('The session\'s source cart no longer exists.'); } - $cart->calculate(); - $live = $this->buildSnapshot($cart); + $live = $this->buildSnapshot($cart->recalculate()); if (! hash_equals($confirmedFingerprint, $live->fingerprint)) { $this->events->dispatch(new CheckoutPaymentConfirmationFailed($session)); diff --git a/src/Http/Controllers/CheckoutController.php b/src/Http/Controllers/CheckoutController.php index 4f7062f..46fcf13 100644 --- a/src/Http/Controllers/CheckoutController.php +++ b/src/Http/Controllers/CheckoutController.php @@ -492,7 +492,7 @@ private function projectCheckout(CheckoutDriver $driver, CheckoutSessionModel $s 'coupon' => $driver->getCoupon($session), // The pay boundary echoes back the fingerprint of the state the // customer confirmed (spec 0010 §E). - 'fingerprint' => $driver->fingerprint($session), + 'fingerprint' => $snapshot->fingerprint, 'paymentMethods' => array_map(fn (PaymentMethod $method): array => [ 'handle' => $method->handle(), 'label' => $method->label(), @@ -1058,8 +1058,8 @@ public function storePaymentIntent(Request $request, CheckoutSessionModel $sessi try { $descriptor = $holdMode - ? $gateway->createHold($cart->calculate()) - : $gateway->createIntent($cart->calculate()); + ? $gateway->createHold($cart->recalculate()) + : $gateway->createIntent($cart->recalculate()); } catch (\Throwable $e) { // Gateway errors carry internals (Stripe's minimum-charge copy // links to its own docs); log the real one, say something human. diff --git a/tests/Feature/FreshPaymentTotalsTest.php b/tests/Feature/FreshPaymentTotalsTest.php new file mode 100644 index 0000000..342b8fa --- /dev/null +++ b/tests/Feature/FreshPaymentTotalsTest.php @@ -0,0 +1,174 @@ + */ + public static array $seen = []; + + public function createIntent(Cart $cart): PaymentIntentDescriptor + { + static::$seen['createIntent'] = $cart->total?->value; + + return new PaymentIntentDescriptor('pi_fresh_'.$cart->id); + } + + public function syncIntent(Cart $cart): void + { + static::$seen['syncIntent'] = $cart->total?->value; + } + + public function createHold(Cart $cart): PaymentIntentDescriptor + { + static::$seen['createHold'] = $cart->total?->value; + + return new PaymentIntentDescriptor('hold_fresh_'.$cart->id); + } + + public function adjustHold(Cart $cart, string $reference, PriceValue $amount): HoldAdjustment + { + static::$seen['adjustHold'] = $amount->value; + + return HoldAdjustment::Ok; + } + + public function captureHold(Cart $cart, string $reference, PriceValue $amount): void {} +} + +class FreshTotalsMethod extends AbstractPaymentMethod +{ + public function handle(): string + { + return 'fresh-card'; + } + + public function label(): string + { + return 'Card'; + } + + public function driver(): string + { + return 'fresh-totals'; + } + + public function requiresIntent(): bool + { + return true; + } + + public function component(): string + { + return 'stripe-card'; + } +} + +beforeEach(function () { + FreshTotalsGateway::$seen = []; + + Payments::extend('fresh-totals', fn () => app(FreshTotalsGateway::class)); + app(PaymentMethodRegistry::class)->add(FreshTotalsMethod::class); +}); + +function calculatedSession(): CheckoutSession +{ + $cart = CheckoutCart::orderable(unitPrice: 1000); + $session = CheckoutCart::session($cart); + + expect($cart->total->value)->toBe(1000) + ->and($session->amount_total)->toBe(1000); + + return $session; +} + +/** + * Reprices the cart's variant straight in the database, which bumps no cart + * revision. Blink is flushed so the next request starts from the persisted + * totals alone, as a new production request would. + */ +function repriceSessionCart(CheckoutSession $session, int $price): void +{ + $variantId = Cart::query()->with('lines')->findOrFail((int) $session->cart_reference)->lines->first()->purchasable_id; + + DB::table((new Price)->getTable()) + ->where('priceable_id', $variantId) + ->update(['price' => $price]); + + Blink::flush(); +} + +it('creates the intent and pins the session from the repriced total, not the cached one', function () { + $session = calculatedSession(); + repriceSessionCart($session, 2500); + + $this->postJson(route('lunar.checkout.payment-intent.store', $session->uuid), [ + 'payment_method' => 'fresh-card', + ])->assertOk(); + + expect(FreshTotalsGateway::$seen['createIntent'] ?? null)->toBe(2500); + + repriceSessionCart($session, 3000); + + $this->postJson(route('lunar.checkout.pay', $session->uuid), [ + 'payment_method' => 'fresh-card', + 'fingerprint' => CheckoutCart::fingerprint($session), + ])->assertSuccessful(); + + $session->refresh(); + + expect($session->status)->toBeInstanceOf(PaymentProcessing::class) + ->and($session->amount_total)->toBe(3000) + ->and(FreshTotalsGateway::$seen['syncIntent'] ?? null)->toBe(3000); +}); + +it('creates the hold and pins the session from the repriced total, not the cached one', function () { + $session = calculatedSession(); + repriceSessionCart($session, 2500); + + $this->postJson(route('lunar.checkout.payment-intent.store', $session->uuid), [ + 'payment_method' => 'fresh-card', + 'mode' => 'hold', + ])->assertOk(); + + expect(FreshTotalsGateway::$seen['createHold'] ?? null)->toBe(2500); + + repriceSessionCart($session, 3000); + + $this->postJson(route('lunar.checkout.pay', $session->uuid), [ + 'payment_method' => 'fresh-card', + 'fingerprint' => CheckoutCart::fingerprint($session), + ])->assertSuccessful(); + + $session->refresh(); + + expect($session->status)->toBeInstanceOf(PaymentProcessing::class) + ->and($session->amount_total)->toBe(3000) + ->and(FreshTotalsGateway::$seen['adjustHold'] ?? null)->toBe(3000); +}); From 27e3bc274f419b687f61a0c4bb0e6cab2f923710 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 08:11:20 +0000 Subject: [PATCH 09/32] test: pin the stale-draft session from the driver snapshot The webhook listener pins amount_total and the fingerprint from one CheckoutDriver::snapshot(). The test pinned the amount from a plain calculate() instead, which in a single test process can return the memoised totals core restores onto a re-queried cart, so it no longer modelled the listener. The assertions are unchanged and still fail against the stale-totals driver. --- tests/Feature/DraftOrderAtPayGateTest.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/Feature/DraftOrderAtPayGateTest.php b/tests/Feature/DraftOrderAtPayGateTest.php index cb517d5..630be80 100644 --- a/tests/Feature/DraftOrderAtPayGateTest.php +++ b/tests/Feature/DraftOrderAtPayGateTest.php @@ -367,12 +367,14 @@ function orderedQuantity(Order $order): int // The gateway took payment with no Pay step: the session is pinned // against the live cart the way the webhook listener pins it, and the // draft still holds the cart from the first attempt. + $live = app(CheckoutDriver::class)->snapshot($session); + $session->forceFill([ 'status' => PaymentProcessing::$name, 'payment_intent_ref' => 'pi_without_pay', 'payment_processing_at' => now(), - 'cart_fingerprint' => CheckoutCart::fingerprint($session), - 'amount_total' => sessionCart($session)->calculate()->total->value, + 'cart_fingerprint' => $live->fingerprint, + 'amount_total' => $live->amountTotal, ])->save(); $this->get(route('lunar.checkout.processing', $session->uuid)); From cfdc7b9ec9153bc3a16ed31ee32c5b95aaa18eb5 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 08:12:50 +0000 Subject: [PATCH 10/32] fix(driver): eager-load line purchasables on the session's cart Core alpha.9 caches each line's calculated properties, so calculate() on a re-queried cart returns the in-request memo (or hydrates the persisted snapshot) without the pipeline's eager loads. Shipping modifiers and the line projection then lazy-load each line's purchasable, which a host running Model::preventLazyLoading() rejects with a 500. resolveCart() loads lines.purchasable, and getLines() loads the variant product, thumbnail and images it projects. --- src/Drivers/LunarCheckoutDriver.php | 3 ++- tests/Feature/OrderSummaryItemsTest.php | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/Drivers/LunarCheckoutDriver.php b/src/Drivers/LunarCheckoutDriver.php index a36f2de..8a650dd 100644 --- a/src/Drivers/LunarCheckoutDriver.php +++ b/src/Drivers/LunarCheckoutDriver.php @@ -673,6 +673,7 @@ public function getLines(CheckoutSession $session): array $cart = $this->resolveCart($session)->calculate(); return $cart->lines + ->loadMorph('purchasable', [ProductVariant::class => ['product.thumbnail', 'images']]) ->map(fn ($line): array => [ 'identifier' => (string) $line->id, 'description' => $line->purchasable?->getDescription(), @@ -724,7 +725,7 @@ public function getTotals(CheckoutSession $session): array private function resolveCart(CheckoutSession $session): Cart { - $cart = Cart::query()->find((int) $session->cart_reference); + $cart = Cart::query()->with('lines.purchasable')->find((int) $session->cart_reference); if ($cart === null) { throw new CheckoutSessionNotOperableException('The session\'s source cart no longer exists.'); diff --git a/tests/Feature/OrderSummaryItemsTest.php b/tests/Feature/OrderSummaryItemsTest.php index 75f0bda..679b8a7 100644 --- a/tests/Feature/OrderSummaryItemsTest.php +++ b/tests/Feature/OrderSummaryItemsTest.php @@ -44,3 +44,16 @@ expect($response->json('props.checkout.items.0'))->toHaveKeys(['id', 'title', 'sku', 'image', 'qty', 'price']); expect($response->json('props.checkout.items.0.image'))->toBeNull(); }); + +it('renders every line of a multi-line cart without lazy loading', function () { + $cart = CheckoutCart::orderable(); + CheckoutCart::addLine($cart, 2500); + $session = CheckoutCart::session($cart->refresh()); + + $response = $this->get(route('lunar.checkout.show', $session->uuid), ['X-Inertia' => 'true']) + ->assertOk(); + + expect($response->json('props.checkout.items'))->toHaveCount(2) + ->and($response->json('props.checkout.shippingMethods'))->not->toBeEmpty() + ->and($response->json('props.checkout.totals.sub_total'))->toBe(3500); +}); From e2d585465a3ee6b20440f42ff11afab914825094 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 08:13:20 +0000 Subject: [PATCH 11/32] test: use the array mailer in the test environment Core alpha.9 mails the customer when an order is placed (SendOrderPlacedNotifications). With the log mailer, a test that spies on the Log facade hands the log transport a null logger and the placement throws. No test reads mail from the log. --- phpunit.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/phpunit.xml b/phpunit.xml index c468861..0cbb54b 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -14,7 +14,7 @@ - + From ffdaa5e77b10b0d95863878ace9ff38b2fa7f694 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 08:14:47 +0000 Subject: [PATCH 12/32] test: give the route test storefront context a default language Core alpha.9 resolves the storefront context, default language included, when it calculates a cart. A session created on an empty cart before any language existed memoised a null default for the request, and the product factory's URL generator then failed on it. A real store always has a default language, so the fixture creates one. --- tests/Feature/CheckoutRouteTest.php | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/tests/Feature/CheckoutRouteTest.php b/tests/Feature/CheckoutRouteTest.php index b0e55a1..89f80c0 100644 --- a/tests/Feature/CheckoutRouteTest.php +++ b/tests/Feature/CheckoutRouteTest.php @@ -9,15 +9,16 @@ use Lunar\Core\Models\Channel; use Lunar\Core\Models\Currency; use Lunar\Core\Models\CustomerGroup; +use Lunar\Core\Models\Language; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; uses(TestCase::class, RefreshDatabase::class); /** - * Storefront context every request has in a real app (default channel + - * currency), without a cart — so CartSession::current() can resolve and - * return null rather than throw. + * Storefront context every request has in a real app (default channel, + * currency and language), without a cart — so CartSession::current() can + * resolve and return null rather than throw. * * @return array{0: Channel, 1: Currency} */ @@ -29,6 +30,10 @@ function routeCheckoutContext(): array CustomerGroup::factory()->create(['default' => true]); } + if (! Language::query()->where('default', true)->exists()) { + Language::factory()->create(['code' => 'en', 'default' => true]); + } + $channel = Channel::query()->firstWhere('handle', 'webstore') ?? Channel::factory()->create(['handle' => 'webstore']); $currency = Currency::query()->firstWhere('code', 'GBP') From db64e4cb060e61364ad3a9133c7f1570f7991e36 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 08:25:33 +0000 Subject: [PATCH 13/32] fix(payments): reopen a session whose intent has waited on the customer too long Stripe on alpha.9 reports requires_payment_method, requires_confirmation and requires_action as PaymentIntentStatus::RequiresAction, and a declined confirmation drops back to requires_payment_method. The monorepo driver reported a decline as Failed, which reopened the session. Reconciliation treated RequiresAction as pending with no attempt counted, so a decline followed by a closed tab, a failed redirect return or an async failure left the session in PaymentProcessing for good: the cart stayed locked, a restart got 409 sibling_payment_processing, the expiry sweep skipped it and nothing ever stalled to alert an operator. RequiresAction is now pending only for lunar.checkout.reconciliation.requires_action_minutes (default 30) after the pin. Past that the session returns to Open with the intent kept, through the helper release() and a failed hold capture already use, with no attempt counted and no event. The outcome code is intent_requires_action, formed like intent_failed and intent_voided. A pin with no timestamp counts as past the window, because it could never age into it. Processing stays pending without a bound, since it settles on its own. The customer can still finish the payment afterwards: the webhook listener adopts the Open session, and a hold-mode session routes to the confirm page once its hold is authorised. If they never return, the expiry sweep voids the intent. --- config/checkout.php | 8 ++ spec/0010-cart-session-reconciliation.md | 8 +- src/Actions/ReconcileCheckoutSession.php | 50 +++++--- .../Actions/ReconcilesCheckoutSession.php | 5 +- tests/Feature/PaymentHoldTest.php | 25 ++++ tests/Feature/PaymentReleaseTest.php | 120 +++++++++++++++++- 6 files changed, 191 insertions(+), 25 deletions(-) diff --git a/config/checkout.php b/config/checkout.php index 4759e0a..ff9cb67 100644 --- a/config/checkout.php +++ b/config/checkout.php @@ -146,6 +146,14 @@ // webhook-less fallback. Small enough that a stuck customer is not // stuck, large enough not to race the immediate post-confirm webhook. 'on_view_after_seconds' => 5, + + // How long (minutes, aged on the pin) an intent may wait on the + // customer before the session reopens for a retry with the intent + // kept. A declined card and an abandoned 3-D Secure challenge both + // read as waiting on the customer and neither settles on its own, so + // without this the cart stays locked. Long enough to finish a + // challenge or a bank redirect. + 'requires_action_minutes' => 30, ], /* diff --git a/spec/0010-cart-session-reconciliation.md b/spec/0010-cart-session-reconciliation.md index a06bac9..f5ea391 100644 --- a/spec/0010-cart-session-reconciliation.md +++ b/spec/0010-cart-session-reconciliation.md @@ -491,7 +491,13 @@ aged on `payment_processing_at`, §A) and **forces reconciliation** through the gateway driver: `fetchIntent` → §E.2 (complete / refund) or void → `Open` (return-path hygiene, §E.2). Each run increments `reconciliation_attempts`; a still-pending intent on a slow method (bank transfer, voucher) **reschedules -without consuming an attempt**, up to a method-declared deadline. After the +without consuming an attempt**, up to a method-declared deadline. An intent +still **waiting on the customer** (a declined card, an abandoned challenge, an +async method that failed back to "pick another method") never settles on its +own, so it is pending only for `reconciliation.requires_action_minutes` +(default 30, aged on `payment_processing_at`); past that the session returns to +`Open` with the intent kept, no attempt consumed and no event, so the customer +can retry and the expiry sweep voids the intent if they never do. After the maximum attempts the session is **stalled**: `CheckoutSessionReconciliationStalled` fires **once** (never per-run noise), and the session drops to a **low-frequency retry tier** — not silence. The diff --git a/src/Actions/ReconcileCheckoutSession.php b/src/Actions/ReconcileCheckoutSession.php index 4e8cc73..f59bc73 100644 --- a/src/Actions/ReconcileCheckoutSession.php +++ b/src/Actions/ReconcileCheckoutSession.php @@ -29,7 +29,8 @@ * Bounded resolution of a `PaymentProcessing` session (spec 0010 §F): the * gateway's actual intent outcome decides — captured completes (or refunds on * mismatch: no charge survives without an order), voided/failed reopens, - * pending reschedules without consuming an attempt. Exhausted attempts fire + * pending reschedules without consuming an attempt, and an intent left + * waiting on the customer past its window reopens. Exhausted attempts fire * {@see CheckoutSessionReconciliationStalled} once; the operator `--resolve` * override is the sanctioned stall exit. */ @@ -72,12 +73,18 @@ public function execute(CheckoutSession $session, ?string $resolve = null): stri // Not an intent the gateway created for this cart: unknowable. null => $this->recordAttempt($session), - // Legitimately still in flight (the customer has yet to act, or - // a slow method has yet to settle): reschedule without consuming - // an attempt (spec 0010 §F). - PaymentIntentStatus::RequiresAction, + // A slow method that has yet to settle does so on its own: + // reschedule without consuming an attempt (spec 0010 §F). PaymentIntentStatus::Processing => 'pending', + // Waiting on the customer covers a recorded decline and an + // abandoned challenge as well as one still under way, and nothing + // settles the first two. Past the window the cart is freed for a + // retry; the intent stays confirmable, so it is kept. + PaymentIntentStatus::RequiresAction => $this->waitedOnCustomerTooLong($session) + ? $this->reopenKeepingIntent($session, 'intent_'.$status->value) + : 'pending', + PaymentIntentStatus::Captured, PaymentIntentStatus::RequiresCapture => $this->completeOrRefund($session, $gateway, $cart, $reference, $status), @@ -125,18 +132,7 @@ public function release(CheckoutSession $session): string } } - // Unlike reopen(), the intent reference survives: the customer's - // mounted payment element is still bound to it, the intent is still - // confirmable, and the retry re-syncs its amount at the pay boundary. - $grace = (int) config('lunar.checkout.session.reopen_grace_minutes', 30); - - $session->transitionGuarded([PaymentProcessing::$name], Open::$name, [ - 'payment_processing_at' => null, - 'reconciliation_attempts' => 0, - 'expires_at' => now()->addMinutes($grace), - ]); - - return 'released'; + return $this->reopenKeepingIntent($session, 'released'); } /** @@ -372,10 +368,11 @@ private function reopen(CheckoutSession $session, string $reason): string } /** - * Back to `Open` like {@see reopen()} but the intent reference survives: - * nothing was captured (the hold's own capture call failed), so there is - * no double-hold risk in leaving the customer bound to the same - * authorisation instead of forcing a fresh one. + * Back to `Open` like {@see reopen()} but the intent reference survives. + * Nothing was captured, so the customer stays bound to the same intent or + * authorisation instead of a fresh one: the mounted payment element still + * points at it, it is still confirmable, and the retry re-syncs its + * amount at the pay boundary. */ private function reopenKeepingIntent(CheckoutSession $session, string $reason): string { @@ -390,6 +387,17 @@ private function reopenKeepingIntent(CheckoutSession $session, string $reason): return $reason; } + /** + * A pin with no timestamp can never age into the window, so it counts as + * past it rather than holding the cart for good. + */ + private function waitedOnCustomerTooLong(CheckoutSession $session): bool + { + $minutes = (int) config('lunar.checkout.reconciliation.requires_action_minutes', 30); + + return $session->payment_processing_at?->lte(now()->subMinutes($minutes)) ?? true; + } + private function pinnedAmount(CheckoutSession $session, Cart $cart): PriceValue { return new PriceValue((int) $session->amount_total, $cart->currency); diff --git a/src/Contracts/Actions/ReconcilesCheckoutSession.php b/src/Contracts/Actions/ReconcilesCheckoutSession.php index 917b4c6..705e99f 100644 --- a/src/Contracts/Actions/ReconcilesCheckoutSession.php +++ b/src/Contracts/Actions/ReconcilesCheckoutSession.php @@ -10,7 +10,10 @@ interface ReconcilesCheckoutSession * Resolve a `PaymentProcessing` session against the gateway's actual * intent outcome (spec 0010 §F): captured → complete (or refund on * mismatch — no charge survives without an order), voided/failed → back - * to `Open`, pending → rescheduled without consuming an attempt. + * to `Open`, pending → rescheduled without consuming an attempt. An + * intent still waiting on the customer counts as pending only for + * `lunar.checkout.reconciliation.requires_action_minutes` after the pin; + * past that the session returns to `Open` with the intent kept. * * `$resolve` is the operator override (`complete` | `refund` | `cancel`) * — the sanctioned stall exit. Returns a stable outcome code. diff --git a/tests/Feature/PaymentHoldTest.php b/tests/Feature/PaymentHoldTest.php index f461f54..8297f7f 100644 --- a/tests/Feature/PaymentHoldTest.php +++ b/tests/Feature/PaymentHoldTest.php @@ -769,6 +769,31 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession ->and($session->payment_intent_ref)->toBe('hold_fake_pinned'); }); +it('routes a hold session reopened after waiting on the customer to confirm once the hold is authorised', function () { + $session = mintPinnedHoldSession(); + $session->forceFill(['payment_processing_at' => now()->subMinutes(31)])->save(); + FakeHoldGateway::$fetchStatus = PaymentIntentStatus::RequiresAction; + + $this->get(route('lunar.checkout.processing', $session->uuid), ['X-Inertia' => 'true']) + ->assertRedirect(route('lunar.checkout.show', $session->uuid).'?payment=failed'); + + $session->refresh(); + + expect($session->status)->toBeInstanceOf(Open::class) + ->and($session->payment_intent_ref)->toBe('hold_fake_pinned') + ->and($session->isHoldMode())->toBeTrue() + ->and(FakeHoldGateway::$voidedReferences)->toBeEmpty(); + + FakeHoldGateway::$fetchStatus = PaymentIntentStatus::RequiresCapture; + FakeHoldGateway::$holdAmount = $session->amount_total; + FakeHoldGateway::$walletLabel = 'Apple Pay'; + + $this->get(route('lunar.checkout.processing', $session->uuid)) + ->assertRedirect(route('lunar.checkout.confirm', $session->uuid).'?payment=failed'); + + expect(FakeHoldGateway::$captureCalls)->toBeEmpty(); +}); + it('processing falls back to show when a reopened hold no longer verifies', function () { $session = mintPinnedHoldSession(); FakeHoldGateway::$throwOnCapture = true; diff --git a/tests/Feature/PaymentReleaseTest.php b/tests/Feature/PaymentReleaseTest.php index fb7fd74..72334ec 100644 --- a/tests/Feature/PaymentReleaseTest.php +++ b/tests/Feature/PaymentReleaseTest.php @@ -1,15 +1,22 @@ [PaymentIntentStatus::Processing], ]); -it('reconciles an in-flight intent to pending without consuming an attempt', function (PaymentIntentStatus $status) { +it('reconciles a recently pinned in-flight intent to pending without consuming an attempt', function (PaymentIntentStatus $status) { ReleaseTestGateway::$status = $status; - $session = pinnedSession(); + $session = pinnedSession(['payment_processing_at' => now()->subMinutes(29)]); expect(app(ReconcilesCheckoutSession::class)->execute($session))->toBe('pending'); @@ -95,6 +102,103 @@ function pinnedSession(array $overrides = []) ->and(ReleaseTestGateway::$fetchedCartIds)->toBe([(int) $session->cart_reference]); })->with('in-flight intent statuses'); +it('reopens a session whose intent has waited on the customer past the window, keeping the intent', function () { + Event::fake([CheckoutCompletionFailed::class, CheckoutSessionReconciliationStalled::class]); + ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + + $session = pinnedSession(['payment_processing_at' => now()->subMinutes(31)]); + + expect(app(ReconcilesCheckoutSession::class)->execute($session))->toBe('intent_requires_action'); + + $session->refresh(); + + expect($session->status)->toBeInstanceOf(Open::class) + ->and($session->payment_intent_ref)->toBe('pi_test_123') + ->and($session->payment_processing_at)->toBeNull() + ->and($session->reconciliation_attempts)->toBe(0) + ->and($session->expires_at->isFuture())->toBeTrue(); + + Event::assertNotDispatched(CheckoutCompletionFailed::class); + Event::assertNotDispatched(CheckoutSessionReconciliationStalled::class); +}); + +it('keeps a session pinned while the gateway is still deciding, however long that takes', function () { + ReleaseTestGateway::$status = PaymentIntentStatus::Processing; + + $session = pinnedSession(['payment_processing_at' => now()->subDays(3)]); + + expect(app(ReconcilesCheckoutSession::class)->execute($session))->toBe('pending'); + + $session->refresh(); + + expect($session->status)->toBeInstanceOf(PaymentProcessing::class) + ->and($session->reconciliation_attempts)->toBe(0) + ->and($session->payment_intent_ref)->toBe('pi_test_123'); +}); + +it('reads how long an intent may wait on the customer from config', function () { + config()->set('lunar.checkout.reconciliation.requires_action_minutes', 5); + ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + + $inside = pinnedSession(['payment_processing_at' => now()->subMinutes(4)]); + $past = pinnedSession(['payment_processing_at' => now()->subMinutes(6), 'payment_intent_ref' => 'pi_test_456']); + + app(ReconcilesCheckoutSession::class)->execute($inside); + app(ReconcilesCheckoutSession::class)->execute($past); + + expect($inside->refresh()->status)->toBeInstanceOf(PaymentProcessing::class) + ->and($past->refresh()->status)->toBeInstanceOf(Open::class); +}); + +it('reopens a session waiting on the customer whose pin time was never recorded', function () { + ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + + $session = pinnedSession(['payment_processing_at' => null]); + + app(ReconcilesCheckoutSession::class)->execute($session); + + expect($session->refresh()->status)->toBeInstanceOf(Open::class) + ->and($session->payment_intent_ref)->toBe('pi_test_123'); +}); + +it('lets the sweep free a cart whose payment the customer abandoned', function () { + ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + + $session = pinnedSession(['payment_processing_at' => now()->subMinutes(61)]); + $cart = Cart::query()->findOrFail((int) $session->cart_reference); + + expect(fn () => app(CheckoutDriver::class)->createSession($cart)) + ->toThrow(CheckoutSessionConflictException::class); + + $this->artisan('lunar:checkout:reconcile')->assertSuccessful(); + + expect($session->refresh()->status)->toBeInstanceOf(Open::class) + ->and($session->reconciliation_attempts)->toBe(0) + ->and($session->meta['reconciliation_stalled'] ?? false)->toBeFalse() + ->and(app(CheckoutDriver::class)->resolveOrCreateSession($cart)->is($session))->toBeTrue(); +}); + +it('completes a reopened session when the customer finishes the payment afterwards', function () { + ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + + $session = pinnedSession(['payment_processing_at' => now()->subMinutes(31)]); + + app(ReconcilesCheckoutSession::class)->execute($session); + + expect($session->refresh()->status)->toBeInstanceOf(Open::class); + + $order = Cart::query()->findOrFail((int) $session->cart_reference)->createOrder(); + $order->update(['placed_at' => now()]); + + PaymentAttemptEvent::dispatch(new PaymentAuthorize(success: true, orderId: $order->id, paymentType: 'release-test')); + + $session->refresh(); + + expect($session->status)->toBeInstanceOf(Completed::class) + ->and((string) $session->order_reference)->toBe((string) $order->id) + ->and(Order::query()->count())->toBe(1); +}); + it('counts an attempt when the gateway did not create the reference for the cart', function () { ReleaseTestGateway::$status = null; @@ -278,6 +382,18 @@ function pinnedSession(array $overrides = []) expect($session->refresh()->status)->toBeInstanceOf(Open::class); }); +it('processing sends a payment that waited on the customer too long back to the checkout to retry', function () { + ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + + $session = pinnedSession(['payment_processing_at' => now()->subMinutes(31)]); + + $this->get(route('lunar.checkout.processing', $session->uuid), ['X-Inertia' => 'true']) + ->assertRedirect(route('lunar.checkout.show', $session->uuid).'?payment=failed'); + + expect($session->refresh()->status)->toBeInstanceOf(Open::class) + ->and($session->payment_intent_ref)->toBe('pi_test_123'); +}); + it('processing renders the polling page while the outcome is in flight', function (PaymentIntentStatus $status) { ReleaseTestGateway::$status = $status; From c5f7d69c58bb6e6f721d553675c86d98cf5e4b3c Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 08:28:19 +0000 Subject: [PATCH 14/32] fix(payments): size refunds and captures in the session's pinned currency pinnedAmount() paired the session's amount_total with the cart's current currency. amount_total is in the session's currency_code, and the cart can change currency after the pin. Stripe refuses a PriceValue whose currency differs from the intent's, so a refund or a hold capture that worked on the monorepo driver now threw: a refund-failed stall, or a spurious hold-capture-failed. The amount is now built from the Currency whose code is the session's currency_code. This covers the hold capture, the refund after a failed completion and the operator's forced refund. The controller's adjustHold call is left alone: it sends the live amount in the live currency. If the store no longer has that currency, pinnedAmount() throws PaymentIntentException instead of falling back to the cart's currency, which by then is known to be the wrong one. Stripe's own intentCurrency() does the same. The existing handlers take it from there: the capture reopens with the hold kept, the refund counts an attempt towards a stall, and the operator command shows the message. The test gateways now record the currency of each refund. --- src/Actions/ReconcileCheckoutSession.php | 24 ++++++++-- tests/Feature/CompletionFailureRefundTest.php | 48 +++++++++++++++++-- tests/Feature/PaymentHoldTest.php | 22 +++++++-- tests/Utils/CheckoutCart.php | 23 +++++++++ 4 files changed, 105 insertions(+), 12 deletions(-) diff --git a/src/Actions/ReconcileCheckoutSession.php b/src/Actions/ReconcileCheckoutSession.php index f59bc73..b0d8178 100644 --- a/src/Actions/ReconcileCheckoutSession.php +++ b/src/Actions/ReconcileCheckoutSession.php @@ -23,6 +23,7 @@ use Lunar\Core\Enums\PaymentIntentStatus; use Lunar\Core\Exceptions\PaymentIntentException; use Lunar\Core\Models\Cart; +use Lunar\Core\Models\Currency; use Lunar\Core\Models\Order; /** @@ -159,7 +160,7 @@ private function completeOrRefund( if ($session->isHoldMode() && $gateway instanceof SupportsPaymentHolds) { try { - $gateway->captureHold($cart, $reference, $this->pinnedAmount($session, $cart)); + $gateway->captureHold($cart, $reference, $this->pinnedAmount($session)); $holdCaptured = true; } catch (PaymentIntentException $e) { report($e); @@ -260,7 +261,7 @@ private function moneyBack( $refund = $gateway->refundIntent( $cart, $reference, - $this->pinnedAmount($session, $cart), + $this->pinnedAmount($session), 'lunar-checkout-refund:'.$reference, ); } catch (PaymentIntentException) { @@ -323,7 +324,7 @@ private function completeOrRefundByForce( $refund = $gateway->refundIntent( $cart, $reference, - $this->pinnedAmount($session, $cart), + $this->pinnedAmount($session), 'lunar-checkout-refund:'.$reference, ); @@ -398,9 +399,22 @@ private function waitedOnCustomerTooLong(CheckoutSession $session): bool return $session->payment_processing_at?->lte(now()->subMinutes($minutes)) ?? true; } - private function pinnedAmount(CheckoutSession $session, Cart $cart): PriceValue + /** + * The pinned total in the currency it was pinned in. The cart's currency + * may have changed since, and a gateway refuses an amount in another + * currency from the intent's, or missizes it. + * + * @throws PaymentIntentException when the store no longer has that + * currency, rather than guess another + */ + private function pinnedAmount(CheckoutSession $session): PriceValue { - return new PriceValue((int) $session->amount_total, $cart->currency); + $currency = Currency::query()->where('code', $session->currency_code)->first() + ?? throw new PaymentIntentException( + "Checkout session [{$session->uuid}] was pinned in [{$session->currency_code}], which this store no longer has.", + ); + + return new PriceValue((int) $session->amount_total, $currency); } private function recordAttempt(CheckoutSession $session): string diff --git a/tests/Feature/CompletionFailureRefundTest.php b/tests/Feature/CompletionFailureRefundTest.php index 06404e1..13029f2 100644 --- a/tests/Feature/CompletionFailureRefundTest.php +++ b/tests/Feature/CompletionFailureRefundTest.php @@ -36,7 +36,7 @@ class CapturedIntentGateway extends OfflinePayment implements CreatesPaymentIntents { - /** @var array */ + /** @var array */ public static array $refunds = []; public static bool $refundFails = false; @@ -59,7 +59,7 @@ public function refundIntent(Cart $cart, string $reference, PriceValue $amount, throw new PaymentIntentException('gateway refund failed'); } - static::$refunds[] = ['reference' => $reference, 'amount' => $amount->value]; + static::$refunds[] = ['reference' => $reference, 'amount' => $amount->value, 'currency' => $amount->resolveCurrency()->code]; return new PaymentRefund(success: true, reference: 'refund_'.$reference); } @@ -127,7 +127,7 @@ function capturedSession(): CheckoutSession $outcome = app(ReconcilesCheckoutSession::class)->execute($session); expect($outcome)->toBe('refunded') - ->and(CapturedIntentGateway::$refunds)->toBe([['reference' => 'pi_captured_pinned', 'amount' => $session->amount_total]]) + ->and(CapturedIntentGateway::$refunds)->toBe([['reference' => 'pi_captured_pinned', 'amount' => $session->amount_total, 'currency' => 'GBP']]) ->and($session->refresh()->status)->toBeInstanceOf(Open::class) ->and(Order::query()->whereNotNull('placed_at')->count())->toBe(0); @@ -274,3 +274,45 @@ function capturedSession(): CheckoutSession expect($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class) ->and($session->reconciliation_attempts)->toBe(1); }); + +it('refunds in the currency the session was pinned in after the cart changed currency', function () { + $session = capturedSession(); + CheckoutCart::changeCurrency(Cart::query()->findOrFail((int) $session->cart_reference), 'EUR'); + + $outcome = app(ReconcilesCheckoutSession::class)->execute($session); + + expect($outcome)->toBe('refunded') + ->and(CapturedIntentGateway::$refunds)->toBe([['reference' => 'pi_captured_pinned', 'amount' => $session->amount_total, 'currency' => 'GBP']]) + ->and($session->refresh()->status)->toBeInstanceOf(Open::class); +}); + +it('refunds in the currency the session was pinned in when the operator forces the refund', function () { + $session = capturedSession(); + CheckoutCart::changeCurrency(Cart::query()->findOrFail((int) $session->cart_reference), 'EUR'); + + $outcome = app(ReconcilesCheckoutSession::class)->execute($session, 'refund'); + + expect($outcome)->toBe('refunded') + ->and(CapturedIntentGateway::$refunds)->toBe([['reference' => 'pi_captured_pinned', 'amount' => $session->amount_total, 'currency' => 'GBP']]) + ->and($session->refresh()->status)->toBeInstanceOf(Open::class); +}); + +it('refuses to refund in another currency when the store no longer has the pinned one', function () { + Event::fake([CheckoutCompletionFailed::class]); + $session = capturedSession(); + $session->forceFill(['currency_code' => 'USD', 'cart_fingerprint' => 'stale'])->save(); + + $outcome = app(ReconcilesCheckoutSession::class)->execute($session->refresh()); + + expect($outcome)->toBe('retry') + ->and(CapturedIntentGateway::$refunds)->toBeEmpty() + ->and($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class) + ->and($session->reconciliation_attempts)->toBe(1); + + Event::assertDispatched(CheckoutCompletionFailed::class, fn (CheckoutCompletionFailed $event): bool => $event->reason === 'refund-failed'); + + expect(fn () => app(ReconcilesCheckoutSession::class)->execute($session, 'refund')) + ->toThrow(PaymentIntentException::class, 'USD'); + + expect(CapturedIntentGateway::$refunds)->toBeEmpty(); +}); diff --git a/tests/Feature/PaymentHoldTest.php b/tests/Feature/PaymentHoldTest.php index 8297f7f..fb4f3ab 100644 --- a/tests/Feature/PaymentHoldTest.php +++ b/tests/Feature/PaymentHoldTest.php @@ -57,7 +57,7 @@ class FakeHoldGateway extends OfflinePayment implements CreatesPaymentIntents, S /** @var array}> */ public static array $captureCalls = []; - /** @var array */ + /** @var array */ public static array $refundCalls = []; public static int $holdSequence = 0; @@ -141,7 +141,7 @@ public function voidIntent(Cart $cart, string $reference): void public function refundIntent(Cart $cart, string $reference, PriceValue $amount, string $idempotencyKey): PaymentRefund { - static::$refundCalls[] = ['reference' => $reference, 'amount' => $amount->value]; + static::$refundCalls[] = ['reference' => $reference, 'amount' => $amount->value, 'currency' => $amount->resolveCurrency()->code]; return new PaymentRefund(success: true, reference: 'refund_fake_'.$reference); } @@ -160,7 +160,7 @@ class IntentOnlyGateway extends OfflinePayment implements CreatesPaymentIntents /** @var array */ public static array $voidedReferences = []; - /** @var array */ + /** @var array */ public static array $refundCalls = []; public static PaymentIntentStatus $fetchStatus = PaymentIntentStatus::RequiresCapture; @@ -182,7 +182,7 @@ public function voidIntent(Cart $cart, string $reference): void public function refundIntent(Cart $cart, string $reference, PriceValue $amount, string $idempotencyKey): PaymentRefund { - static::$refundCalls[] = ['reference' => $reference, 'amount' => $amount->value]; + static::$refundCalls[] = ['reference' => $reference, 'amount' => $amount->value, 'currency' => $amount->resolveCurrency()->code]; return new PaymentRefund(success: true, reference: 'refund_intent_only_'.$reference); } @@ -603,6 +603,20 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession expect($session->refresh()->status)->toBeInstanceOf(Open::class); }); +it('captures and refunds a hold in the currency the session was pinned in after the cart changed currency', function () { + $session = mintPinnedHoldSession(); + FakeHoldGateway::$fetchStatus = PaymentIntentStatus::RequiresCapture; + + CheckoutCart::changeCurrency(Cart::query()->findOrFail((int) $session->cart_reference), 'EUR'); + + $this->get(route('lunar.checkout.processing', $session->uuid)); + + expect(Arr::only(FakeHoldGateway::$captureCalls[0] ?? [], ['reference', 'amount', 'currency'])) + ->toBe(['reference' => 'hold_fake_pinned', 'amount' => $session->amount_total, 'currency' => 'GBP']) + ->and(FakeHoldGateway::$refundCalls) + ->toBe([['reference' => 'hold_fake_pinned', 'amount' => $session->amount_total, 'currency' => 'GBP']]); +}); + it('refunds the captured hold when completion throws for any reason', function () { Exceptions::fake(); $session = mintPinnedHoldSession(); diff --git a/tests/Utils/CheckoutCart.php b/tests/Utils/CheckoutCart.php index 080c936..3a06871 100644 --- a/tests/Utils/CheckoutCart.php +++ b/tests/Utils/CheckoutCart.php @@ -146,6 +146,29 @@ public static function addLine(Cart $cart, int $unitPrice = 1000): Cart return $cart->refresh(); } + /** + * The shopper switched currency after the session pinned its own: the + * cart moves to `$code`, priced there, while the session keeps the old one. + */ + public static function changeCurrency(Cart $cart, string $code): Cart + { + $currency = Currency::factory()->createQuietly(['code' => $code, 'default' => false, 'decimal_places' => 2]); + + foreach ($cart->lines()->get() as $line) { + Price::factory()->create([ + 'price' => 1000, + 'min_quantity' => 1, + 'currency_id' => $currency->id, + 'priceable_type' => $line->purchasable_type, + 'priceable_id' => $line->purchasable_id, + ]); + } + + $cart->update(['currency_id' => $currency->id]); + + return $cart->refresh(); + } + public static function session(Cart $cart): CheckoutSession { return app(CheckoutDriver::class)->createSession($cart); From f970f9196a26fc2b91969fc2ff799703ff344679 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 08:30:31 +0000 Subject: [PATCH 15/32] fix(payments): reconcile sessions whose cart was pruned The alpha.9 intent verbs take the cart, so reconcile, release and void-first invalidation loaded it with Cart::query()->find(). Lunar's Cart soft-deletes and lunar:prune:carts soft-deletes idle carts, so once a cart was pruned those loads returned null. The operator's --resolve=refund answered refund-failed without calling the gateway, the sweep counted attempts until it stalled, and an expired session holding an intent could never be voided. The monorepo driver worked by reference alone and had none of these gaps. PaymentIntentGateway::cartFor() now resolves the cart with trashed rows included, and the three sites use it: - ReconcileCheckoutSession::execute(), which covers the sweep, the customer's poll and the operator override. - ReconcileCheckoutSession::release(), so it answers from the same facts as execute() instead of unconfirmed. - InvalidateCheckoutSession::execute(), so the expiry sweep can void the intent and cancel the session. The controller's liveHold() keeps the plain lookup. It decides whether to render the confirm page for a customer about to capture, and completion refuses a deleted cart, so "no live hold" is the right answer there. The expiry sweep then voids that hold. A captured payment on a pruned cart cannot complete, so the sweep now refunds it instead of stalling. --- src/Actions/InvalidateCheckoutSession.php | 3 +-- src/Actions/ReconcileCheckoutSession.php | 4 ++-- src/Support/PaymentIntentGateway.php | 11 +++++++++ tests/Feature/CompletionFailureRefundTest.php | 24 +++++++++++++++++++ tests/Feature/PaymentHoldTest.php | 14 +++++++++++ tests/Feature/PaymentReleaseTest.php | 11 +++++++++ 6 files changed, 63 insertions(+), 4 deletions(-) diff --git a/src/Actions/InvalidateCheckoutSession.php b/src/Actions/InvalidateCheckoutSession.php index cc3d4ce..651ca98 100644 --- a/src/Actions/InvalidateCheckoutSession.php +++ b/src/Actions/InvalidateCheckoutSession.php @@ -10,7 +10,6 @@ use Lunar\Checkout\States\CheckoutSession\Open; use Lunar\Checkout\States\CheckoutSession\PaymentProcessing; use Lunar\Checkout\Support\PaymentIntentGateway; -use Lunar\Core\Models\Cart; /** * Void-first invalidation (spec 0010 §F). No transition to `Cancelled` ever @@ -29,7 +28,7 @@ public function execute(CheckoutSession $session, string $reason): bool { if ($reference = $session->payment_intent_ref) { $gateway = $this->gateways->for($session); - $cart = Cart::query()->find((int) $session->cart_reference); + $cart = $this->gateways->cartFor($session); if ($gateway === null || $cart === null) { return false; diff --git a/src/Actions/ReconcileCheckoutSession.php b/src/Actions/ReconcileCheckoutSession.php index b0d8178..ea0cb87 100644 --- a/src/Actions/ReconcileCheckoutSession.php +++ b/src/Actions/ReconcileCheckoutSession.php @@ -54,7 +54,7 @@ public function execute(CheckoutSession $session, ?string $resolve = null): stri $gateway = $this->gateways->for($session); $reference = $session->payment_intent_ref; - $cart = Cart::query()->find((int) $session->cart_reference); + $cart = $this->gateways->cartFor($session); if ($resolve !== null) { return $this->resolveByOperator($session, $gateway, $cart, $reference, $resolve); @@ -107,7 +107,7 @@ public function release(CheckoutSession $session): string // An intent exists, so money may exist. Reopen only on the // gateway's word that it was not captured; anything unknowable // stays frozen and the reconciliation sweep owns it. - $cart = Cart::query()->find((int) $session->cart_reference); + $cart = $this->gateways->cartFor($session); if ($gateway === null || $cart === null) { return 'unconfirmed'; diff --git a/src/Support/PaymentIntentGateway.php b/src/Support/PaymentIntentGateway.php index 429f426..d9ee07a 100644 --- a/src/Support/PaymentIntentGateway.php +++ b/src/Support/PaymentIntentGateway.php @@ -5,6 +5,7 @@ use Lunar\Checkout\Models\CheckoutSession; use Lunar\Core\Contracts\ReconcilesPaymentIntents; use Lunar\Core\Managers\PaymentManager; +use Lunar\Core\Models\Cart; /** * Resolves the gateway driver behind a session's in-flight intent, when that @@ -35,4 +36,14 @@ public function for(CheckoutSession $session): ?ReconcilesPaymentIntents return $driver instanceof ReconcilesPaymentIntents ? $driver : null; } + + /** + * The cart the intent verbs are scoped to, pruned or not. Lunar prunes + * idle carts by soft-deleting them, and money held or taken against one + * must still be voidable and refundable afterwards. + */ + public function cartFor(CheckoutSession $session): ?Cart + { + return Cart::query()->withTrashed()->find((int) $session->cart_reference); + } } diff --git a/tests/Feature/CompletionFailureRefundTest.php b/tests/Feature/CompletionFailureRefundTest.php index 13029f2..cb267a8 100644 --- a/tests/Feature/CompletionFailureRefundTest.php +++ b/tests/Feature/CompletionFailureRefundTest.php @@ -316,3 +316,27 @@ function capturedSession(): CheckoutSession expect(CapturedIntentGateway::$refunds)->toBeEmpty(); }); + +it('lets the operator refund a session whose cart was pruned', function () { + $session = capturedSession(); + Cart::query()->findOrFail((int) $session->cart_reference)->delete(); + + $outcome = app(ReconcilesCheckoutSession::class)->execute($session, 'refund'); + + expect($outcome)->toBe('refunded') + ->and(CapturedIntentGateway::$refunds)->toBe([['reference' => 'pi_captured_pinned', 'amount' => $session->amount_total, 'currency' => 'GBP']]) + ->and($session->refresh()->status)->toBeInstanceOf(Open::class); +}); + +it('refunds a captured payment whose cart was pruned before it could complete', function () { + Exceptions::fake(); + $session = capturedSession(); + Cart::query()->findOrFail((int) $session->cart_reference)->delete(); + + $outcome = app(ReconcilesCheckoutSession::class)->execute($session); + + expect($outcome)->toBe('refunded') + ->and(CapturedIntentGateway::$refunds)->toHaveCount(1) + ->and($session->refresh()->status)->toBeInstanceOf(Open::class) + ->and(Order::query()->whereNotNull('placed_at')->count())->toBe(0); +}); diff --git a/tests/Feature/PaymentHoldTest.php b/tests/Feature/PaymentHoldTest.php index fb4f3ab..23ca592 100644 --- a/tests/Feature/PaymentHoldTest.php +++ b/tests/Feature/PaymentHoldTest.php @@ -677,6 +677,20 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession expect($session->refresh()->status)->toBeInstanceOf(Cancelled::class); }); +it('voids the hold of an expired session whose cart was pruned', function () { + $session = mintHoldSession(); + $reference = $session->payment_intent_ref; + + Cart::query()->findOrFail((int) $session->cart_reference)->delete(); + $session->forceFill(['expires_at' => now()->subMinute()])->save(); + + Artisan::call('lunar:checkout:expire-sessions'); + + expect(FakeHoldGateway::$voidedReferences)->toBe([$reference]) + ->and($session->refresh()->status)->toBeInstanceOf(Cancelled::class) + ->and($session->active_cart_reference)->toBeNull(); +}); + it('voids, never refunds, a stray hold when the driver never supported holds and completion fails', function () { $session = mintPinnedHoldSessionWithoutHoldSupport(); diff --git a/tests/Feature/PaymentReleaseTest.php b/tests/Feature/PaymentReleaseTest.php index 72334ec..37a0b92 100644 --- a/tests/Feature/PaymentReleaseTest.php +++ b/tests/Feature/PaymentReleaseTest.php @@ -281,6 +281,17 @@ function pinnedSession(array $overrides = []) expect($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class); }); +it('releases on the gateway\'s word when the cart was pruned', function () { + ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + + $session = pinnedSession(); + Cart::query()->findOrFail((int) $session->cart_reference)->delete(); + + expect(app(ReconcilesCheckoutSession::class)->release($session))->toBe('released') + ->and($session->refresh()->status)->toBeInstanceOf(Open::class) + ->and(ReleaseTestGateway::$fetchedCartIds)->toBe([(int) $session->cart_reference]); +}); + it('is a no-op on a session that is not pinned', function () { $session = CheckoutCart::session(CheckoutCart::orderable()); From dd4fa33f08ce07feebccfb13230d050612f9c5a9 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 08:33:07 +0000 Subject: [PATCH 16/32] docs(spec): use the alpha.9 pickup, steps and payment intent names The specs still described the monorepo build. No behaviour changes here. - Pickup: core's flag, order line meta, shipping driver, fulfilment method and states are pickup, Pickup, "Ready for pickup" and "Picked up", and the panel exposes pickup. The package's own collect mode and customer copy keep their names. - Steps: PickupPointRequired is appended in boot() through Steps::for(StepList::OrderCreateValidation), and address writes run the StepList::AddAddressValidation steps. The lunar.cart.validators config keys no longer exist. - Payment intents: SupportsPaymentIntents is ReconcilesPaymentIntents. Its verbs and the hold verbs take the cart first, amounts are PriceValue, fetchIntent() returns a nullable PaymentIntentSnapshot and refundIntent() returns a PaymentRefund. PaymentIntentStatus has RequiresAction and Processing in place of Pending. --- spec/0000-overview.md | 8 +++--- spec/0001-core-element-model.md | 2 +- spec/0002-payment-methods-and-driver.md | 22 +++++++++------ spec/0006-worked-example.md | 2 +- spec/0010-cart-session-reconciliation.md | 11 ++++---- spec/0012-express-payments.md | 10 +++---- spec/0013-pickup-points.md | 35 ++++++++++++------------ spec/RESUME.md | 4 +-- spec/overview.md | 8 +++--- 9 files changed, 54 insertions(+), 48 deletions(-) diff --git a/spec/0000-overview.md b/spec/0000-overview.md index ba5155e..649be2d 100644 --- a/spec/0000-overview.md +++ b/spec/0000-overview.md @@ -48,7 +48,7 @@ lunar/checkout Everything checkout. The element model: capability interfaces elements/gateways contribute Vue UI via runtime chunks, no rebuild (0009). │ ├── lunar/core The seams checkout rides: the cart API (Cart::set*), ShippingManifest, - │ Payments/AbstractPayment — plus ONE addition, the SupportsPaymentIntents + │ Payments/AbstractPayment, plus ONE addition, the ReconcilesPaymentIntents │ capability contract (fetch/void/refund by intent) gateway drivers adopt │ for the integrity protocol (0010). No checkout code. │ @@ -91,7 +91,7 @@ client. | 0009 | Frontend element extension | How third-party elements/gateways contribute Vue UI into the prebuilt app at runtime — `CheckoutAssets` registry, contributed ES-module chunks served same-origin, shared Vue + SDK via `window.Vue`/`window.Lunar` externals, build preset, version/fallback; first-party gateways prebuilt | | 0006 | Worked example (guide) | End-to-end walkthrough of one reference checkout through the Inertia spine — element impl, registration, session, DTO, Vue render, payment method, completion. Illustrative, not normative | | 0007 | Discount element | Resolves 0001's open question: discount is a `Summary`-region `CapturesData` element; adds an additive `Cart::setCoupon()` so it persists through the cart API | -| 0010 | Cart–session reconciliation | Backend-neutral session data model (no Lunar FKs; store only non-derivable); the full `CheckoutDriver` store/read surface; element bag; **driver-owned fingerprint + sync-while-Open + pin-and-confirm-at-pay** integrity with the completion re-verify + refund invariant; void-first invalidation on every terminalizing transition; one-active-session-per-cart via guarded unique-column concurrency; the `SupportsPaymentIntents` gateway seam; bounded `PaymentProcessing` reconciliation + stall protocol; lifecycle events | +| 0010 | Cart–session reconciliation | Backend-neutral session data model (no Lunar FKs; store only non-derivable); the full `CheckoutDriver` store/read surface; element bag; **driver-owned fingerprint + sync-while-Open + pin-and-confirm-at-pay** integrity with the completion re-verify + refund invariant; void-first invalidation on every terminalizing transition; one-active-session-per-cart via guarded unique-column concurrency; the `ReconcilesPaymentIntents` gateway seam; bounded `PaymentProcessing` reconciliation + stall protocol; lifecycle events | ### Cross-cutting decisions (apply to all specs) @@ -155,7 +155,7 @@ client. landing; future breaking changes require a spec + Rector rule per the package rule. - The checkout concern lives in its own `packages/checkout` sub-package (`Lunar\Checkout\…`), not a new core `Checkout/` folder — core's spec-0013 list is untouched; core gains only the - `SupportsPaymentIntents` capability contract (`Contracts/`, additive). + `ReconcilesPaymentIntents` capability contract (`Contracts/`, additive). - Depends on the planned `public_id` (ULID) and Region/`StorefrontContext` TODO items; until they land, cart identity stays resolved server-side via `CartSession` and the country list stays channel-scoped. @@ -184,7 +184,7 @@ client. ([[0008-checkout-ui-and-theming]]). It is **not** embedded into a consumer's Vue build; any storefront stack links to it. `storefront-ui` is a reference host with it installed. The Lunar-hosted page ([[0005-hosted-checkout]]) is the same app under a Lunar-operated deployment. - Core gains only the `SupportsPaymentIntents` capability contract. + Core gains only the `ReconcilesPaymentIntents` capability contract. - A transport-free **`checkout-core` split** (element model + session + driver, no Inertia/Vue) so a REST-only consumer (`lunar/api`) need not depend on the Inertia app package — recorded as an open question, not done now. (Owner: package maintainer.) diff --git a/spec/0001-core-element-model.md b/spec/0001-core-element-model.md index 44fdfc7..d4588f1 100644 --- a/spec/0001-core-element-model.md +++ b/spec/0001-core-element-model.md @@ -130,7 +130,7 @@ the configured validators and `recalculate()`: | Element | Write path | |---------|-----------| | `ContactInformation` | `$context->storeContact($validated)` → (driver) `storeContact` — guest email/phone ([[0010-cart-session-reconciliation]] §B); contact is **not** an address write | -| `AddressElement` | `$context->storeShippingAddress($validated)` / `storeBillingAddress($validated)` → (driver) → `Cart::setShippingAddress()` / `setBillingAddress()` (→ `AddAddress` action, `lunar.cart.validators.add_address`, tax-zone clear, recalc) | +| `AddressElement` | `$context->storeShippingAddress($validated)` / `storeBillingAddress($validated)` → (driver) → `Cart::setShippingAddress()` / `setBillingAddress()` (→ `AddAddress` action, the `StepList::AddAddressValidation` steps, tax-zone clear, recalc) | | `ShippingOptionsElement` | `$context->setShippingOption($identifier)` → (driver) resolves via `ShippingManifest::getOption($cart, $identifier)` → `Cart::setShippingOption($option)` (→ `SetShippingOption` action + validator + recalc); persists identifier only | Direct `fill()->save()` is forbidden: it bypasses the validators and the recalculation, letting diff --git a/spec/0002-payment-methods-and-driver.md b/spec/0002-payment-methods-and-driver.md index 246f7ec..4707413 100644 --- a/spec/0002-payment-methods-and-driver.md +++ b/spec/0002-payment-methods-and-driver.md @@ -65,15 +65,19 @@ like the element capability interfaces ([[0001-core-element-model]] §B): ```php namespace Lunar\Core\Contracts; -interface SupportsPaymentIntents +interface ReconcilesPaymentIntents { - public function fetchIntent(string $ref): PaymentIntentStatus; // enum: Pending, RequiresCapture, - // Captured, Voided, Failed - public function voidIntent(string $ref): void; - public function refundIntent(string $ref, int $amountMinor, string $idempotencyKey): string; // refund ref + // Null when the driver did not create the reference for the cart. + public function fetchIntent(Cart $cart, string $reference): ?PaymentIntentSnapshot; + public function voidIntent(Cart $cart, string $reference): void; + public function refundIntent(Cart $cart, string $reference, PriceValue $amount, string $idempotencyKey): PaymentRefund; } ``` +`PaymentIntentSnapshot::$status` is a `PaymentIntentStatus`: `RequiresAction`, `Processing`, +`RequiresCapture`, `Captured`, `Voided` or `Failed`. `PaymentRefund::$reference` is the +gateway's refund id. + A gateway that does not implement it **cannot be voided or reconciled**: its sessions stay in `PaymentProcessing` and flow into the stall protocol ([[0010-cart-session-reconciliation]] §F). The interface is also the test seam — the contract-test fake gateway implements it (§E, @@ -153,9 +157,9 @@ re-verifying against the **session** total/currency before transition: - Recompute the session cart's total and verify `intent.amount`/`currency` match before capture/transition; on mismatch, fail and void/refund — routed through - `SupportsPaymentIntents` (§A). + `ReconcilesPaymentIntents` (§A). - Idempotent webhook handling (atomic claim), transaction recording, and intent reconciliation — - the fetch/void/refund-by-intent calls route through `SupportsPaymentIntents` (§A). + the fetch/void/refund-by-intent calls route through `ReconcilesPaymentIntents` (§A). - **Advisory intents.** `payment_intent_ref` is recorded at intent **creation**. A gateway success event that resolves to a non-current intent, or to a session not in `PaymentProcessing`, is **refunded** (`refundIntent`) — it never completes. Terminalizing an @@ -201,7 +205,7 @@ session's `PaymentProcessing` state (which rejects element stores), not a cart f - New `Lunar\Checkout\Contracts\PaymentMethod` + a payment-method registry (in `lunar/checkout`, gateway-agnostic) and the payment host element. **No dependency on `lunar/stripe`.** -- New **core** capability contract `Lunar\Core\Contracts\SupportsPaymentIntents` + the +- New **core** capability contract `Lunar\Core\Contracts\ReconcilesPaymentIntents` + the `PaymentIntentStatus` enum (§A) — additive, opt-in via `instanceof`; existing gateways are unaffected until they adopt it. - `lunar/stripe` (optional) gains a `StripeCardMethod implements PaymentMethod` + a prebuilt @@ -219,7 +223,7 @@ session's `PaymentProcessing` state (which rejects element stores), not a cart f - A payment-method **contract test** fixture each gateway runs to prove the seam (method resolves a registered `AbstractPayment` driver; submit → `authorize()` → `AwaitingPayment → InProcess` + `placed_at` + `Transaction` rows). The fixture's **fake gateway implements - `SupportsPaymentIntents`** (§A) so the intent-keyed verbs are exercised end-to-end. + `ReconcilesPaymentIntents`** (§A) so the intent-keyed verbs are exercised end-to-end. - A gateway success event for a **non-current intent**, or for a session **not in `PaymentProcessing`**, is refunded via `refundIntent` and never completes the session (§E). - Terminalizing an `Open` session **voids its advisory intent first** via `voidIntent` (§E, diff --git a/spec/0006-worked-example.md b/spec/0006-worked-example.md index c85a839..270cc07 100644 --- a/spec/0006-worked-example.md +++ b/spec/0006-worked-example.md @@ -42,7 +42,7 @@ Three packages, one contract ([[0000-overview]]): facade, the built-in element impls, the `/checkout/{uuid}/elements/{handle}` Inertia multiplexer. (A transport-free `checkout-core` split is an open question — [[0000-overview]].) - **`lunar/core`** — the surfaces checkout rides: `Cart::set*`, `ShippingManifest`, - `Payments`/`AbstractPayment` (plus the `SupportsPaymentIntents` capability). No checkout code. + `Payments`/`AbstractPayment` (plus the `ReconcilesPaymentIntents` capability). No checkout code. - **`lunar/api`** — the REST projection of the same DTO (not the spine here; see [[0003-transport-projections]] §A). This walkthrough uses the **Inertia spine**: the self-contained checkout app renders `` diff --git a/spec/0010-cart-session-reconciliation.md b/spec/0010-cart-session-reconciliation.md index f5ea391..b52eaee 100644 --- a/spec/0010-cart-session-reconciliation.md +++ b/spec/0010-cart-session-reconciliation.md @@ -476,9 +476,10 @@ exists, is voided **before** the terminal transition, and an unabortable / unknown-outcome void blocks the terminal transition exactly as above. Every intent operation in §E.2/§F — fetch, void, refund — goes through the new -core gateway capability interface `Lunar\Core\Contracts\SupportsPaymentIntents` -(`fetchIntent(string $ref)`, `voidIntent(string $ref)`, `refundIntent(string -$ref, int $amount, string $idempotencyKey)`), `instanceof`-checked on the +core gateway capability interface `Lunar\Core\Contracts\ReconcilesPaymentIntents` +(`fetchIntent(Cart $cart, string $reference)`, `voidIntent(Cart $cart, string +$reference)`, `refundIntent(Cart $cart, string $reference, PriceValue $amount, +string $idempotencyKey)`), `instanceof`-checked on the gateway driver ([[0002-payment-methods-and-driver]] carries the seam detail). A gateway that does not implement it cannot void — its session stays `PaymentProcessing` and resolves through the stall protocol below. @@ -578,7 +579,7 @@ states (`Expired`, etc.); the table does not duplicate those. `src/DataObjects/` (`Lunar\Checkout\DataObjects\…`). - **Driver surface:** the §B verbs added to `CheckoutDriver`, plus the mandatory `AbstractCheckoutDriver` base class (§B). New core gateway capability - interface `Lunar\Core\Contracts\SupportsPaymentIntents` (§F). + interface `Lunar\Core\Contracts\ReconcilesPaymentIntents` (§F). - **Session API:** `hasDrifted()`, `putElementData()` / `getElementData()`. - **Actions:** `SyncCheckoutSession` (guarded single-statement re-sync while `Open`, §D), `InvalidateCheckoutSession` (void-first → `Cancelled` + reason, @@ -763,6 +764,6 @@ states (`Expired`, etc.); the table does not duplicate those. - `Lunar\Core\Models\Cart::setShippingAddress()` / `setBillingAddress()` / `setShippingOption()`, `Lunar\Core\Validation\Cart\ValidateCartForOrderCreation`, - `Lunar\Core\Contracts\SupportsPaymentIntents` (new, §F). Core's + `Lunar\Core\Contracts\ReconcilesPaymentIntents` (new, §F). Core's `Cart::fingerprint()` / `checkFingerprint()` / `GeneratesFingerprint` dedupe machinery is explicitly **not** a dependency (§D). diff --git a/spec/0012-express-payments.md b/spec/0012-express-payments.md index d75bdce..fdd46af 100644 --- a/spec/0012-express-payments.md +++ b/spec/0012-express-payments.md @@ -42,11 +42,11 @@ session state. The state machine tracks money-safety states, not UI location. ### A. `SupportsPaymentHolds` (core capability) -New opt-in contract in `lunar/core` beside `CreatesPaymentIntents` / `SupportsPaymentIntents` / +New opt-in contract in `lunar/core` beside `CreatesPaymentIntents` / `ReconcilesPaymentIntents` / `SyncsPaymentIntents`, checked via `instanceof`, never a required part of `PaymentType`: ```php -interface SupportsPaymentHolds +interface SupportsPaymentHolds extends ReconcilesPaymentIntents { /** * Create (or resume) the cart's authorise-only intent: capture deferred, @@ -60,19 +60,19 @@ interface SupportsPaymentHolds * hold now covers it; NeedsReauthorization when this hold cannot stretch * (the customer re-opens the wallet for a fresh authorisation). */ - public function adjustHold(string $reference, int $amountMinor): HoldAdjustment; + public function adjustHold(Cart $cart, string $reference, PriceValue $amount): HoldAdjustment; /** * Capture an authorised hold for the final amount (<= authorised). * Idempotent per reference. MUST throw when the gateway cannot confirm * the capture; an unknown outcome is not a capture. */ - public function captureHold(string $reference, int $amountMinor): void; + public function captureHold(Cart $cart, string $reference, PriceValue $amount): void; } ``` - `HoldAdjustment` is an enum: `Ok | NeedsReauthorization`. -- Releasing a hold is the existing `SupportsPaymentIntents::voidIntent()`; no new verb. +- Releasing a hold is the existing `ReconcilesPaymentIntents::voidIntent()`; no new verb. - **Express eligibility** = `$method->supportsExpress() && $driver instanceof SupportsPaymentHolds && $method->isAvailable($cart)`. A gateway that cannot hold cannot be express; the squeeze page's "not charged until you confirm" promise is only honest with a hold. diff --git a/spec/0013-pickup-points.md b/spec/0013-pickup-points.md index 26b15cd..4773c31 100644 --- a/spec/0013-pickup-points.md +++ b/spec/0013-pickup-points.md @@ -14,11 +14,11 @@ Click and collect works end to end in Lunar core and stops one step short in this package. **What core already does.** A collect order is any order whose shipping line carries -`meta.collect = true`. The `collection` shipping driver returns a `ShippingOption` with -`collect: true` and a `meta` array; `Pipelines\Order\Creation\CreateShippingLine` merges that -meta (plus the `collect` flag) onto the shipping order line; `FulfilmentMethods\Collection` +`meta.pickup = true`. The `pickup` shipping driver returns a `ShippingOption` with +`pickup: true` and a `meta` array; `Pipelines\Order\Creation\CreateShippingLine` merges that +meta (plus the `pickup` flag) onto the shipping order line; `FulfilmentMethods\Pickup` claims the order's physical lines by reading exactly that array and runs -Pending → Ready for collection → Collected; `ValidateCartForOrderCreation` waives the +Pending → Ready for pickup → Picked up; `ValidateCartForOrderCreation` waives the shipping-address requirement for a collect option. `FillOrderFromCart` also copies `cart.meta` onto `orders.meta`, and every shipping driver receives the cart in its `ShippingOptionRequest`. None of this knows *where* the customer collects from, and none of it needs to: with no pickup @@ -41,7 +41,7 @@ locations defined, an order simply is a collection order. is dropped by `LunarCheckoutDriver::getShippingOptions()` and never reaches the client. 4. **The panel cannot tell a collect order apart** beyond the fulfilment card's method badge. `OrderShowController::shippingOption()` reads the breakdown item, which carries neither - `collect` nor meta. + `pickup` nor meta. ## Proposal @@ -134,7 +134,7 @@ public function execute(Cart $cart, string $mode, ?string $pickupPoint = null): Behaviour: - `mode = 'collect'`: write `meta.fulfilment`. If a shipping address row exists, resolve the - cart's collect option through `ShippingManifest::getOptions($cart)->firstWhere('collect', true)` + cart's collect option through `ShippingManifest::getOptions($cart)->firstWhere('pickup', true)` and store it via `$cart->setShippingOption()` (a collect-capable cart always has exactly one; a cart with none keeps its current option and the projection says collect is unavailable). Then apply the point: the given handle if valid, else the single point if the provider offers @@ -187,7 +187,7 @@ public function handle(Cart $cart, Closure $next): mixed if (is_array($point)) { foreach (app(ShippingManifest::class)->options as $option) { - if ($option->collect) { + if ($option->pickup) { $option->meta = array_merge($option->meta ?? [], ['pickup_point' => $point]); } } @@ -199,18 +199,19 @@ public function handle(Cart $cart, Closure $next): mixed That is the whole write path. `ShippingManifest::getOption()` re-resolves the option from the cart at order creation, `CreateShippingLine` stamps the meta onto the shipping line, and the -placed order carries `order_lines(shipping).meta = {collect: true, …, pickup_point}`. It +placed order carries `order_lines(shipping).meta = {pickup: true, …, pickup_point}`. It works for any collect-capable driver, including a static `ShippingManifest::addOption()`, so the package's own tests can assert the line meta without table-rate-shipping. The checkout package does not touch the order and `OrderPlacing` listeners are not involved. `orders.meta.pickup_point` also arrives via `FillOrderFromCart`; the shipping line copy is -the normative one, because that is where `collect` lives and what the fulfilment method reads. +the normative one, because that is where `pickup` lives and what the fulfilment method reads. ### D. Validation through Lunar's seam `Validation\Cart\PickupPointRequired extends Lunar\Core\Validation\BaseValidator`, -appended by `CheckoutServiceProvider::register()` to `lunar.cart.validators.order_create` -after core's `ValidateCartForOrderCreation`: +appended in `CheckoutServiceProvider::boot()` with +`Steps::for(StepList::OrderCreateValidation)->append(...)`, after core's +`ValidateCartForOrderCreation`: - fail on `fulfilment` when `meta.fulfilment` and the stored option disagree (collect mode with a non-collect option, or the reverse), which is only reachable by a writer that bypassed @@ -299,14 +300,14 @@ The host owns that endpoint's route and auth; the action is the reuse boundary. ### H. Panel (sibling change: `panel`) `OrderShowController::shippingOption()` reads the shipping line in both branches and adds -`collect: bool` and `pickup_point: ?{handle, name, lines}` from `$line->meta`. The order -screen's Shipping section swaps the truck icon for the store icon when `collect` is true and +`pickup: bool` and `pickup_point: ?{handle, name, lines}` from `$line->meta`. The order +screen's Shipping section swaps the truck icon for the store icon when `pickup` is true and renders "Collect from {name}" with the lines beneath the method name. Nothing else changes: the fulfilment card already badges the method and drives its states; `location` stays the stock location, which is a different concept from the pickup point and deliberately not conflated. The order's shipping address on a collect order is the customer's own address (§F.1). Anything -that renders it as "Delivery address", in this panel or in a host, must check `collect` first +that renders it as "Delivery address", in this panel or in a host, must check `pickup` first and say so. The panel's Shipping address section is relabelled "Customer address" when the shipping line collects. @@ -330,14 +331,14 @@ Package (feature, alongside the existing checkout suite): - express start response carries the three keys; squeeze page confirm in collect mode with a point places the order with the point on the line. -`panel`: `OrderShowController` exposes `collect` and `pickup_point` for a collect order and -`collect: false` for a delivery order. +`panel`: `OrderShowController` exposes `pickup` and `pickup_point` for a collect order and +`pickup: false` for a delivery order. ## Out of scope - Offline / pay-later for collect orders. `PaymentMethods\Offline` already exists as the mechanism; when it is wanted, the host registers it with an `appliesTo()` that reads the - stored option's `collect` flag, exactly as its docblock illustrates. The decision for the + stored option's `pickup` flag, exactly as its docblock illustrates. The decision for the first storefront is that offline payment belongs to on-account orders, which are a separate piece of work. - Per-point availability (stock at a branch, opening hours, cut-offs). The provider gets the diff --git a/spec/RESUME.md b/spec/RESUME.md index a5a41a0..648f9df 100644 --- a/spec/RESUME.md +++ b/spec/RESUME.md @@ -12,7 +12,7 @@ Pick up the Lunar checkout-session work. Context: `active_cart_reference` unique-column concurrency; single-statement guarded session writes (guarded-transition helper = concurrency layer, spatie machine = legality layer); gate step 0 (currency/channel); sync-path gate inside `complete()`'s order transaction; the - `SupportsPaymentIntents` core capability seam; stall protocol + operator resolve; renames + `ReconcilesPaymentIntents` core capability seam; stall protocol + operator resolve; renames (`hasDrifted()`, `scopeExpirable`, `cancelled_at`, `config('lunar.checkout.driver')`); zero-total carts force the sync path; package home pinned to `packages/checkout` (`Lunar\Checkout\…`). - **Implementation: session-core slice LANDED (2026-06-12).** Everything in the Rework/Add lists @@ -51,7 +51,7 @@ Pick up the Lunar checkout-session work. Context: so the driver can't resolve it. - `tests/checkout/Unit/ArchitectureTest.php` — mirror core's arch rules (actions implement a contract, expose `execute()`, no facade imports). -- Core `SupportsPaymentIntents` interface (`packages/core` — small, additive: +- Core `ReconcilesPaymentIntents` interface (`packages/core`, small and additive: fetchIntent/voidIntent/refundIntent). - `AbstractCheckoutDriver` base class (mandatory for third-party drivers). - The guarded-transition helper (single-statement guarded UPDATEs over the spatie machine). diff --git a/spec/overview.md b/spec/overview.md index 95f92a7..d30febc 100644 --- a/spec/overview.md +++ b/spec/overview.md @@ -26,7 +26,7 @@ Three delivery/customisation tiers: | Package | Role | |---|---| | `lunar/checkout` | Everything checkout: the transport-agnostic element model, `CheckoutData` DTO, `CheckoutSession` + the swappable `CheckoutDriver` (default `LunarCheckoutDriver`), `PaymentMethod` registry — **and** the self-contained Inertia app: ``, registry, `CheckoutProvider`, composables, built-in elements, the `CheckoutAssets` extension seam, prebuilt `dist/`. (A transport-free `checkout-core` split is an open question — 0000.) | -| `lunar/core` | The seams checkout rides: `Cart::set*`, `ShippingManifest`, `Payments`/`AbstractPayment` — plus the `SupportsPaymentIntents` capability contract (0010). No checkout code. | +| `lunar/core` | The seams checkout rides: `Cart::set*`, `ShippingManifest`, `Payments`/`AbstractPayment`, plus the `ReconcilesPaymentIntents` capability contract (0010). No checkout code. | | `lunar/api` | REST projection of the same DTO (JSON:API envelope, Sanctum, headers). | | `storefront-ui` | Reference host app with `lunar/checkout` installed (demos install-and-go). | | hosted (future) | The **same** app under a Lunar-operated deployment, rendering a session by UUID. | @@ -116,7 +116,7 @@ Three delivery/customisation tiers: not portable to MySQL); all persisted session writes are single-statement guarded UPDATEs, with the guarded-transition helper as the concurrency layer over the spatie machine (the legality layer); gate step 0 (live currency/channel must equal pinned); the sync path runs the gate inside - `complete()`'s order transaction; the `SupportsPaymentIntents` core capability seam + `complete()`'s order transaction; the `ReconcilesPaymentIntents` core capability seam (fetch/void/refund by intent); the stall protocol + `lunar:checkout:reconcile` operator resolve; consistent-read completion + idempotent `complete()`; new transport verbs (`POST /checkout/{uuid}/pay`, `/contact`, `/elements/{handle}`); `CheckoutData` gains session-level fields (sessionUuid, status, @@ -145,11 +145,11 @@ Three delivery/customisation tiers: CI/release build step. - **Dual-Inertia coexistence** (0008 open question) — if the consumer's storefront also runs Inertia, two apps share a page lifecycle. Expected fine (separate root/manifest/namespace) but unverified. -- **0010 — `SupportsPaymentIntents` is new public surface in `lunar/core`.** Small and additive +- **0010: `ReconcilesPaymentIntents` is new public surface in `lunar/core`.** Small and additive (`Contracts/`, fetch/void/refund by intent), but contract on landing — confirm the verb shape before gateway drivers adopt it, because changing it later needs a spec + Rector rule. - **Gateway adoption of the capability interface.** The void-first/reconcile/refund-by-intent - protocol only works for gateways implementing `SupportsPaymentIntents`; gateways without it flow + protocol only works for gateways implementing `ReconcilesPaymentIntents`; gateways without it flow into the stall protocol (stalled event → low-frequency retries → operator resolve). Confirm that degraded path is acceptable for the gateways merchants actually run. - **0000 — the transport-free `checkout-core` split is unresolved.** Until it is, a REST-only From 5abc120f82594fe14585afca9abdb7390a486f1d Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 08:33:07 +0000 Subject: [PATCH 17/32] test: drop the duplicated order-create validator registration test PickupPointValidationTest repeated, word for word, the assertion OrderCreateValidatorsTest already makes about the order of the order-create validation steps. --- tests/Feature/PickupPointValidationTest.php | 9 --------- 1 file changed, 9 deletions(-) diff --git a/tests/Feature/PickupPointValidationTest.php b/tests/Feature/PickupPointValidationTest.php index 8dac248..9de4c77 100644 --- a/tests/Feature/PickupPointValidationTest.php +++ b/tests/Feature/PickupPointValidationTest.php @@ -5,11 +5,7 @@ use Lunar\Checkout\Contracts\CheckoutDriver; use Lunar\Checkout\DataTypes\PickupPoint; use Lunar\Checkout\Exceptions\PaymentConfirmationException; -use Lunar\Checkout\Validation\Cart\PickupPointRequired; -use Lunar\Core\Enums\StepList; use Lunar\Core\Facades\CartSession; -use Lunar\Core\Facades\Steps; -use Lunar\Core\Validation\Cart\ValidateCartForOrderCreation; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; use Lunar\Tests\Checkout\Utils\PickupPointsStub; @@ -82,8 +78,3 @@ expect($withLondon)->not->toBe($before) ->and($withDartford)->not->toBe($withLondon); }); - -it('appends the pickup point validator after core\'s own', function () { - expect(Steps::for(StepList::OrderCreateValidation)->all()) - ->toBe([ValidateCartForOrderCreation::class, PickupPointRequired::class]); -}); From eede84fbc1a94ab8b4011d1ef0f3fd93641e7b7c Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 08:36:46 +0000 Subject: [PATCH 18/32] fix(fulfilment): eager-load line purchasables before resolving shipping options SetFulfilment receives a refreshed cart from the driver's address and option verbs. calculate() then serves the persisted totals snapshot, which skips the pipeline's eager load, and resolving the shipping options reads every line's purchasable. On a multi-line cart under preventLazyLoading that was a LazyLoadingViolationException when the customer picked the collect option or saved an address in collect mode. --- src/Actions/SetFulfilment.php | 2 +- .../Feature/CheckoutDriverFulfilmentTest.php | 34 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/Actions/SetFulfilment.php b/src/Actions/SetFulfilment.php index 3cd0d38..52e697d 100644 --- a/src/Actions/SetFulfilment.php +++ b/src/Actions/SetFulfilment.php @@ -22,7 +22,7 @@ public function execute(Cart $cart, string $mode, ?string $pickupPoint = null): ]); } - $cart = $cart->calculate(); + $cart = $cart->loadMissing('lines.purchasable')->calculate(); $meta = $cart->meta?->getArrayCopy() ?? []; $meta[PickupPoints::MODE_KEY] = $mode; diff --git a/tests/Feature/CheckoutDriverFulfilmentTest.php b/tests/Feature/CheckoutDriverFulfilmentTest.php index b11b31f..802bc0a 100644 --- a/tests/Feature/CheckoutDriverFulfilmentTest.php +++ b/tests/Feature/CheckoutDriverFulfilmentTest.php @@ -16,6 +16,7 @@ use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; use Lunar\Tests\Checkout\Utils\PickupPointsStub; +use Spatie\LaravelBlink\BlinkFacade as Blink; uses(TestCase::class, RefreshDatabase::class); @@ -148,3 +149,36 @@ function driverCart(): Cart expect($cart->refresh()->shippingAddress)->toBeNull(); }); + +it('stores the collect option on a multi-line cart without lazy loading its purchasables', function () { + $cart = driverCart(); + CheckoutCart::addLine($cart, 2500); + $driver = app(CheckoutDriver::class); + $session = $driver->resolveOrCreateSession($cart->refresh()); + Blink::flush(); + + $driver->setShippingOption($session, 'collection'); + + expect($driver->getFulfilment($session))->toBe('collect') + ->and($driver->getSelectedShippingOption($session))->toBe('collection') + ->and($driver->getLines($session))->toHaveCount(2); +}); + +it('stores the collect option when an address arrives in collect mode on a multi-line cart', function () { + $cart = driverCart(); + CheckoutCart::addLine($cart, 2500); + $cart->addresses()->where('type', 'shipping')->delete(); + $driver = app(CheckoutDriver::class); + $session = $driver->resolveOrCreateSession($cart->refresh()); + + $driver->setFulfilment($session, 'collect'); + Blink::flush(); + + $driver->storeShippingAddress($session, [ + 'first_name' => 'Terry', 'last_name' => 'Sparks', 'line1' => '1 Trade Counter Way', + 'city' => 'London', 'postcode' => 'SE1 1AA', 'country_code' => 'GB', + ]); + + expect($driver->getSelectedShippingOption($session))->toBe('collection') + ->and($driver->getFulfilment($session))->toBe('collect'); +}); From 0e156a848f74a0f9f4d111e491bd24d5a23ecc67 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 08:39:49 +0000 Subject: [PATCH 19/32] fix(payments): decide method availability on fresh totals at pay and intent creation pay() and storePaymentIntent() resolved the method, its availability and any payment guard against an unforced calculate(), which can serve the persisted totals snapshot, and only then pinned or created the intent on recalculated totals. A minimum amount or a credit limit could therefore pass on a stale figure. Both actions now load the cart once, recalculate it, and hand that same instance to every decision and gateway call, so the forced recalculations per request stay the same. --- src/Http/Controllers/CheckoutController.php | 27 ++++-- tests/Feature/FreshPaymentTotalsTest.php | 96 ++++++++++++++++++++- 2 files changed, 114 insertions(+), 9 deletions(-) diff --git a/src/Http/Controllers/CheckoutController.php b/src/Http/Controllers/CheckoutController.php index 46fcf13..ad0f2b3 100644 --- a/src/Http/Controllers/CheckoutController.php +++ b/src/Http/Controllers/CheckoutController.php @@ -993,7 +993,7 @@ public function storePaymentIntent(Request $request, CheckoutSessionModel $sessi 'renew' => ['sometimes', 'boolean'], ]); - $cart = Cart::query()->findOrFail((int) $session->cart_reference); + $cart = $this->freshCart($session); $method = $this->resolveAvailableMethod($methods, $cart, $data['payment_method']); @@ -1058,8 +1058,8 @@ public function storePaymentIntent(Request $request, CheckoutSessionModel $sessi try { $descriptor = $holdMode - ? $gateway->createHold($cart->recalculate()) - : $gateway->createIntent($cart->recalculate()); + ? $gateway->createHold($cart) + : $gateway->createIntent($cart); } catch (\Throwable $e) { // Gateway errors carry internals (Stripe's minimum-charge copy // links to its own docs); log the real one, say something human. @@ -1145,7 +1145,7 @@ public function pay(Request $request, CheckoutSessionModel $session, CheckoutDri 'payment_method' => ['required', 'string'], ]); - $cart = Cart::query()->findOrFail((int) $session->cart_reference); + $cart = $this->freshCart($session); $method = $this->resolveAvailableMethod($methods, $cart, $data['payment_method']); @@ -1155,7 +1155,7 @@ public function pay(Request $request, CheckoutSessionModel $session, CheckoutDri // Live amount, not the session's pinned figure — the pin happens // inside assertReadyForPayment(), after this decision. - $amountTotal = $checkoutDriver->snapshot($session)->amountTotal; + $amountTotal = $cart->total?->value ?? 0; /* * The gateway intent was created when the payment form mounted, and @@ -1184,9 +1184,7 @@ public function pay(Request $request, CheckoutSessionModel $session, CheckoutDri ]); } } elseif ($gateway instanceof SyncsPaymentIntents) { - $gateway->syncIntent( - Cart::query()->findOrFail((int) $session->cart_reference)->calculate(), - ); + $gateway->syncIntent($cart); } } @@ -1433,6 +1431,19 @@ private function paymentRejectionMessage(PaymentConfirmationException $e): strin }; } + /** + * The session's cart with totals from the pipeline, not the persisted + * snapshot: method availability, payment guards and the gateway amount + * are all money decisions, and the pin that follows uses fresh totals. + */ + private function freshCart(CheckoutSessionModel $session): Cart + { + return Cart::query() + ->with('lines.purchasable') + ->findOrFail((int) $session->cart_reference) + ->recalculate(); + } + /** * The registered method for this handle, provided the basket can actually * use it right now. "Available" means a survivor of diff --git a/tests/Feature/FreshPaymentTotalsTest.php b/tests/Feature/FreshPaymentTotalsTest.php index 342b8fa..b22506d 100644 --- a/tests/Feature/FreshPaymentTotalsTest.php +++ b/tests/Feature/FreshPaymentTotalsTest.php @@ -90,11 +90,59 @@ public function component(): string } } +/** + * A credit-limit style method: offered only while the basket stays within a + * limit, the way a host's on-account closure decides. + */ +class FreshLimitedAccountMethod extends AbstractPaymentMethod +{ + public function handle(): string + { + return 'fresh-account'; + } + + public function label(): string + { + return 'Pay on account'; + } + + public function driver(): string + { + return 'offline'; + } + + public function component(): string + { + return 'offline-notice'; + } + + public function isAvailable(Cart $cart): bool + { + return $cart->calculate()->total->value <= 2000; + } +} + +class FreshLimitedCardMethod extends FreshTotalsMethod +{ + public function handle(): string + { + return 'fresh-limited-card'; + } + + public function isAvailable(Cart $cart): bool + { + return $cart->calculate()->total->value <= 2000; + } +} + beforeEach(function () { FreshTotalsGateway::$seen = []; Payments::extend('fresh-totals', fn () => app(FreshTotalsGateway::class)); - app(PaymentMethodRegistry::class)->add(FreshTotalsMethod::class); + app(PaymentMethodRegistry::class) + ->add(FreshTotalsMethod::class) + ->add(FreshLimitedAccountMethod::class) + ->add(FreshLimitedCardMethod::class); }); function calculatedSession(): CheckoutSession @@ -172,3 +220,49 @@ function repriceSessionCart(CheckoutSession $session, int $price): void ->and($session->amount_total)->toBe(3000) ->and(FreshTotalsGateway::$seen['adjustHold'] ?? null)->toBe(3000); }); + +/** + * The cart's live price is $live while its persisted totals still say the + * session's 1000, which calculate() serves. Returns the fingerprint of the + * live basket, the one a customer looking at fresh totals would confirm. + */ +function staleCachedTotals(CheckoutSession $session, int $live): string +{ + repriceSessionCart($session, $live); + $fingerprint = CheckoutCart::fingerprint($session); + + repriceSessionCart($session, 1000); + Cart::query()->findOrFail((int) $session->cart_reference)->recalculate(); + + repriceSessionCart($session, $live); + + $cached = Cart::query()->findOrFail((int) $session->cart_reference); + expect($cached->totalsAreFresh())->toBeTrue() + ->and($cached->calculate()->total->value)->toBe(1000); + Blink::flush(); + + return $fingerprint; +} + +it('decides payment method availability at pay on the repriced total, not the cached one', function () { + $session = calculatedSession(); + $fingerprint = staleCachedTotals($session, 2500); + + $this->postJson(route('lunar.checkout.pay', $session->uuid), [ + 'payment_method' => 'fresh-account', + 'fingerprint' => $fingerprint, + ])->assertUnprocessable()->assertJsonValidationErrors(['payment_method']); + + expect($session->refresh()->order_reference)->toBeNull(); +}); + +it('decides payment method availability for a new intent on the repriced total, not the cached one', function () { + $session = calculatedSession(); + staleCachedTotals($session, 2500); + + $this->postJson(route('lunar.checkout.payment-intent.store', $session->uuid), [ + 'payment_method' => 'fresh-limited-card', + ])->assertUnprocessable()->assertJsonValidationErrors(['payment_method']); + + expect(FreshTotalsGateway::$seen)->not->toHaveKey('createIntent'); +}); From 8d8afc07cebebc8ad7b7c1bf6aade1d3b1f924b4 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 08:40:50 +0000 Subject: [PATCH 20/32] test(payments): pin the driver's pay gate and completion verify to fresh totals The controller-level fresh totals tests stayed green with the pay gate's locked recalculation reverted to calculate(), and never reached complete(). These drive the driver directly: reprice behind persisted totals that calculate() would still serve, then expect the pin and the completion verify both to refuse with fingerprint_mismatch. --- tests/Feature/FreshPaymentTotalsTest.php | 50 ++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/tests/Feature/FreshPaymentTotalsTest.php b/tests/Feature/FreshPaymentTotalsTest.php index b22506d..0f2de5c 100644 --- a/tests/Feature/FreshPaymentTotalsTest.php +++ b/tests/Feature/FreshPaymentTotalsTest.php @@ -2,7 +2,11 @@ use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Event; +use Lunar\Checkout\Contracts\CheckoutDriver; use Lunar\Checkout\Contracts\PaymentMethodRegistry; +use Lunar\Checkout\Events\CheckoutCompletionFailed; +use Lunar\Checkout\Exceptions\PaymentConfirmationException; use Lunar\Checkout\Models\CheckoutSession; use Lunar\Checkout\PaymentMethods\AbstractPaymentMethod; use Lunar\Checkout\States\CheckoutSession\PaymentProcessing; @@ -266,3 +270,49 @@ function staleCachedTotals(CheckoutSession $session, int $live): string expect(FreshTotalsGateway::$seen)->not->toHaveKey('createIntent'); }); + +/** + * The persisted totals still describe the old price, so anything that trusts + * calculate() would see the basket the customer confirmed. + */ +function expectCachedTotalsServable(CheckoutSession $session, int $cachedTotal): void +{ + $cart = Cart::query()->findOrFail((int) $session->cart_reference); + + expect($cart->totalsAreFresh())->toBeTrue() + ->and($cart->calculate()->total->value)->toBe($cachedTotal); + + Blink::flush(); +} + +it('refuses to pin a session whose cart was repriced behind fresh cached totals', function () { + $session = calculatedSession(); + $fingerprint = CheckoutCart::fingerprint($session); + + repriceSessionCart($session, 2500); + expectCachedTotalsServable($session, 1000); + + expect(fn () => app(CheckoutDriver::class)->assertReadyForPayment($session, $fingerprint)) + ->toThrow(PaymentConfirmationException::class, 'fingerprint_mismatch'); + + expect($session->refresh()->status)->not->toBeInstanceOf(PaymentProcessing::class) + ->and($session->amount_total)->toBe(1000); +}); + +it('refuses to complete a pinned session whose cart was repriced behind fresh cached totals', function () { + Event::fake([CheckoutCompletionFailed::class]); + + $session = calculatedSession(); + $driver = app(CheckoutDriver::class); + $driver->assertReadyForPayment($session, CheckoutCart::fingerprint($session)); + expect($session->status)->toBeInstanceOf(PaymentProcessing::class); + + repriceSessionCart($session, 2500); + expectCachedTotalsServable($session, 1000); + + expect(fn () => $driver->complete($session)) + ->toThrow(PaymentConfirmationException::class, 'fingerprint_mismatch'); + + Event::assertDispatched(CheckoutCompletionFailed::class, fn (CheckoutCompletionFailed $event): bool => $event->reason === 'verify-mismatch'); + expect($session->refresh()->order_reference)->toBeNull(); +}); From ed0bd7ff1ec11d9fb131359f30c88461717b6b90 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 08:41:33 +0000 Subject: [PATCH 21/32] fix(payments): snapshot the cart before locking the session in the gateway success listener The listener locked the session row and then took the cart snapshot, which now writes the cart row's totals cache. The pay boundary locks the cart row and then writes the session row, so a gateway success for an Open session racing that session's pay could deadlock. The snapshot now runs before the session lock. The lock never guarded the cart: a cart change after the snapshot fails complete()'s verify under the cart-row lock, and a session moved meanwhile fails the locked Open check. --- .../CompleteSessionOnPaymentSuccess.php | 17 ++++++++++++----- tests/Feature/WebhookFirstPlacementTest.php | 6 +++--- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/Listeners/CompleteSessionOnPaymentSuccess.php b/src/Listeners/CompleteSessionOnPaymentSuccess.php index 2d0b4ef..f8ff16d 100644 --- a/src/Listeners/CompleteSessionOnPaymentSuccess.php +++ b/src/Listeners/CompleteSessionOnPaymentSuccess.php @@ -92,10 +92,19 @@ private function pinForGatewayPayment(CheckoutSession $session): bool * The status moves with the same guarded raw update the pay * boundary uses (LunarCheckoutDriver::assertReadyForPayment()): * session states change through these one-statement guards, not - * model transitions. The snapshot is taken under the lock; complete() - * re-verifies it against the cart under the cart-row lock anyway. + * model transitions. + * + * The snapshot is taken before the session row is locked. Taking it + * writes the cart row's totals cache, and the pay boundary locks the + * cart row before it writes the session row, so snapshotting under + * the session lock could deadlock against it. The session lock never + * guarded the cart: a cart edit after the snapshot leaves a + * fingerprint that complete() rejects under the cart-row lock, and a + * session another process moved meanwhile fails the Open check below. */ - $pinned = DB::transaction(function () use ($session): int { + $live = $this->driver->snapshot($session); + + $pinned = DB::transaction(function () use ($session, $live): int { $locked = CheckoutSession::query() ->whereKey($session->getKey()) ->lockForUpdate() @@ -105,8 +114,6 @@ private function pinForGatewayPayment(CheckoutSession $session): bool return 0; } - $live = $this->driver->snapshot($locked); - return CheckoutSession::query() ->whereKey($session->getKey()) ->where('status', Open::$name) diff --git a/tests/Feature/WebhookFirstPlacementTest.php b/tests/Feature/WebhookFirstPlacementTest.php index 5d83403..9761a1f 100644 --- a/tests/Feature/WebhookFirstPlacementTest.php +++ b/tests/Feature/WebhookFirstPlacementTest.php @@ -68,9 +68,9 @@ public function component(): string /** * Swap the checkout driver for a proxy whose snapshot() first runs $race. - * The listener calls snapshot() between its locked read and its guarded - * update, so this exercises the guarded update's lost-race fallback (in - * production the row lock serialises the other writer instead). + * The listener takes its snapshot before it locks the session row, so this + * is another process moving the session in that window: the locked re-read + * has to notice and leave the session to that process. */ function raceTheListener(Closure $race): void { From 3f9f38dc7e3ee89b113c54971ee12fb4bd27c3f7 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 08:42:05 +0000 Subject: [PATCH 22/32] fix(checkout): return a recalculated snapshot from associateCustomer Every other store verb returns a snapshot built from forced totals. associateCustomer() built its snapshot from an unforced calculate(), so a host reading it could get the persisted totals and a fingerprint the pay boundary would reject. --- src/Drivers/LunarCheckoutDriver.php | 2 +- tests/Feature/FreshPaymentTotalsTest.php | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/Drivers/LunarCheckoutDriver.php b/src/Drivers/LunarCheckoutDriver.php index 8a650dd..e14d045 100644 --- a/src/Drivers/LunarCheckoutDriver.php +++ b/src/Drivers/LunarCheckoutDriver.php @@ -605,7 +605,7 @@ public function associateCustomer(CheckoutSession $session, string $customerRefe $this->events->dispatch(new CustomerAssociated($session, $customerReference)); - return $this->buildSnapshot($cart); + return $this->buildSnapshot($cart->recalculate()); } /* diff --git a/tests/Feature/FreshPaymentTotalsTest.php b/tests/Feature/FreshPaymentTotalsTest.php index 0f2de5c..cb69023 100644 --- a/tests/Feature/FreshPaymentTotalsTest.php +++ b/tests/Feature/FreshPaymentTotalsTest.php @@ -316,3 +316,15 @@ function expectCachedTotalsServable(CheckoutSession $session, int $cachedTotal): Event::assertDispatched(CheckoutCompletionFailed::class, fn (CheckoutCompletionFailed $event): bool => $event->reason === 'verify-mismatch'); expect($session->refresh()->order_reference)->toBeNull(); }); + +it('returns the repriced snapshot when a customer is associated, not the cached one', function () { + $session = calculatedSession(); + + repriceSessionCart($session, 2500); + expectCachedTotalsServable($session, 1000); + + $snapshot = app(CheckoutDriver::class)->associateCustomer($session, '42', 'terry@example.com'); + + expect($snapshot->amountTotal)->toBe(2500) + ->and($snapshot->fingerprint)->toBe(CheckoutCart::fingerprint($session)); +}); From 3468f8a8d2287efa71559bd4e9089ebb963c2ab1 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 08:42:11 +0000 Subject: [PATCH 23/32] docs(contracts): say that snapshot() writes the cart's totals cache The contract said reads never write. Since alpha.9 a snapshot recalculates the cart, and core persists those totals to the cart row. --- src/Contracts/CheckoutDriver.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Contracts/CheckoutDriver.php b/src/Contracts/CheckoutDriver.php index d2a2547..224a1b4 100644 --- a/src/Contracts/CheckoutDriver.php +++ b/src/Contracts/CheckoutDriver.php @@ -63,7 +63,9 @@ public function resolveOrCreateSession(mixed $source, array $attributes = []): C public function complete(CheckoutSession $session, ?string $confirmationToken = null): mixed; /** - * Live, never-persisted view of the source cart (0010 §B). Reads never write. + * Live view of the source cart (0010 §B), built from freshly calculated + * totals. The snapshot itself is never persisted, but calculating it + * writes core's totals cache columns on the cart row. */ public function snapshot(CheckoutSession $session): CartSnapshot; From 4c07359a94e6602539482730d6cb0085ffbfdef2 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 09:12:38 +0000 Subject: [PATCH 24/32] fix(driver): pass the intent to authorize() under the reference key core documents Core's CreatesPaymentIntents contract on alpha.9 says a driver's authorize() receives the intent as withData(['reference' => ...]). recordPayment() only sent payment_intent, which Stripe still reads as a fallback but another driver written to the contract would not find. It now sends both keys with the same value, so a driver written to either one records the payment. --- src/Drivers/LunarCheckoutDriver.php | 4 +++- tests/Feature/PaymentRecordingTest.php | 5 ++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/Drivers/LunarCheckoutDriver.php b/src/Drivers/LunarCheckoutDriver.php index e14d045..3813fda 100644 --- a/src/Drivers/LunarCheckoutDriver.php +++ b/src/Drivers/LunarCheckoutDriver.php @@ -292,7 +292,9 @@ private function recordPayment(CheckoutSession $session, Order $order): void } try { - $gateway->order($order)->withData(['payment_intent' => $reference])->authorize(); + // `reference` is the key core's CreatesPaymentIntents documents; + // `payment_intent` is the one drivers read before it. + $gateway->order($order)->withData(['reference' => $reference, 'payment_intent' => $reference])->authorize(); } catch (\Throwable $e) { report(new PaymentRecordingException( "Could not record payment intent [{$reference}] on order [{$order->id}]: {$e->getMessage()}", diff --git a/tests/Feature/PaymentRecordingTest.php b/tests/Feature/PaymentRecordingTest.php index f6f0b8b..ec37fb5 100644 --- a/tests/Feature/PaymentRecordingTest.php +++ b/tests/Feature/PaymentRecordingTest.php @@ -151,7 +151,10 @@ function pinnedRecordingSession(): CheckoutSession expect(RecordingGateway::$authorizeCalls)->toHaveCount(1) ->and(RecordingGateway::$authorizeCalls[0]['order_id'])->toBe($order->id) - ->and(RecordingGateway::$authorizeCalls[0]['data']['payment_intent'])->toBe('pi_recording_pinned') + ->and(RecordingGateway::$authorizeCalls[0]['data'])->toBe([ + 'reference' => 'pi_recording_pinned', + 'payment_intent' => 'pi_recording_pinned', + ]) ->and($session->status)->toBeInstanceOf(Completed::class) ->and($order->placed_at)->not->toBeNull() ->and($order->transactions()->where('type', 'capture')->count())->toBe(1) From 910f3fb9ca897770075712e043eb7cdd37ae723e Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 09:15:39 +0000 Subject: [PATCH 25/32] fix(payments): answer a gateway that refuses to resize the intent at pay Stripe on alpha.9 throws PaymentIntentException from adjustHold() and syncIntent() for an intent in another currency, one not created for the cart, or a hold no longer awaiting capture. pay() let it through as a 500, and for a cart that changed currency it did so before the gate's step 0 could void the intent and cancel the session. pay() now skips the resize when the cart has left the session's currency, so the gate cancels the session as context_diverged. A refused adjustHold() is reported and answered with the existing hold_reauthorization_required 422, which the confirm page already handles by renewing the hold. A refused syncIntent() is reported and answered with the same payment_method message a failed intent creation uses. The session stays Open in both cases. The currency-change test fixture now re-prices its shipping option in the new currency, so a cart in that currency can be calculated. --- spec/0012-express-payments.md | 5 ++- src/Http/Controllers/CheckoutController.php | 27 ++++++++++-- tests/Feature/PayBoundaryTest.php | 36 +++++++++++++++- tests/Feature/PaymentHoldTest.php | 47 +++++++++++++++++++++ tests/Utils/CheckoutCart.php | 12 ++++++ 5 files changed, 122 insertions(+), 5 deletions(-) diff --git a/spec/0012-express-payments.md b/spec/0012-express-payments.md index fdd46af..36dc2f7 100644 --- a/spec/0012-express-payments.md +++ b/spec/0012-express-payments.md @@ -165,7 +165,10 @@ session whose intent is hold-flavoured: 1. Total above authorised: `adjustHold`, BEFORE the pin (where the standard flow syncs its intent amount; a confirmed hold's amount cannot be edited, so holds adjust instead of syncing). `NeedsReauthorization` is a structured 422 with the session still `Open`: - nothing to unpin, the UI opens the re-open-wallet panel. + nothing to unpin, the UI opens the re-open-wallet panel. A hold the gateway refuses to + adjust at all (a `PaymentIntentException`: not this cart's, or no longer awaiting + capture) is reported and gets the same 422. A cart that has left the session's currency + skips the adjustment, because gate step 0 voids the hold and cancels the session. 2. Fingerprint pin, exactly as the standard flow (the squeeze page echoes the fingerprint it rendered; any drift is the existing `fingerprint_mismatch` 422). `Open -> PaymentProcessing`; the client is sent to the existing `processing` URL. diff --git a/src/Http/Controllers/CheckoutController.php b/src/Http/Controllers/CheckoutController.php index ad0f2b3..73bf07b 100644 --- a/src/Http/Controllers/CheckoutController.php +++ b/src/Http/Controllers/CheckoutController.php @@ -49,6 +49,7 @@ use Lunar\Core\DataObjects\PriceValue; use Lunar\Core\Enums\HoldAdjustment; use Lunar\Core\Enums\PaymentIntentStatus; +use Lunar\Core\Exceptions\PaymentIntentException; use Lunar\Core\Facades\CartSession; use Lunar\Core\Facades\Payments; use Lunar\Core\Models\Address; @@ -1168,12 +1169,24 @@ public function pay(Request $request, CheckoutSessionModel $session, CheckoutDri * stretches (incremental authorization) or it does not, so hold-mode * sessions branch to adjustHold() instead of * SyncsPaymentIntents::syncIntent(). + * + * A cart that left the session's currency is skipped: the gateway + * refuses to resize an intent in another currency, and step 0 of + * the gate below voids that intent and cancels the session anyway. */ - if ($method->requiresIntent() && $amountTotal > 0) { + if ($method->requiresIntent() && $amountTotal > 0 && $cart->currency->code === $session->currency_code) { $gateway = Payments::driver($method->driver()); if ($session->isHoldMode() && $gateway instanceof SupportsPaymentHolds && $session->payment_intent_ref !== null) { - $adjustment = $gateway->adjustHold($cart, $session->payment_intent_ref, new PriceValue($amountTotal, $cart->currency)); + try { + $adjustment = $gateway->adjustHold($cart, $session->payment_intent_ref, new PriceValue($amountTotal, $cart->currency)); + } catch (PaymentIntentException $e) { + // A hold the gateway will not adjust (not this cart's, + // no longer awaiting capture) cannot cover the total. + report($e); + + $adjustment = HoldAdjustment::NeedsReauthorization; + } if ($adjustment === HoldAdjustment::NeedsReauthorization) { // Session still Open: nothing to unpin. The client @@ -1184,7 +1197,15 @@ public function pay(Request $request, CheckoutSessionModel $session, CheckoutDri ]); } } elseif ($gateway instanceof SyncsPaymentIntents) { - $gateway->syncIntent($cart); + try { + $gateway->syncIntent($cart); + } catch (PaymentIntentException $e) { + report($e); + + throw ValidationException::withMessages([ + 'payment_method' => 'Card payments are unavailable right now. Please try again in a moment.', + ]); + } } } diff --git a/tests/Feature/PayBoundaryTest.php b/tests/Feature/PayBoundaryTest.php index 4043f29..0d2a12a 100644 --- a/tests/Feature/PayBoundaryTest.php +++ b/tests/Feature/PayBoundaryTest.php @@ -1,6 +1,7 @@ id); @@ -103,6 +112,10 @@ public function createIntent(Cart $cart): PaymentIntentDescriptor public function syncIntent(Cart $cart): void { + if (static::$throwOnSync) { + throw new PaymentIntentException('fake gateway refused to sync the intent'); + } + static::$syncedAmount = $cart->calculate()->total->value; } } @@ -125,7 +138,6 @@ public function driver(): string it('syncs the gateway intent to the live total before pinning', function () { Payments::extend('sync-test', fn () => app(SyncingTestGateway::class)); - SyncingTestGateway::$syncedAmount = null; app(PaymentMethodRegistry::class)->add(SyncingIntentTestMethod::class); @@ -144,6 +156,28 @@ public function driver(): string ->and($session->status)->toBeInstanceOf(PaymentProcessing::class); }); +it('refuses to pin, with a retry message, when the gateway refuses to sync the intent', function () { + Exceptions::fake(); + Payments::extend('sync-test', fn () => app(SyncingTestGateway::class)); + SyncingTestGateway::$throwOnSync = true; + + app(PaymentMethodRegistry::class)->add(SyncingIntentTestMethod::class); + + $session = CheckoutCart::session(CheckoutCart::orderable()); + + $this->postJson(route('lunar.checkout.pay', $session->uuid), [ + 'fingerprint' => CheckoutCart::fingerprint($session), + 'payment_method' => 'sync-card', + ]) + ->assertUnprocessable() + ->assertJsonPath('errors.payment_method.0', 'Card payments are unavailable right now. Please try again in a moment.'); + + expect($session->refresh()->status)->toBeInstanceOf(Open::class) + ->and($session->meta['payment_handle'] ?? null)->toBeNull(); + + Exceptions::assertReported(PaymentIntentException::class); +}); + it('pins for confirmation with the order drafted but unplaced when the method needs an intent', function () { app(PaymentMethodRegistry::class)->add(IntentTestMethod::class); diff --git a/tests/Feature/PaymentHoldTest.php b/tests/Feature/PaymentHoldTest.php index 23ca592..8fd3ebc 100644 --- a/tests/Feature/PaymentHoldTest.php +++ b/tests/Feature/PaymentHoldTest.php @@ -70,6 +70,8 @@ class FakeHoldGateway extends OfflinePayment implements CreatesPaymentIntents, S public static bool $throwOnVoid = false; + public static bool $throwOnAdjust = false; + /** * Answers for successive fetches, taken ahead of `$fetchStatus`. Null is * a reference the gateway did not create for the cart. @@ -98,6 +100,10 @@ public function createHold(Cart $cart): PaymentIntentDescriptor public function adjustHold(Cart $cart, string $reference, PriceValue $amount): HoldAdjustment { + if (static::$throwOnAdjust) { + throw new PaymentIntentException('fake gateway refused to adjust the hold'); + } + static::$adjustCalls[] = [ 'cart' => $cart->id, 'reference' => $reference, @@ -387,6 +393,7 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession FakeHoldGateway::$fetchStatus = PaymentIntentStatus::RequiresCapture; FakeHoldGateway::$throwOnCapture = false; FakeHoldGateway::$throwOnVoid = false; + FakeHoldGateway::$throwOnAdjust = false; FakeHoldGateway::$fetchScript = []; FakeHoldGateway::$holdAmount = 0; FakeHoldGateway::$walletLabel = null; @@ -514,6 +521,46 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession expect($session->refresh()->status)->toBeInstanceOf(Open::class); }); +it('asks for a fresh authorisation when the gateway refuses to adjust the hold', function () { + Exceptions::fake(); + $session = mintHoldSession(); + FakeHoldGateway::$throwOnAdjust = true; + + $this->postJson(route('lunar.checkout.pay', $session->uuid), [ + 'payment_method' => 'fake', + 'fingerprint' => CheckoutCart::fingerprint($session), + ]) + ->assertUnprocessable() + ->assertJsonPath('errors.hold.0', 'hold_reauthorization_required'); + + expect($session->refresh()->status)->toBeInstanceOf(Open::class) + ->and($session->meta['payment_handle'] ?? null)->toBeNull(); + + Exceptions::assertReported(PaymentIntentException::class); +}); + +it('cancels a hold session whose cart changed currency instead of asking the gateway to adjust the hold', function () { + Exceptions::fake(); + $session = mintHoldSession(); + $hold = $session->payment_intent_ref; + FakeHoldGateway::$throwOnAdjust = true; + + CheckoutCart::changeCurrency(Cart::query()->findOrFail((int) $session->cart_reference), 'EUR'); + + $this->postJson(route('lunar.checkout.pay', $session->uuid), [ + 'payment_method' => 'fake', + 'fingerprint' => CheckoutCart::fingerprint($session), + ]) + ->assertUnprocessable() + ->assertJsonValidationErrorFor('fingerprint'); + + $session->refresh(); + + expect($session->status)->toBeInstanceOf(Cancelled::class) + ->and($session->meta['invalidation_reason'] ?? null)->toBe('context_diverged') + ->and(FakeHoldGateway::$voidedReferences)->toBe([$hold]); +}); + it('pins a hold session and reconcile captures then completes', function () { $session = mintHoldSession(); FakeHoldGateway::$fetchStatus = PaymentIntentStatus::RequiresCapture; diff --git a/tests/Utils/CheckoutCart.php b/tests/Utils/CheckoutCart.php index 3a06871..22a3b66 100644 --- a/tests/Utils/CheckoutCart.php +++ b/tests/Utils/CheckoutCart.php @@ -164,6 +164,18 @@ public static function changeCurrency(Cart $cart, string $code): Cart ]); } + $options = ShippingManifest::getOptions($cart)->map(fn (ShippingOption $option) => new ShippingOption( + name: $option->name, + description: $option->description, + identifier: $option->identifier, + price: new PriceValue($option->price->value, $currency), + taxClass: $option->taxClass, + pickup: $option->pickup, + )); + + ShippingManifest::clearOptions(); + ShippingManifest::addOptions($options); + $cart->update(['currency_id' => $currency->id]); return $cart->refresh(); From d0ada7e0cede0d8301d75cb7e7816fe2e8b63b0c Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 09:17:39 +0000 Subject: [PATCH 26/32] fix(checkout): reopen the session when the customer returns from a failed redirect A redirect payment method (Klarna, PayPal, a full-page 3DS challenge) that fails or is cancelled sends the customer back to the session page, which StripeCard.vue gives Stripe as its return_url. The session was still pinned, because the in-page release only runs when the confirmation fails without leaving the page. On alpha.9 Stripe reports the declined intent as RequiresAction, which reconciliation treats as pending, so the customer faced a frozen checkout for up to 30 minutes. On main the old driver reported Failed and the page reopened at once. show() now runs the customer-initiated release when the request carries redirect_status=failed and a payment_intent equal to the session's own reference. The release asks the gateway first: a captured intent completes or refunds, and only an uncaptured one reopens, with the intent kept. A reopened session redirects to the page with ?payment=failed, which shows the retry message and drops Stripe's parameters from the URL. The fix is server-side so that consumers do not need a rebuilt dist/. The two parameter names are the only gateway knowledge the controller gains, and the session's owner can already ask for the same release through the payment-release route. --- spec/0010-cart-session-reconciliation.md | 10 +++++ src/Http/Controllers/CheckoutController.php | 38 +++++++++++++++++- tests/Feature/PaymentReleaseTest.php | 43 +++++++++++++++++++++ 3 files changed, 90 insertions(+), 1 deletion(-) diff --git a/spec/0010-cart-session-reconciliation.md b/spec/0010-cart-session-reconciliation.md index b52eaee..2e37276 100644 --- a/spec/0010-cart-session-reconciliation.md +++ b/spec/0010-cart-session-reconciliation.md @@ -510,6 +510,16 @@ until one of those exits applies. Retention pruning anchors on the terminal timestamps (`completed_at` / `cancelled_at` / `expires_at`); a stalled session is pruned only after it reaches a terminal state through a sanctioned exit. +**Return from a failed redirect.** A redirect payment method (Klarna, PayPal, a +full-page 3DS challenge) that fails or is cancelled sends the customer back to +the session URL with the session still pinned, and the in-page release never +ran because the browser had left the page. When that request carries Stripe's +`redirect_status=failed` for the session's own `payment_intent`, the session +page runs the customer-initiated release before it renders: `→ Open` with the +intent kept, only on the gateway's word that nothing was captured (a captured +intent resolves through §E.2 instead), then a redirect to the retry state. +Without those parameters the session waits out the window above. + ### F.2 One active session per cart `cart_reference` 1:N sessions is per-*attempt* history, not per-attempt diff --git a/src/Http/Controllers/CheckoutController.php b/src/Http/Controllers/CheckoutController.php index 73bf07b..5d15441 100644 --- a/src/Http/Controllers/CheckoutController.php +++ b/src/Http/Controllers/CheckoutController.php @@ -146,10 +146,30 @@ public function start(Request $request, CheckoutDriver $checkoutDriver): Symfony * caller returns a bare 409 SymfonyResponse rather than a RedirectResponse * (same reason `start()` above is typed against SymfonyResponse). */ - public function show(CheckoutSessionModel $session, CheckoutDriver $checkoutDriver, CheckoutTheme $theme): Response|RedirectResponse|SymfonyResponse + public function show(Request $request, CheckoutSessionModel $session, CheckoutDriver $checkoutDriver, CheckoutTheme $theme): Response|RedirectResponse|SymfonyResponse { $this->ensureOwnership($session); + /* + * A redirect payment method (Klarna, PayPal, a full-page 3DS + * challenge) that failed or was cancelled lands back here with the + * session still pinned: the browser left the page, so the in-page + * release never ran. Release it now, on the gateway's word that + * nothing was captured, and send the customer to the retry state. + */ + if ($session->status instanceof PaymentProcessing && $this->returnedFromFailedRedirect($request, $session)) { + try { + app(ReconcilesCheckoutSession::class)->release($session); + $session->refresh(); + } catch (\Throwable $e) { + report($e); + } + + if ($session->status instanceof Open) { + return redirect()->to(route('lunar.checkout.show', $session->uuid).'?payment=failed'); + } + } + /* * A pinned session normally completes via the gateway webhook, but * webhooks can be slow, misconfigured or absent (local dev). The @@ -1440,6 +1460,22 @@ private function redirectDeadSession(CheckoutSessionModel $session): RedirectRes * carries the developer reason code ("Payment confirmation rejected * [fingerprint_mismatch]."), which is for logs, not for the customer. */ + /** + * Whether Stripe sent the customer back from a redirect payment method + * that did not go through. StripeCard.vue gives Stripe this page as its + * `return_url`, and Stripe appends the intent it was confirming and how + * the redirect ended. Only a failure for the session's own intent + * counts. These are the only gateway parameters the controller reads, + * and they grant nothing new: the session's owner can already ask for + * the same release through releasePayment(). + */ + private function returnedFromFailedRedirect(Request $request, CheckoutSessionModel $session): bool + { + return $request->query('redirect_status') === 'failed' + && $session->payment_intent_ref !== null + && $request->query('payment_intent') === $session->payment_intent_ref; + } + private function paymentRejectionMessage(PaymentConfirmationException $e): string { return match ($e->reason) { diff --git a/tests/Feature/PaymentReleaseTest.php b/tests/Feature/PaymentReleaseTest.php index 37a0b92..7647a87 100644 --- a/tests/Feature/PaymentReleaseTest.php +++ b/tests/Feature/PaymentReleaseTest.php @@ -354,6 +354,49 @@ function pinnedSession(array $overrides = []) expect($session->refresh()->status)->toBeInstanceOf(Open::class); }); +it('reopens a pinned session at once when the customer returns from a failed gateway redirect', function () { + ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + + $session = pinnedSession(['payment_processing_at' => now()->subMinute()]); + + $response = $this->get(route('lunar.checkout.show', $session->uuid).'?payment_intent=pi_test_123&payment_intent_client_secret=secret&redirect_status=failed'); + + $session->refresh(); + + expect($session->status)->toBeInstanceOf(Open::class) + ->and($session->payment_intent_ref)->toBe('pi_test_123'); + + $response->assertRedirect(route('lunar.checkout.show', $session->uuid).'?payment=failed'); +}); + +it('keeps a session pinned on view unless the redirect failed for its own intent', function (string $query) { + ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + + $session = pinnedSession(['payment_processing_at' => now()->subMinute()]); + + $this->get(route('lunar.checkout.show', $session->uuid).$query, ['X-Inertia' => 'true'])->assertOk(); + + expect($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class); +})->with([ + 'no redirect parameters' => [''], + 'a redirect that succeeded' => ['?payment_intent=pi_test_123&redirect_status=succeeded'], + 'a failed redirect for another intent' => ['?payment_intent=pi_test_other&redirect_status=failed'], + 'a failed redirect naming no intent' => ['?redirect_status=failed'], +]); + +it('completes instead of reopening when the gateway captured despite a failed redirect return', function () { + ReleaseTestGateway::$status = PaymentIntentStatus::Captured; + + $session = pinnedSession(['success_url' => 'https://store.test/thanks']); + + $response = $this->get(route('lunar.checkout.show', $session->uuid).'?payment_intent=pi_test_123&redirect_status=failed'); + + expect($session->refresh()->status)->toBeInstanceOf(Completed::class) + ->and(Order::query()->count())->toBe(1); + + $response->assertRedirect('https://store.test/thanks'); +}); + it('processing settles a captured session and forwards to the success url', function () { ReleaseTestGateway::$status = PaymentIntentStatus::Captured; From 16fb30ca82d035d5fe37861bd7adf824dd28cd3a Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 09:19:39 +0000 Subject: [PATCH 27/32] fix(payments): void an intent that waited on the customer too long before reopening db64e4c reopened a session whose intent had waited on the customer past the window and kept the intent. The intent stayed confirmable, so a payment that went through after the reopen had nothing to settle it when webhooks were down: the sweep skips Open sessions, the processing page showed a failure, and a retry minted a second intent, which left an orphaned or double charge. The timed path now voids the intent first and then reopens with the reference cleared, so the retry starts on a fresh intent. If the gateway refuses the void, because the payment went through between the fetch and the void, the session stays pinned and the pass counts an attempt. The next pass reads the real status and completes, and a void that keeps failing stalls with the operator alert. The outcome code is still intent_requires_action and no CheckoutCompletionFailed event fires. The customer-initiated release still keeps the intent, because the customer is on the page with the payment element bound to it. A hold-mode session follows the same timed rule: a hold that never got authorised is voided, and the customer opens the wallet again. --- config/checkout.php | 10 +-- spec/0010-cart-session-reconciliation.md | 14 +++- src/Actions/ReconcileCheckoutSession.php | 31 ++++++- .../Actions/ReconcilesCheckoutSession.php | 4 +- tests/Feature/PaymentHoldTest.php | 17 +--- tests/Feature/PaymentReleaseTest.php | 80 +++++++++++++++---- 6 files changed, 116 insertions(+), 40 deletions(-) diff --git a/config/checkout.php b/config/checkout.php index ff9cb67..1478069 100644 --- a/config/checkout.php +++ b/config/checkout.php @@ -148,11 +148,11 @@ 'on_view_after_seconds' => 5, // How long (minutes, aged on the pin) an intent may wait on the - // customer before the session reopens for a retry with the intent - // kept. A declined card and an abandoned 3-D Secure challenge both - // read as waiting on the customer and neither settles on its own, so - // without this the cart stays locked. Long enough to finish a - // challenge or a bank redirect. + // customer before it is voided and the session reopens for a retry + // on a fresh intent. A declined card and an abandoned 3-D Secure + // challenge both read as waiting on the customer and neither settles + // on its own, so without this the cart stays locked. Long enough to + // finish a challenge or a bank redirect. 'requires_action_minutes' => 30, ], diff --git a/spec/0010-cart-session-reconciliation.md b/spec/0010-cart-session-reconciliation.md index 2e37276..1086afe 100644 --- a/spec/0010-cart-session-reconciliation.md +++ b/spec/0010-cart-session-reconciliation.md @@ -496,9 +496,17 @@ without consuming an attempt**, up to a method-declared deadline. An intent still **waiting on the customer** (a declined card, an abandoned challenge, an async method that failed back to "pick another method") never settles on its own, so it is pending only for `reconciliation.requires_action_minutes` -(default 30, aged on `payment_processing_at`); past that the session returns to -`Open` with the intent kept, no attempt consumed and no event, so the customer -can retry and the expiry sweep voids the intent if they never do. After the +(default 30, aged on `payment_processing_at`); past that the intent is +**voided first** and the session then returns to `Open` with the reference +cleared (return-path hygiene, §E.2), no attempt consumed and no event, so the +customer retries on a fresh intent. The void is what makes the reopen safe: an +intent left confirmable could take a payment after the session reopened, when +the sweep no longer watches it and a retry would mint a second intent. A void +the gateway refuses (the payment went through between the fetch and the void) +leaves the session `PaymentProcessing` and consumes an attempt, so the next +pass settles on the real status, and a void that keeps failing stalls. The +customer-initiated release is the exception that keeps the intent: the customer +is on the page with the payment element still bound to it. After the maximum attempts the session is **stalled**: `CheckoutSessionReconciliationStalled` fires **once** (never per-run noise), and the session drops to a **low-frequency retry tier** — not silence. The diff --git a/src/Actions/ReconcileCheckoutSession.php b/src/Actions/ReconcileCheckoutSession.php index ea0cb87..429dcfa 100644 --- a/src/Actions/ReconcileCheckoutSession.php +++ b/src/Actions/ReconcileCheckoutSession.php @@ -31,7 +31,8 @@ * gateway's actual intent outcome decides — captured completes (or refunds on * mismatch: no charge survives without an order), voided/failed reopens, * pending reschedules without consuming an attempt, and an intent left - * waiting on the customer past its window reopens. Exhausted attempts fire + * waiting on the customer past its window is voided and the session reopens. + * Exhausted attempts fire * {@see CheckoutSessionReconciliationStalled} once; the operator `--resolve` * override is the sanctioned stall exit. */ @@ -81,9 +82,9 @@ public function execute(CheckoutSession $session, ?string $resolve = null): stri // Waiting on the customer covers a recorded decline and an // abandoned challenge as well as one still under way, and nothing // settles the first two. Past the window the cart is freed for a - // retry; the intent stays confirmable, so it is kept. + // retry. PaymentIntentStatus::RequiresAction => $this->waitedOnCustomerTooLong($session) - ? $this->reopenKeepingIntent($session, 'intent_'.$status->value) + ? $this->voidAndReopen($session, $gateway, $cart, $reference, 'intent_'.$status->value) : 'pending', PaymentIntentStatus::Captured, @@ -136,6 +137,30 @@ public function release(CheckoutSession $session): string return $this->reopenKeepingIntent($session, 'released'); } + /** + * Gives up on an intent the customer never finished. The void comes + * first: an intent left confirmable could take a payment after the + * session reopened, when nothing settles it and a retry mints a second + * intent. A void the gateway refuses means the payment may have gone + * through since the fetch, so the session stays pinned and the attempt + * counts: the next pass reads the real status. + */ + private function voidAndReopen( + CheckoutSession $session, + ReconcilesPaymentIntents $gateway, + Cart $cart, + string $reference, + string $reason, + ): string { + try { + $gateway->voidIntent($cart, $reference); + } catch (PaymentIntentException) { + return $this->recordAttempt($session); + } + + return $this->reopen($session, $reason); + } + /** * Captured money resolves to exactly one of: an order, or money back. * Money back is flavour-aware: an authorisation that was never captured diff --git a/src/Contracts/Actions/ReconcilesCheckoutSession.php b/src/Contracts/Actions/ReconcilesCheckoutSession.php index 705e99f..4168f18 100644 --- a/src/Contracts/Actions/ReconcilesCheckoutSession.php +++ b/src/Contracts/Actions/ReconcilesCheckoutSession.php @@ -13,7 +13,9 @@ interface ReconcilesCheckoutSession * to `Open`, pending → rescheduled without consuming an attempt. An * intent still waiting on the customer counts as pending only for * `lunar.checkout.reconciliation.requires_action_minutes` after the pin; - * past that the session returns to `Open` with the intent kept. + * past that the intent is voided and the session returns to `Open`. A + * void the gateway refuses keeps the session pinned and consumes an + * attempt. * * `$resolve` is the operator override (`complete` | `refund` | `cancel`) * — the sanctioned stall exit. Returns a stable outcome code. diff --git a/tests/Feature/PaymentHoldTest.php b/tests/Feature/PaymentHoldTest.php index 8fd3ebc..d292177 100644 --- a/tests/Feature/PaymentHoldTest.php +++ b/tests/Feature/PaymentHoldTest.php @@ -844,7 +844,7 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession ->and($session->payment_intent_ref)->toBe('hold_fake_pinned'); }); -it('routes a hold session reopened after waiting on the customer to confirm once the hold is authorised', function () { +it('voids a hold that waited on the customer too long and sends the customer back to the checkout', function () { $session = mintPinnedHoldSession(); $session->forceFill(['payment_processing_at' => now()->subMinutes(31)])->save(); FakeHoldGateway::$fetchStatus = PaymentIntentStatus::RequiresAction; @@ -855,18 +855,9 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession $session->refresh(); expect($session->status)->toBeInstanceOf(Open::class) - ->and($session->payment_intent_ref)->toBe('hold_fake_pinned') - ->and($session->isHoldMode())->toBeTrue() - ->and(FakeHoldGateway::$voidedReferences)->toBeEmpty(); - - FakeHoldGateway::$fetchStatus = PaymentIntentStatus::RequiresCapture; - FakeHoldGateway::$holdAmount = $session->amount_total; - FakeHoldGateway::$walletLabel = 'Apple Pay'; - - $this->get(route('lunar.checkout.processing', $session->uuid)) - ->assertRedirect(route('lunar.checkout.confirm', $session->uuid).'?payment=failed'); - - expect(FakeHoldGateway::$captureCalls)->toBeEmpty(); + ->and(FakeHoldGateway::$voidedReferences)->toBe(['hold_fake_pinned']) + ->and($session->payment_intent_ref)->toBeNull() + ->and(FakeHoldGateway::$captureCalls)->toBeEmpty(); }); it('processing falls back to show when a reopened hold no longer verifies', function () { diff --git a/tests/Feature/PaymentReleaseTest.php b/tests/Feature/PaymentReleaseTest.php index 7647a87..39b5470 100644 --- a/tests/Feature/PaymentReleaseTest.php +++ b/tests/Feature/PaymentReleaseTest.php @@ -11,12 +11,10 @@ use Lunar\Checkout\States\CheckoutSession\Open; use Lunar\Checkout\States\CheckoutSession\PaymentProcessing; use Lunar\Core\Contracts\ReconcilesPaymentIntents; -use Lunar\Core\DataObjects\PaymentAuthorize; use Lunar\Core\DataObjects\PaymentIntentSnapshot; use Lunar\Core\DataObjects\PaymentRefund; use Lunar\Core\DataObjects\PriceValue; use Lunar\Core\Enums\PaymentIntentStatus; -use Lunar\Core\Events\PaymentAttemptEvent; use Lunar\Core\Exceptions\PaymentIntentException; use Lunar\Core\Facades\Payments; use Lunar\Core\Models\Cart; @@ -42,6 +40,11 @@ class ReleaseTestGateway extends OfflinePayment implements ReconcilesPaymentInte /** @var array */ public static array $fetchedCartIds = []; + /** @var array */ + public static array $voided = []; + + public static bool $throwOnVoid = false; + public function fetchIntent(Cart $cart, string $reference): ?PaymentIntentSnapshot { static::$fetchedCartIds[] = $cart->id; @@ -53,7 +56,14 @@ public function fetchIntent(Cart $cart, string $reference): ?PaymentIntentSnapsh return static::$status ? FakeIntents::snapshot($cart, static::$status) : null; } - public function voidIntent(Cart $cart, string $reference): void {} + public function voidIntent(Cart $cart, string $reference): void + { + if (static::$throwOnVoid) { + throw new PaymentIntentException('the intent is no longer voidable'); + } + + static::$voided[] = $reference; + } public function refundIntent(Cart $cart, string $reference, PriceValue $amount, string $idempotencyKey): PaymentRefund { @@ -80,6 +90,8 @@ function pinnedSession(array $overrides = []) ReleaseTestGateway::$status = PaymentIntentStatus::Processing; ReleaseTestGateway::$throwOnFetch = false; ReleaseTestGateway::$fetchedCartIds = []; + ReleaseTestGateway::$voided = []; + ReleaseTestGateway::$throwOnVoid = false; }); dataset('in-flight intent statuses', [ @@ -102,7 +114,7 @@ function pinnedSession(array $overrides = []) ->and(ReleaseTestGateway::$fetchedCartIds)->toBe([(int) $session->cart_reference]); })->with('in-flight intent statuses'); -it('reopens a session whose intent has waited on the customer past the window, keeping the intent', function () { +it('voids an intent that has waited on the customer past the window and reopens the session', function () { Event::fake([CheckoutCompletionFailed::class, CheckoutSessionReconciliationStalled::class]); ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; @@ -113,7 +125,8 @@ function pinnedSession(array $overrides = []) $session->refresh(); expect($session->status)->toBeInstanceOf(Open::class) - ->and($session->payment_intent_ref)->toBe('pi_test_123') + ->and(ReleaseTestGateway::$voided)->toBe(['pi_test_123']) + ->and($session->payment_intent_ref)->toBeNull() ->and($session->payment_processing_at)->toBeNull() ->and($session->reconciliation_attempts)->toBe(0) ->and($session->expires_at->isFuture())->toBeTrue(); @@ -158,7 +171,8 @@ function pinnedSession(array $overrides = []) app(ReconcilesCheckoutSession::class)->execute($session); expect($session->refresh()->status)->toBeInstanceOf(Open::class) - ->and($session->payment_intent_ref)->toBe('pi_test_123'); + ->and(ReleaseTestGateway::$voided)->toBe(['pi_test_123']) + ->and($session->payment_intent_ref)->toBeNull(); }); it('lets the sweep free a cart whose payment the customer abandoned', function () { @@ -178,25 +192,60 @@ function pinnedSession(array $overrides = []) ->and(app(CheckoutDriver::class)->resolveOrCreateSession($cart)->is($session))->toBeTrue(); }); -it('completes a reopened session when the customer finishes the payment afterwards', function () { +it('keeps the session pinned and counts an attempt when the gateway refuses to void the waiting intent', function () { + Event::fake([CheckoutCompletionFailed::class, CheckoutSessionReconciliationStalled::class]); ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + ReleaseTestGateway::$throwOnVoid = true; $session = pinnedSession(['payment_processing_at' => now()->subMinutes(31)]); - app(ReconcilesCheckoutSession::class)->execute($session); + expect(app(ReconcilesCheckoutSession::class)->execute($session))->toBe('retry'); - expect($session->refresh()->status)->toBeInstanceOf(Open::class); + $session->refresh(); + + expect($session->status)->toBeInstanceOf(PaymentProcessing::class) + ->and($session->payment_intent_ref)->toBe('pi_test_123') + ->and($session->reconciliation_attempts)->toBe(1); + + Event::assertNotDispatched(CheckoutCompletionFailed::class); + Event::assertNotDispatched(CheckoutSessionReconciliationStalled::class); +}); + +it('completes on the next pass when the payment went through just as the window closed', function () { + ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + ReleaseTestGateway::$throwOnVoid = true; + + $session = pinnedSession(['payment_processing_at' => now()->subMinutes(31)]); - $order = Cart::query()->findOrFail((int) $session->cart_reference)->createOrder(); - $order->update(['placed_at' => now()]); + // The customer finished between the fetch and the void, so the gateway + // refuses the void and the next fetch reads the money. + app(ReconcilesCheckoutSession::class)->execute($session); + + ReleaseTestGateway::$status = PaymentIntentStatus::Captured; - PaymentAttemptEvent::dispatch(new PaymentAuthorize(success: true, orderId: $order->id, paymentType: 'release-test')); + expect(app(ReconcilesCheckoutSession::class)->execute($session->refresh()))->toBe('completed'); $session->refresh(); expect($session->status)->toBeInstanceOf(Completed::class) - ->and((string) $session->order_reference)->toBe((string) $order->id) - ->and(Order::query()->count())->toBe(1); + ->and(Order::query()->whereNotNull('placed_at')->count())->toBe(1) + ->and((string) $session->order_reference)->toBe((string) Order::query()->firstOrFail()->id); +}); + +it('stalls for the operator when the waiting intent can never be voided', function () { + Event::fake([CheckoutCompletionFailed::class, CheckoutSessionReconciliationStalled::class]); + config()->set('lunar.checkout.reconciliation.max_attempts', 2); + ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + ReleaseTestGateway::$throwOnVoid = true; + + $session = pinnedSession(['payment_processing_at' => now()->subMinutes(31)]); + + expect(app(ReconcilesCheckoutSession::class)->execute($session))->toBe('retry') + ->and(app(ReconcilesCheckoutSession::class)->execute($session->refresh()))->toBe('stalled') + ->and($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class); + + Event::assertDispatchedTimes(CheckoutSessionReconciliationStalled::class, 1); + Event::assertNotDispatched(CheckoutCompletionFailed::class); }); it('counts an attempt when the gateway did not create the reference for the cart', function () { @@ -445,7 +494,8 @@ function pinnedSession(array $overrides = []) ->assertRedirect(route('lunar.checkout.show', $session->uuid).'?payment=failed'); expect($session->refresh()->status)->toBeInstanceOf(Open::class) - ->and($session->payment_intent_ref)->toBe('pi_test_123'); + ->and(ReleaseTestGateway::$voided)->toBe(['pi_test_123']) + ->and($session->payment_intent_ref)->toBeNull(); }); it('processing renders the polling page while the outcome is in flight', function (PaymentIntentStatus $status) { From 16f9f8450fbc84e1df50c15fc12e349d73bb0464 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 09:22:10 +0000 Subject: [PATCH 28/32] fix(payments): never complete a payment whose money already went back A Stripe intent stays succeeded after a refund, so reconciliation still read it as Captured. Two failures followed from ignoring the snapshot's refunded amount. If a pass refunded and then died before its reopen committed, the session stayed pinned, and the next pass completed it and placed an order on refunded money. If the refund landed but its response was lost, every later pass asked for the refund again, alpha.9 Stripe refused because nothing was left to refund, and the session stalled while firing refund-failed on each attempt. execute() and release() now keep the intent snapshot and check its refunded amount before they capture or complete. A fully refunded intent reopens the session under the same lock and guards as a normal refund, without a second refund call, and fires CheckoutCompletionFailed with reason refunded. The refund reference is null there: the snapshot carries amounts only, and the call that made the refund never returned one. A partly refunded intent records an attempt and stalls to the operator, because part of the money is still held with no order. --- spec/0010-cart-session-reconciliation.md | 14 ++- src/Actions/ReconcileCheckoutSession.php | 64 +++++++--- tests/Feature/CompletionFailureRefundTest.php | 117 +++++++++++++++++- tests/Utils/FakeIntents.php | 4 +- 4 files changed, 173 insertions(+), 26 deletions(-) diff --git a/spec/0010-cart-session-reconciliation.md b/spec/0010-cart-session-reconciliation.md index 1086afe..ff3899b 100644 --- a/spec/0010-cart-session-reconciliation.md +++ b/spec/0010-cart-session-reconciliation.md @@ -411,9 +411,17 @@ second order, and the synchronous path creates or adopts it inside `complete()`: attempts fire `CheckoutSessionReconciliationStalled`. `CheckoutCompletionFailed` fires with a `reason` distinguishing **refunded / refund-pending / refund-failed**, carrying the refund - reference when one exists. A non-Lunar driver may substitute its own - remediation (a backorder, a manual-review hold) but MUST NOT silently - retain a charge that produced no order. + reference when one exists. A gateway keeps reporting a refunded intent as + captured (a Stripe intent stays `succeeded`), so every pass reads the + intent snapshot's refunded amount before it completes anything. A fully + refunded intent means an earlier pass returned the money and never + committed the reopen (it died after the refund, or the gateway's answer + was lost): the session moves `→ Open` with `refunded` and no reference, + without a second refund call. A partly refunded intent was refunded by + someone else and still holds money with no order, so it records an attempt + and stalls to the operator. Neither is ever completed. A non-Lunar driver + may substitute its own remediation (a backorder, a manual-review hold) but + MUST NOT silently retain a charge that produced no order. - **The draft survives, unplaced.** Neither a void nor a refund touches the order the pin drafted: it stays on the cart with `placed_at` null and no session points at it. The next Pay on the reopened session reuses that same diff --git a/src/Actions/ReconcileCheckoutSession.php b/src/Actions/ReconcileCheckoutSession.php index 429dcfa..6502d6c 100644 --- a/src/Actions/ReconcileCheckoutSession.php +++ b/src/Actions/ReconcileCheckoutSession.php @@ -19,6 +19,7 @@ use Lunar\Checkout\Support\PaymentIntentGateway; use Lunar\Core\Contracts\ReconcilesPaymentIntents; use Lunar\Core\Contracts\SupportsPaymentHolds; +use Lunar\Core\DataObjects\PaymentIntentSnapshot; use Lunar\Core\DataObjects\PriceValue; use Lunar\Core\Enums\PaymentIntentStatus; use Lunar\Core\Exceptions\PaymentIntentException; @@ -66,11 +67,13 @@ public function execute(CheckoutSession $session, ?string $resolve = null): stri } try { - $status = $gateway->fetchIntent($cart, $reference)?->status; + $intent = $gateway->fetchIntent($cart, $reference); } catch (PaymentIntentException) { return $this->recordAttempt($session); } + $status = $intent?->status; + return match ($status) { // Not an intent the gateway created for this cart: unknowable. null => $this->recordAttempt($session), @@ -88,7 +91,7 @@ public function execute(CheckoutSession $session, ?string $resolve = null): stri : 'pending', PaymentIntentStatus::Captured, - PaymentIntentStatus::RequiresCapture => $this->completeOrRefund($session, $gateway, $cart, $reference, $status), + PaymentIntentStatus::RequiresCapture => $this->completeOrRefund($session, $gateway, $cart, $reference, $intent), PaymentIntentStatus::Voided, PaymentIntentStatus::Failed => $this->reopen($session, 'intent_'.$status->value), @@ -115,21 +118,21 @@ public function release(CheckoutSession $session): string } try { - $status = $gateway->fetchIntent($cart, $reference)?->status; + $intent = $gateway->fetchIntent($cart, $reference); } catch (PaymentIntentException) { return 'unconfirmed'; } - if ($status === null) { + if ($intent === null) { return 'unconfirmed'; } - if (in_array($status, [PaymentIntentStatus::Captured, PaymentIntentStatus::RequiresCapture], true)) { + if (in_array($intent->status, [PaymentIntentStatus::Captured, PaymentIntentStatus::RequiresCapture], true)) { // An authorise-only hold at RequiresCapture is not money // moved: the customer may keep editing and re-confirm, so // reopen with the hold intact instead of forcing completion. - if (! ($session->isHoldMode() && $status === PaymentIntentStatus::RequiresCapture)) { - return $this->completeOrRefund($session, $gateway, $cart, $reference, $status); + if (! ($session->isHoldMode() && $intent->status === PaymentIntentStatus::RequiresCapture)) { + return $this->completeOrRefund($session, $gateway, $cart, $reference, $intent); } } } @@ -167,14 +170,27 @@ private function voidAndReopen( * (a hold, or a policy-mode requires_capture intent) voids; anything * actually captured (a standard intent, or a hold captured by this very * call) refunds. + * + * A gateway keeps reporting a refunded intent as captured, so money an + * earlier pass returned is recognised by the refunded amount. A full + * refund whose reopen never committed (the pass died, or the gateway's + * answer was lost) finishes here without a second refund call. A partial + * one is not this class's doing and leaves money with no order, so it + * stalls to the operator. Neither ever completes. */ private function completeOrRefund( CheckoutSession $session, ReconcilesPaymentIntents $gateway, Cart $cart, string $reference, - PaymentIntentStatus $status, + PaymentIntentSnapshot $intent, ): string { + if ($intent->refunded->value > 0) { + return $intent->refunded->value >= $intent->captured->value + ? $this->moneyBack($session, $gateway, $cart, $reference, captured: true, alreadyRefunded: true) + : $this->recordAttempt($session); + } + // An authorise-only hold is not money moved yet: capture it now, in // the one idempotent place every completion path funnels through, so // a crash between pin and capture recovers on the next reconcile. @@ -219,7 +235,7 @@ private function completeOrRefund( } } - return $this->moneyBack($session, $gateway, $cart, $reference, $holdCaptured || $status === PaymentIntentStatus::Captured); + return $this->moneyBack($session, $gateway, $cart, $reference, $holdCaptured || $intent->status === PaymentIntentStatus::Captured); } /** @@ -236,8 +252,9 @@ private function moneyBack( Cart $cart, string $reference, bool $captured, + bool $alreadyRefunded = false, ): string { - [$outcome, $event] = $session->getConnection()->transaction(function () use ($session, $gateway, $cart, $reference, $captured): array { + [$outcome, $event] = $session->getConnection()->transaction(function () use ($session, $gateway, $cart, $reference, $captured, $alreadyRefunded): array { $locked = CheckoutSession::query()->whereKey($session->getKey())->lockForUpdate()->firstOrFail(); if ($locked->status instanceof Completed) { @@ -282,20 +299,27 @@ private function moneyBack( return ['voided', new CheckoutCompletionFailed($session, $holdMode ? 'hold-voided' : 'voided')]; } - try { - $refund = $gateway->refundIntent( - $cart, - $reference, - $this->pinnedAmount($session), - 'lunar-checkout-refund:'.$reference, - ); - } catch (PaymentIntentException) { - return ['refund-failed', new CheckoutCompletionFailed($session, 'refund-failed')]; + // A refund found on the intent has no reference to pass on: the + // snapshot carries amounts only, and the call that made it never + // returned one. + $refundReference = null; + + if (! $alreadyRefunded) { + try { + $refundReference = $gateway->refundIntent( + $cart, + $reference, + $this->pinnedAmount($session), + 'lunar-checkout-refund:'.$reference, + )->reference; + } catch (PaymentIntentException) { + return ['refund-failed', new CheckoutCompletionFailed($session, 'refund-failed')]; + } } $this->reopen($session, 'refunded'); - return ['refunded', new CheckoutCompletionFailed($session, 'refunded', $refund->reference)]; + return ['refunded', new CheckoutCompletionFailed($session, 'refunded', $refundReference)]; }); // Count the attempt before any listener runs, so a throwing diff --git a/tests/Feature/CompletionFailureRefundTest.php b/tests/Feature/CompletionFailureRefundTest.php index cb267a8..48a59bb 100644 --- a/tests/Feature/CompletionFailureRefundTest.php +++ b/tests/Feature/CompletionFailureRefundTest.php @@ -41,6 +41,14 @@ class CapturedIntentGateway extends OfflinePayment implements CreatesPaymentInte public static bool $refundFails = false; + public static int $captured = 0; + + /** What the gateway holds as refunded, whatever the caller heard back. */ + public static int $refunded = 0; + + /** Thrown once the gateway has made the refund: the caller never hears of it. */ + public static ?Throwable $failAfterRefunding = null; + public function createIntent(Cart $cart): PaymentIntentDescriptor { return new PaymentIntentDescriptor('pi_captured_'.$cart->id); @@ -48,7 +56,7 @@ public function createIntent(Cart $cart): PaymentIntentDescriptor public function fetchIntent(Cart $cart, string $reference): ?PaymentIntentSnapshot { - return FakeIntents::snapshot($cart, PaymentIntentStatus::Captured); + return FakeIntents::snapshot($cart, PaymentIntentStatus::Captured, static::$captured, refunded: static::$refunded); } public function voidIntent(Cart $cart, string $reference): void {} @@ -59,7 +67,16 @@ public function refundIntent(Cart $cart, string $reference, PriceValue $amount, throw new PaymentIntentException('gateway refund failed'); } + if (static::$refunded > 0) { + throw new PaymentIntentException('nothing left to refund'); + } + static::$refunds[] = ['reference' => $reference, 'amount' => $amount->value, 'currency' => $amount->resolveCurrency()->code]; + static::$refunded = $amount->value; + + if (static::$failAfterRefunding !== null) { + throw static::$failAfterRefunding; + } return new PaymentRefund(success: true, reference: 'refund_'.$reference); } @@ -96,6 +113,9 @@ public function component(): string beforeEach(function () { CapturedIntentGateway::$refunds = []; CapturedIntentGateway::$refundFails = false; + CapturedIntentGateway::$captured = 0; + CapturedIntentGateway::$refunded = 0; + CapturedIntentGateway::$failAfterRefunding = null; Payments::extend('captured-intent', fn () => app(CapturedIntentGateway::class)); app(PaymentMethodRegistry::class)->add(CapturedIntentMethod::class); @@ -340,3 +360,98 @@ function capturedSession(): CheckoutSession ->and($session->refresh()->status)->toBeInstanceOf(Open::class) ->and(Order::query()->whereNotNull('placed_at')->count())->toBe(0); }); + +it('never places an order on money an earlier pass refunded before it crashed', function () { + Exceptions::fake(); + Event::fake([CheckoutCompletionFailed::class]); + $session = capturedSession(); + CapturedIntentGateway::$captured = $session->amount_total; + CapturedIntentGateway::$failAfterRefunding = new RuntimeException('connection lost after the refund landed'); + + $placementVetoed = true; + Event::listen(OrderPlacing::class, function () use (&$placementVetoed) { + if ($placementVetoed) { + throw new LogicException('placement vetoed'); + } + }); + + expect(fn () => app(ReconcilesCheckoutSession::class)->execute($session)) + ->toThrow(RuntimeException::class, 'connection lost after the refund landed'); + + expect($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class); + + $placementVetoed = false; + + $outcome = app(ReconcilesCheckoutSession::class)->execute($session); + + expect($outcome)->toBe('refunded') + ->and($session->refresh()->status)->toBeInstanceOf(Open::class) + ->and($session->payment_intent_ref)->toBeNull() + ->and(Order::query()->whereNotNull('placed_at')->count())->toBe(0) + ->and(CapturedIntentGateway::$refunds)->toHaveCount(1); + + Event::assertDispatched( + CheckoutCompletionFailed::class, + fn (CheckoutCompletionFailed $event): bool => $event->reason === 'refunded' && $event->refundReference === null, + ); +}); + +it('reopens instead of retrying a refund whose response was lost', function () { + Event::fake([CheckoutCompletionFailed::class]); + $session = capturedSession(); + $session->forceFill(['cart_fingerprint' => 'stale'])->save(); + CapturedIntentGateway::$captured = $session->amount_total; + CapturedIntentGateway::$failAfterRefunding = new PaymentIntentException('refund response lost'); + + expect(app(ReconcilesCheckoutSession::class)->execute($session->refresh()))->toBe('retry'); + + $outcome = app(ReconcilesCheckoutSession::class)->execute($session->refresh()); + + expect($outcome)->toBe('refunded') + ->and($session->refresh()->status)->toBeInstanceOf(Open::class) + ->and($session->payment_intent_ref)->toBeNull() + ->and(CapturedIntentGateway::$refunds)->toHaveCount(1); + + $reasons = Event::dispatched(CheckoutCompletionFailed::class) + ->map(fn (array $arguments): string => $arguments[0]->reason) + ->countBy(); + + expect($reasons->get('refund-failed'))->toBe(1) + ->and($reasons->get('refunded'))->toBe(1); + + Event::assertDispatched( + CheckoutCompletionFailed::class, + fn (CheckoutCompletionFailed $event): bool => $event->reason === 'refunded' && $event->refundReference === null, + ); +}); + +it('never completes a refunded payment when the customer releases the session', function () { + Event::fake([CheckoutCompletionFailed::class]); + $session = capturedSession(); + CapturedIntentGateway::$captured = $session->amount_total; + CapturedIntentGateway::$refunded = $session->amount_total; + + $outcome = app(ReconcilesCheckoutSession::class)->release($session); + + expect($outcome)->toBe('refunded') + ->and($session->refresh()->status)->toBeInstanceOf(Open::class) + ->and(Order::query()->whereNotNull('placed_at')->count())->toBe(0) + ->and(CapturedIntentGateway::$refunds)->toBeEmpty(); +}); + +it('leaves a partly refunded payment pinned for the operator', function () { + Event::fake([CheckoutCompletionFailed::class]); + $session = capturedSession(); + CapturedIntentGateway::$captured = $session->amount_total; + CapturedIntentGateway::$refunded = 100; + + $outcome = app(ReconcilesCheckoutSession::class)->execute($session); + + expect($outcome)->toBe('retry') + ->and($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class) + ->and($session->reconciliation_attempts)->toBe(1) + ->and(Order::query()->whereNotNull('placed_at')->count())->toBe(0) + ->and(CapturedIntentGateway::$refunds)->toBeEmpty(); + + Event::assertNotDispatched(CheckoutCompletionFailed::class); +}); diff --git a/tests/Utils/FakeIntents.php b/tests/Utils/FakeIntents.php index ea527f4..bd06fd0 100644 --- a/tests/Utils/FakeIntents.php +++ b/tests/Utils/FakeIntents.php @@ -9,7 +9,7 @@ final class FakeIntents { - public static function snapshot(Cart $cart, PaymentIntentStatus $status, int $amount = 0, ?string $walletLabel = null): PaymentIntentSnapshot + public static function snapshot(Cart $cart, PaymentIntentStatus $status, int $amount = 0, ?string $walletLabel = null, int $refunded = 0): PaymentIntentSnapshot { $price = fn (int $value) => new PriceValue($value, $cart->currency); @@ -17,7 +17,7 @@ public static function snapshot(Cart $cart, PaymentIntentStatus $status, int $am status: $status, amount: $price($amount), captured: $price($status === PaymentIntentStatus::Captured ? $amount : 0), - refunded: $price(0), + refunded: $price($refunded), walletLabel: $walletLabel, ); } From 52f610de73fdaaf5c5779e59cf015c618ccb27e1 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 09:24:55 +0000 Subject: [PATCH 29/32] fix(payments): never refund an order the gateway placed before its success pinned the session The placed-order guard in moneyBack() counted an order as placed for this payment only when placed_at was at or after the pin. A session that CompleteSessionOnPaymentSuccess pins is pinned after Stripe's authorize() stamped placed_at, so the guard missed the order unless both fell in the same second. If complete() then threw, the webhook retry returned early without firing the event again, reconciliation read the intent as Captured, complete() failed again, and the refund went out against a placed order. The listener now notes on the session which order the gateway announced and for which intent, before it pins or completes, on every path. The guard treats that order as placed for this payment when the noted intent is the one being reconciled. The intent keeps the scope 3965316 chose: a note left by an earlier payment on the same session does not block the refund of a later one. The time comparison stays as the second signal, for a placement whose announcement never reached the listener. --- spec/0010-cart-session-reconciliation.md | 13 +++-- src/Actions/ReconcileCheckoutSession.php | 42 ++++++++++----- .../CompleteSessionOnPaymentSuccess.php | 44 +++++++++++++++- tests/Feature/CompletionFailureRefundTest.php | 51 +++++++++++++++++++ 4 files changed, 133 insertions(+), 17 deletions(-) diff --git a/spec/0010-cart-session-reconciliation.md b/spec/0010-cart-session-reconciliation.md index ff3899b..b8e5071 100644 --- a/spec/0010-cart-session-reconciliation.md +++ b/spec/0010-cart-session-reconciliation.md @@ -386,10 +386,15 @@ second order, and the synchronous path creates or adopts it inside `complete()`: `Open`, so a session reopened mid-completion is never completed. Under the same lock, money stays put when the session was re-pinned against another intent meanwhile, or when the gateway's own `authorize()` placed an order - for the cart since the pin (the failure came after placement): that records - an attempt and stalls to the operator instead. An attempt is only counted - while the session is still `PaymentProcessing`, and before any listener - runs. Residual: a gateway that places the order in its own transaction + for this payment (the failure came after placement): that records an + attempt and stalls to the operator instead. An order counts as placed for + this payment when the gateway announced it for the session's current intent + (the success listener notes the order and the intent on the session before + it pins or completes, because a session pinned by that announcement is + pinned after the order was placed), or when it was placed since the pin. An + order an earlier checkout of the same cart placed is neither. An attempt is + only counted while the session is still `PaymentProcessing`, and before any + listener runs. Residual: a gateway that places the order in its own transaction without touching the session row (Stripe's `authorize()` does) can still commit that placement while the refund is in flight, so "never refunded" holds against checkout's own completion, not against every gateway's. `CheckoutCompletionFailed` diff --git a/src/Actions/ReconcileCheckoutSession.php b/src/Actions/ReconcileCheckoutSession.php index 6502d6c..4f99068 100644 --- a/src/Actions/ReconcileCheckoutSession.php +++ b/src/Actions/ReconcileCheckoutSession.php @@ -11,6 +11,7 @@ use Lunar\Checkout\Events\CheckoutSessionInvalidated; use Lunar\Checkout\Events\CheckoutSessionReconciliationStalled; use Lunar\Checkout\Exceptions\PaymentConfirmationException; +use Lunar\Checkout\Listeners\CompleteSessionOnPaymentSuccess; use Lunar\Checkout\Models\CheckoutSession; use Lunar\Checkout\States\CheckoutSession\Cancelled; use Lunar\Checkout\States\CheckoutSession\Completed; @@ -267,18 +268,10 @@ private function moneyBack( return ['not-applicable', null]; } - // The gateway's own authorize() placed an order for this cart - // since the pin, before complete() failed: returning the money - // would leave a placed order unpaid. The operator resolves it. - // An order an earlier checkout of the same cart placed does not - // count. - $placedForThisPayment = Order::query() - ->where('cart_id', (int) $session->cart_reference) - ->whereNotNull('placed_at') - ->when($locked->payment_processing_at, fn ($query, $pinnedAt) => $query->where('placed_at', '>=', $pinnedAt)) - ->exists(); - - if ($placedForThisPayment) { + // The gateway's own authorize() placed an order for this + // payment before complete() failed: returning the money would + // leave a placed order unpaid. The operator resolves it. + if ($this->orderPlacedForThisPayment($locked, $reference)) { return ['order-placed', null]; } @@ -336,6 +329,31 @@ private function moneyBack( return $result; } + /** + * Whether the gateway placed an order for the payment the session is + * pinned on. Two signals, either enough: the order the gateway announced + * for this intent ({@see CompleteSessionOnPaymentSuccess} notes it on the + * session), or an order placed since the pin, for a placement whose + * announcement never reached that listener. An order an earlier checkout + * of the same cart placed matches neither. + */ + private function orderPlacedForThisPayment(CheckoutSession $session, string $reference): bool + { + $placed = Order::query() + ->where('cart_id', (int) $session->cart_reference) + ->whereNotNull('placed_at'); + + $announced = $session->meta['gateway_placed_order'] ?? null; + + if (($announced['intent'] ?? null) === $reference && (clone $placed)->whereKey($announced['order'] ?? null)->exists()) { + return true; + } + + return $placed + ->when($session->payment_processing_at, fn ($query, $pinnedAt) => $query->where('placed_at', '>=', $pinnedAt)) + ->exists(); + } + private function resolveByOperator( CheckoutSession $session, ?ReconcilesPaymentIntents $gateway, diff --git a/src/Listeners/CompleteSessionOnPaymentSuccess.php b/src/Listeners/CompleteSessionOnPaymentSuccess.php index f8ff16d..a1e5ef3 100644 --- a/src/Listeners/CompleteSessionOnPaymentSuccess.php +++ b/src/Listeners/CompleteSessionOnPaymentSuccess.php @@ -63,13 +63,55 @@ public function handle(PaymentAttemptEvent $event): void * finishes on the confirm page, which captures at reconcile; it is * never adopted from here. */ - if ($session->status instanceof Open && ($session->isHoldMode() || ! $this->pinForGatewayPayment($session))) { + if ($session->status instanceof Open && $session->isHoldMode()) { + return; + } + + $this->rememberPlacedOrder($session, $authorize->orderId); + + if ($session->status instanceof Open && ! $this->pinForGatewayPayment($session)) { return; } $this->driver->complete($session); } + /** + * Notes on the session which order the gateway placed for the intent the + * session carries, before anything else can fail. If complete() then + * throws, reconciliation must not refund that order's money, and it + * cannot tell by time: a session this listener pins is pinned after the + * order was placed. The intent is kept beside the order so the note + * stops counting once the session moves on to another intent. + * + * Written under the row lock for the reason pinForGatewayPayment() gives, + * in a transaction of its own that commits before that method takes its + * snapshot. + */ + private function rememberPlacedOrder(CheckoutSession $session, int $orderId): void + { + DB::transaction(function () use ($session, $orderId): void { + $locked = CheckoutSession::query() + ->whereKey($session->getKey()) + ->lockForUpdate() + ->first(); + + if ($locked === null || ! ($locked->status instanceof Open || $locked->status instanceof PaymentProcessing)) { + return; + } + + CheckoutSession::query() + ->whereKey($session->getKey()) + ->update([ + 'meta' => json_encode(array_merge((array) $locked->meta, [ + 'gateway_placed_order' => ['order' => $orderId, 'intent' => $locked->payment_intent_ref], + ])), + ]); + }); + + $session->refresh(); + } + /** * The customer confirmed the payment with the gateway directly (e.g. * Stripe.js) without going through the pay boundary, so the session is diff --git a/tests/Feature/CompletionFailureRefundTest.php b/tests/Feature/CompletionFailureRefundTest.php index 48a59bb..eff18ab 100644 --- a/tests/Feature/CompletionFailureRefundTest.php +++ b/tests/Feature/CompletionFailureRefundTest.php @@ -16,11 +16,13 @@ use Lunar\Checkout\States\CheckoutSession\Open; use Lunar\Checkout\States\CheckoutSession\PaymentProcessing; use Lunar\Core\Contracts\CreatesPaymentIntents; +use Lunar\Core\DataObjects\PaymentAuthorize; use Lunar\Core\DataObjects\PaymentIntentDescriptor; use Lunar\Core\DataObjects\PaymentIntentSnapshot; use Lunar\Core\DataObjects\PaymentRefund; use Lunar\Core\DataObjects\PriceValue; use Lunar\Core\Enums\PaymentIntentStatus; +use Lunar\Core\Events\PaymentAttemptEvent; use Lunar\Core\Exceptions\PaymentIntentException; use Lunar\Core\Facades\CartSession; use Lunar\Core\Facades\Payments; @@ -455,3 +457,52 @@ function capturedSession(): CheckoutSession Event::assertNotDispatched(CheckoutCompletionFailed::class); }); + +it('never refunds an order the gateway placed before its success pinned the session', function () { + Exceptions::fake(); + $session = capturedSession(); + $session->forceFill(['status' => Open::$name, 'payment_processing_at' => null])->save(); + + $order = Cart::query()->findOrFail((int) $session->cart_reference)->createOrder(); + $order->update(['placed_at' => now()]); + + // The gateway announces the order after placing it, so the pin that + // announcement causes is later than placed_at. + $this->travel(5)->seconds(); + + Event::listen(OrderPlacing::class, fn () => throw new LogicException('placement vetoed')); + + expect(fn () => PaymentAttemptEvent::dispatch(new PaymentAuthorize(success: true, orderId: $order->id, paymentType: 'captured-intent'))) + ->toThrow(LogicException::class, 'placement vetoed'); + + expect($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class) + ->and($session->payment_processing_at->gt($order->refresh()->placed_at))->toBeTrue(); + + $outcome = app(ReconcilesCheckoutSession::class)->execute($session); + + expect($outcome)->toBe('retry') + ->and(CapturedIntentGateway::$refunds)->toBeEmpty() + ->and($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class) + ->and($session->reconciliation_attempts)->toBe(1); +}); + +it('still refunds a later payment on a session whose earlier payment the gateway placed', function () { + $session = capturedSession(); + + $earlier = Cart::query()->findOrFail((int) $session->cart_reference)->createOrder(); + $earlier->update(['placed_at' => now()->subDay()]); + + $session->forceFill([ + 'payment_intent_ref' => 'pi_captured_later', + 'cart_fingerprint' => 'stale', + 'meta' => array_merge((array) $session->meta, [ + 'gateway_placed_order' => ['order' => $earlier->id, 'intent' => 'pi_captured_earlier'], + ]), + ])->save(); + + $outcome = app(ReconcilesCheckoutSession::class)->execute($session->refresh()); + + expect($outcome)->toBe('refunded') + ->and(CapturedIntentGateway::$refunds)->toHaveCount(1) + ->and($session->refresh()->status)->toBeInstanceOf(Open::class); +}); From 2a8e7431771818d1c83e689ed7c823f278ff89ee Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 09:28:04 +0000 Subject: [PATCH 30/32] fix(payments): leave the listener's copy of the session as read when noting the gateway's order 52f610d refreshed the session after it noted the gateway's order. If another process ended the session between the listener's read and that note, the refreshed copy no longer read Open, so the listener skipped the pin and called complete() on a cancelled session. complete() fired OrderPlacing and then threw CheckoutSessionConflictException. Before 52f610d the pin's locked re-read caught that case and the listener returned. The note no longer refreshes the caller's copy, so the listener decides on the status it read and the pin's re-read catches the change again. --- .../CompleteSessionOnPaymentSuccess.php | 6 ++--- tests/Feature/WebhookFirstPlacementTest.php | 25 +++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/src/Listeners/CompleteSessionOnPaymentSuccess.php b/src/Listeners/CompleteSessionOnPaymentSuccess.php index a1e5ef3..9498b65 100644 --- a/src/Listeners/CompleteSessionOnPaymentSuccess.php +++ b/src/Listeners/CompleteSessionOnPaymentSuccess.php @@ -86,7 +86,9 @@ public function handle(PaymentAttemptEvent $event): void * * Written under the row lock for the reason pinForGatewayPayment() gives, * in a transaction of its own that commits before that method takes its - * snapshot. + * snapshot. The caller's copy of the session is left as it was read, so + * a session another process moved meanwhile is still caught by the pin's + * locked re-read, or by complete()'s guarded write. */ private function rememberPlacedOrder(CheckoutSession $session, int $orderId): void { @@ -108,8 +110,6 @@ private function rememberPlacedOrder(CheckoutSession $session, int $orderId): vo ])), ]); }); - - $session->refresh(); } /** diff --git a/tests/Feature/WebhookFirstPlacementTest.php b/tests/Feature/WebhookFirstPlacementTest.php index 9761a1f..08015c8 100644 --- a/tests/Feature/WebhookFirstPlacementTest.php +++ b/tests/Feature/WebhookFirstPlacementTest.php @@ -247,3 +247,28 @@ function gatewayPlacesOrder(Order $order, bool $success = true): void Log::shouldNotHaveReceived('warning'); }); + +it('leaves a session alone when another process ends it just after the listener read it', function () { + Event::fake([OrderPlacing::class]); + + $cart = CheckoutCart::orderable(); + CartSession::use($cart); + $session = app(CheckoutDriver::class)->resolveOrCreateSession($cart); + $order = $cart->createOrder(); + + // The listener's copy still reads Open; the row another process wrote + // does not. + $ended = false; + CheckoutSession::retrieved(function (CheckoutSession $read) use (&$ended) { + if (! $ended) { + $ended = true; + CheckoutSession::query()->whereKey($read->getKey())->update(['status' => Cancelled::$name]); + } + }); + + gatewayPlacesOrder($order); + + expect($session->refresh()->status)->toBeInstanceOf(Cancelled::class); + + Event::assertNotDispatched(OrderPlacing::class); +}); From 28922021e46c5574219327fa1bcba1a4307357c5 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 09:28:32 +0000 Subject: [PATCH 31/32] docs(checkout): say that the failed-redirect release relies on an undocumented Stripe parameter Stripe's return_url documentation lists payment_intent and payment_intent_client_secret. It does not list redirect_status, which Stripe appends all the same and which show() reads to release a session after a failed redirect. The controller docblock and spec 0010 section F now say so, and say that a return without the parameter only costs the wait for reconciliation. --- spec/0010-cart-session-reconciliation.md | 5 ++++- src/Http/Controllers/CheckoutController.php | 4 ++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/spec/0010-cart-session-reconciliation.md b/spec/0010-cart-session-reconciliation.md index b8e5071..6704636 100644 --- a/spec/0010-cart-session-reconciliation.md +++ b/spec/0010-cart-session-reconciliation.md @@ -539,7 +539,10 @@ ran because the browser had left the page. When that request carries Stripe's page runs the customer-initiated release before it renders: `→ Open` with the intent kept, only on the gateway's word that nothing was captured (a captured intent resolves through §E.2 instead), then a redirect to the retry state. -Without those parameters the session waits out the window above. +Without those parameters the session waits out the window above. Stripe's +return URL documentation lists `payment_intent` but not `redirect_status`, so +the shortcut depends on a parameter Stripe sends without documenting it, and +its absence only costs the wait. ### F.2 One active session per cart diff --git a/src/Http/Controllers/CheckoutController.php b/src/Http/Controllers/CheckoutController.php index 5d15441..85c5f55 100644 --- a/src/Http/Controllers/CheckoutController.php +++ b/src/Http/Controllers/CheckoutController.php @@ -1468,6 +1468,10 @@ private function redirectDeadSession(CheckoutSessionModel $session): RedirectRes * counts. These are the only gateway parameters the controller reads, * and they grant nothing new: the session's owner can already ask for * the same release through releasePayment(). + * + * Stripe's return_url documentation lists `payment_intent` but not + * `redirect_status`, which it sends all the same. A return without it + * is not treated as a failure: the session waits for reconciliation. */ private function returnedFromFailedRedirect(Request $request, CheckoutSessionModel $session): bool { From a7e275b3383e7d0a67a76df7c9926b2661917400 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Thu, 12 Nov 2026 09:32:52 +0000 Subject: [PATCH 32/32] style: return the rejection-copy docblock to its method --- src/Actions/ReconcileCheckoutSession.php | 5 ++--- src/Http/Controllers/CheckoutController.php | 10 +++++----- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/Actions/ReconcileCheckoutSession.php b/src/Actions/ReconcileCheckoutSession.php index 4f99068..8354d42 100644 --- a/src/Actions/ReconcileCheckoutSession.php +++ b/src/Actions/ReconcileCheckoutSession.php @@ -34,9 +34,8 @@ * mismatch: no charge survives without an order), voided/failed reopens, * pending reschedules without consuming an attempt, and an intent left * waiting on the customer past its window is voided and the session reopens. - * Exhausted attempts fire - * {@see CheckoutSessionReconciliationStalled} once; the operator `--resolve` - * override is the sanctioned stall exit. + * Exhausted attempts fire {@see CheckoutSessionReconciliationStalled} once; + * the operator `--resolve` override is the sanctioned stall exit. */ final class ReconcileCheckoutSession implements ReconcilesCheckoutSession { diff --git a/src/Http/Controllers/CheckoutController.php b/src/Http/Controllers/CheckoutController.php index 85c5f55..045e77b 100644 --- a/src/Http/Controllers/CheckoutController.php +++ b/src/Http/Controllers/CheckoutController.php @@ -1455,11 +1455,6 @@ private function redirectDeadSession(CheckoutSessionModel $session): RedirectRes )); } - /** - * Customer-facing copy for a rejected pay attempt. The exception message - * carries the developer reason code ("Payment confirmation rejected - * [fingerprint_mismatch]."), which is for logs, not for the customer. - */ /** * Whether Stripe sent the customer back from a redirect payment method * that did not go through. StripeCard.vue gives Stripe this page as its @@ -1480,6 +1475,11 @@ private function returnedFromFailedRedirect(Request $request, CheckoutSessionMod && $request->query('payment_intent') === $session->payment_intent_ref; } + /** + * Customer-facing copy for a rejected pay attempt. The exception message + * carries the developer reason code ("Payment confirmation rejected + * [fingerprint_mismatch]."), which is for logs, not for the customer. + */ private function paymentRejectionMessage(PaymentConfirmationException $e): string { return match ($e->reason) {