Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Unify payment settlement on PaymentSession#settle_payment!
Damian Legawiecc819ab5beb45
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 9d3781646c..b53027a5eb 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -705,6 +705,34 @@ means splitting first, and split-then-ship inside an `after_transition` callbackis exactly the shape `6.0-service-workflows.md` prohibits. The workflow wraps themachine as a low-level mechanic, mirroring how `Fulfillments::Create` alreadywraps `mark_shipped`.+## 2026-08-10 — One payment settlement path: PaymentSession#settle_payment!++A settled payment session is noticed on two routes — the storefront's confirm+call and the gateway webhook — and they settled the payment differently. The+webhook path called `Payment#confirm!`, a local state move guessed from the+`auto_capture?` setting. The Stripe sync path called `process!`/`authorize!`,+which route through `gateway_action` back into the gateway's authorize/purchase+verbs: a second Stripe round trip to learn what `complete_payment_session` had+just read from the intent. Worse, those verbs look the owner up in+`store.orders`, which can never find a cart — so checkout-time (cart-owned)+settlement failed with "Order not found". The specs missed it because they+built order-owned sessions.++Now both routes call `PaymentSession#settle_payment!(captured:)` — find or+create the payment, skip if completed, then `confirm!(captured:)`. The+`captured` flag carries what the gateway actually reported instead of the+config guess: `Payment#confirm!` gained the keyword (nil keeps the old+auto_capture fallback for any other caller). Stripe passes intent status+`succeeded`; the webhook path passes `action == :captured`. That also fixes the+dashboard-capture edge: a manual-capture payment captured directly in the+Stripe dashboard now completes on webhook instead of pending forever.++**Consequences:** gateway `complete_payment_session` implementations settle via+`settle_payment!` and never call `process!`/`authorize!` — those verbs remain+core's fallback for payments not covered at completion time, where the owner is+already an Order. A gateway reports facts (`captured` or not); core owns what+the payment does with them.+## 2026-08-10 — Stripe drops Apple Pay domain registration; payment intents are not a subsystemTwo removals from the Stripe port, both from the same question: what does adiff --git a/spree/core/app/models/spree/payment/processing.rb b/spree/core/app/models/spree/payment/processing.rbindex 1cda34328a..5e1820828a 100644--- a/spree/core/app/models/spree/payment/processing.rb+++ b/spree/core/app/models/spree/payment/processing.rb@@ -28,13 +28,19 @@ module Spreehandle_payment_preconditions { process_purchase }end- # Confirms a payment by completing it or pending it depending on when the- # payment method charges. Useful for payments that are authorized/captured- # with SDK/Drop-in elements- def confirm!+ # Confirms a payment already authorized or captured on the gateway side+ # (SDK / Drop-in / payment session flows) — the local state move only, no+ # gateway call.+ #+ # @param captured [Boolean, nil] whether the gateway reports the funds as+ # captured. Callers who know the gateway state pass it; nil falls back+ # to when the payment method charges.+ def confirm!(captured: nil)+ captured = payment_method&.capture_at_checkout? if captured.nil?+started_processing! if checkout?- if payment_method&.capture_at_checkout? && can_complete?+ if captured && can_complete?complete!capture_events.create!(amount: amount)elsif can_pend?diff --git a/spree/core/app/models/spree/payment_session.rb b/spree/core/app/models/spree/payment_session.rbindex 1525486ced..956aa32e06 100644--- a/spree/core/app/models/spree/payment_session.rb+++ b/spree/core/app/models/spree/payment_session.rb@@ -101,6 +101,22 @@ module Spree)end+ # The one place a session settles its payment — used by both routes a+ # settled session is noticed on (the storefront confirm call and the+ # gateway webhook), so the two can never drift apart.+ #+ # @param captured [Boolean] whether the gateway reports the funds as+ # captured; false means authorized only, so the payment pends+ # @param metadata [Hash] gateway-specific metadata for payment creation+ # @return [Spree::Payment, nil]+ def settle_payment!(captured:, metadata: {})+ settled_payment = find_or_create_payment!(metadata)+ return settled_payment if settled_payment.blank? || settled_payment.completed?++ settled_payment.confirm!(captured: captured)+ settled_payment+ end+# @return [Spree::Cart, Spree::Order, nil]def ownerorder || cartdiff --git a/spree/core/app/workflows/spree/payments/handle_webhook.rb b/spree/core/app/workflows/spree/payments/handle_webhook.rbindex 0e561d6c53..8cd7157d85 100644--- a/spree/core/app/workflows/spree/payments/handle_webhook.rb+++ b/spree/core/app/workflows/spree/payments/handle_webhook.rb@@ -65,12 +65,12 @@ module Spreefailure(payment_session, error.message)end- # Spree::Payment#confirm! honors when the payment method charges:- # charging at checkout completes and records a capture event, otherwise- # the payment pends (auth-only, payment_state=balance_due).+ # :captured means the gateway reports the funds as moved, so the payment+ # completes with a capture event; :authorized pends it (auth-only,+ # payment_state=balance_due) until an explicit capture. The webhook's+ # action decides, not the method's capture timing.def ensure_payment- @payment = payment_session.find_or_create_payment!(metadata)- payment.confirm! if payment.present? && !payment.completed?+ @payment = payment_session.settle_payment!(captured: action == :captured, metadata: metadata)enddef complete_sessiondiff --git a/spree/core/spec/models/spree/payment_session_spec.rb b/spree/core/spec/models/spree/payment_session_spec.rbindex 0a7c772403..7dccac85b6 100644--- a/spree/core/spec/models/spree/payment_session_spec.rb+++ b/spree/core/spec/models/spree/payment_session_spec.rb@@ -164,6 +164,36 @@ RSpec.describe Spree::PaymentSession, type: :model doendend+ describe '#settle_payment!' do+ context 'when the funds are captured' do+ it 'creates the payment and completes it with a capture event' do+ payment = payment_session.settle_payment!(captured: true)++ expect(payment).to be_completed+ expect(payment.capture_events.sum(:amount)).to eq(payment.amount)+ expect(payment.response_code).to eq(payment_session.external_id)+ end+ end++ context 'when the funds are only authorized' do+ it 'creates the payment and pends it' do+ payment = payment_session.settle_payment!(captured: false)++ expect(payment).to be_pending+ expect(payment.capture_events).to be_empty+ end+ end++ context 'when the payment is already completed' do+ it 'leaves it untouched without a duplicate capture event' do+ first_settlement = payment_session.settle_payment!(captured: true)++ expect { payment_session.settle_payment!(captured: true) }.+ not_to change { first_settlement.reload.capture_events.count }+ end+ end+ end+describe '#amount_in_cents' doit 'returns amount in cents' dopayment_session.update!(amount: 99.99)diff --git a/spree/core/spec/models/spree/payment_spec.rb b/spree/core/spec/models/spree/payment_spec.rbindex 319a97b364..ec94447d63 100644--- a/spree/core/spec/models/spree/payment_spec.rb+++ b/spree/core/spec/models/spree/payment_spec.rb@@ -539,6 +539,30 @@ describe Spree::Payment, type: :model doendendend++ # The caller reporting actual gateway state overrides the auto_capture+ # guess in both directions.+ context 'when the funds are captured on a manual-capture method' do+ let(:auto_capture) { false }++ it 'completes the payment with a capture event' do+ payment.confirm!(captured: true)++ expect(payment.reload).to be_completed+ expect(payment.capture_events.count).to eq(1)+ end+ end++ context 'when the funds are not captured on an auto-capture method' do+ let(:auto_capture) { true }++ it 'pends the payment' do+ payment.confirm!(captured: false)++ expect(payment.reload).to be_pending+ expect(payment.capture_events).to be_empty+ end+ endenddescribe '#capture!' dodiff --git a/spree/providers/stripe/app/models/spree_stripe/gateway/payment_sessions.rb b/spree/providers/stripe/app/models/spree_stripe/gateway/payment_sessions.rbindex 601cac320e..f4ada96bc2 100644--- a/spree/providers/stripe/app/models/spree_stripe/gateway/payment_sessions.rb+++ b/spree/providers/stripe/app/models/spree_stripe/gateway/payment_sessions.rb@@ -97,19 +97,12 @@ module SpreeStripecharge = payment_session.stripe_chargepatch_wallet_address(payment_session.owner, charge) if charge.present?- payment_session.find_or_create_payment!-- payment = payment_session.payment- if payment.present? && !payment.completed?- # The `else` covers requires_capture (manual capture), processing- # (delayed-notification banks) and requires_action (bank transfer- # awaiting funds) — all authorization-only states.- if payment_intent_successful?(stripe_payment_intent)- payment.process!- else- payment.authorize!- end- end+ # `succeeded` is the only status where funds have moved. The other+ # accepted statuses — requires_capture (manual capture), processing+ # (delayed-notification banks), requires_action (bank transfer awaiting+ # funds) — settle as authorization-only, completed later by webhook or+ # explicit capture.+ payment_session.settle_payment!(captured: payment_intent_successful?(stripe_payment_intent))payment_session.complete unless payment_session.completed?payment_sessiondiff --git a/spree/providers/stripe/spec/models/spree_stripe/gateway/payment_sessions_spec.rb b/spree/providers/stripe/spec/models/spree_stripe/gateway/payment_sessions_spec.rbindex 6dae39f9e9..07d6be3b26 100644--- a/spree/providers/stripe/spec/models/spree_stripe/gateway/payment_sessions_spec.rb+++ b/spree/providers/stripe/spec/models/spree_stripe/gateway/payment_sessions_spec.rb@@ -213,13 +213,12 @@ RSpec.describe SpreeStripe::Gateway::PaymentSessions docontext 'when the payment intent is accepted and succeeded' dolet(:stripe_pi) { Stripe::StripeObject.construct_from(id: 'pi_complete_123', status: 'succeeded', latest_charge: 'ch_test_123', payment_method: { type: 'card' }) }+ let(:payment) { create(:payment, order: order, payment_method: gateway, amount: order.total, state: 'checkout') }before doallow(gateway).to receive(:retrieve_payment_intent).and_return(stripe_pi)allow(gateway).to receive(:retrieve_charge).and_return(stripe_charge)- allow(payment_session).to receive(:find_or_create_payment!).and_return(- create(:payment, order: order, payment_method: gateway, amount: order.total, state: 'checkout')- )+ allow(payment_session).to receive(:find_or_create_payment!).and_return(payment)endit 'completes the session' do@@ -227,9 +226,11 @@ RSpec.describe SpreeStripe::Gateway::PaymentSessions doexpect(payment_session.reload.status).to eq('completed')end- it 'creates a payment record' do- expect(payment_session).to receive(:find_or_create_payment!)+ it 'completes the payment with a capture event' dogateway.complete_payment_session(payment_session: payment_session)++ expect(payment.reload).to be_completed+ expect(payment.capture_events.sum(:amount)).to eq(payment.amount)enddescribe 'wallet billing address patching' do@@ -385,12 +386,13 @@ RSpec.describe SpreeStripe::Gateway::PaymentSessions doallow(gateway).to receive(:retrieve_charge).and_return(stripe_charge)allow(gateway).to receive(:payment_intent_accepted?).and_return(true)allow(payment_session).to receive(:find_or_create_payment!).and_return(payment)- allow(payment_session).to receive(:payment).and_return(payment)end- it 'authorizes the payment instead of processing' do- expect(payment).to receive(:authorize!)+ it 'pends the payment instead of capturing it' dogateway.complete_payment_session(payment_session: payment_session)++ expect(payment.reload).to be_pending+ expect(payment.capture_events).to be_emptyendend@@ -427,14 +429,64 @@ RSpec.describe SpreeStripe::Gateway::PaymentSessions dobefore doallow(gateway).to receive(:retrieve_payment_intent).and_return(stripe_pi)allow(payment_session).to receive(:find_or_create_payment!).and_return(payment)- allow(payment_session).to receive(:payment).and_return(payment)end- it 'completes the session and authorizes the payment without capturing' do- expect(payment).to receive(:authorize!)- expect(payment).not_to receive(:process!)+ it 'completes the session with the payment pending, not captured' do+ gateway.complete_payment_session(payment_session: payment_session)++ expect(payment_session.reload.status).to eq('completed')+ expect(payment.reload).to be_pending+ expect(payment.capture_events).to be_empty+ end+ end++ # Regression: settlement used to route through the gateway's authorize and+ # purchase verbs, which look the owner up in store.orders — a lookup that+ # can never find a cart, so every checkout-time (cart-owned) settlement+ # failed with 'Order not found'.+ context 'when the session is owned by a cart' do+ let(:cart) { create(:cart_with_line_items, store: store, customer: customer) }+ let(:payment_session) do+ create(:stripe_payment_session, owner: cart, payment_method: gateway, amount: cart.total)+ end+ let(:stripe_pi) do+ Stripe::StripeObject.construct_from(+ id: payment_session.external_id,+ status: 'succeeded',+ latest_charge: 'ch_cart_123',+ payment_method: { type: 'card' }+ )+ end+ let(:cart_charge) do+ Stripe::StripeObject.construct_from(+ id: 'ch_cart_123',+ payment_method: 'pm_cart_123',+ billing_details: {+ name: 'John Doe', email: '[email protected]', phone: nil,+ address: { line1: '100 California Street', line2: nil, city: 'San Francisco',+ state: 'CA', postal_code: '94111', country: 'US' }+ },+ payment_method_details: {+ type: 'card',+ card: { brand: 'visa', last4: '4242', exp_month: 12, exp_year: 2035, fingerprint: 'fp_cart',+ checks: nil, wallet: nil }+ }+ )+ end++ before do+ allow(gateway).to receive(:retrieve_payment_intent).and_return(stripe_pi)+ allow(gateway).to receive(:retrieve_charge).and_return(cart_charge)+ allow(gateway).to receive(:fetch_or_create_customer).and_return(nil)+ end++ it 'settles the payment on the cart' dogateway.complete_payment_session(payment_session: payment_session)+expect(payment_session.reload.status).to eq('completed')+ payment = cart.payments.last+ expect(payment).to be_completed+ expect(payment.response_code).to eq(payment_session.external_id)endend