Skip to content

armgit / spree

Public Imported from GitHub
0

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.

Fix: Two Stripe payment sessions on one cart could both be charged (#14777)

Łukasz Adamczyk64a70fe5469a
diff --git a/docs/developer/core-concepts/payments.mdx b/docs/developer/core-concepts/payments.mdx
index 92a55e7fd4..853f6d1210 100644
--- a/docs/developer/core-concepts/payments.mdx
+++ b/docs/developer/core-concepts/payments.mdx
@@ -244,8 +244,10 @@ sequenceDiagram
The frontend calls the API to create a Payment Session for a specific payment method and order. Spree calls the gateway to create a provider-side session (e.g., Stripe PaymentIntent, Adyen Session) and returns the session data including a `client_secret` for the frontend SDK.
<Info>
- The payment session should be created (or recreated) **after** the shipping method is selected, so the amount includes shipping costs. If the order total changes (e.g., customer selects a different shipping rate or applies a coupon), create a new payment session with the updated amount.
+ Create the payment session **after** the shipping method is selected, so the amount includes shipping costs. If the order total changes (a different shipping rate, a coupon), create the session again.
</Info>
+
+ A cart has at most one open session per gateway. Asking Stripe for a session again (a reloaded checkout page, a second tab) cancels the cart's open session and opens a new one, because every open Stripe PaymentIntent can be paid on its own. If that session has already been paid, the request fails with a `gateway_error` and the paid session stays open. Once the order is placed, a background job cancels any session still pending — for example, one left behind when the customer switched to a different payment method — so it can no longer be paid.
</Step>
<Step title="Customer pays on the frontend">
The frontend uses the gateway's JavaScript SDK (e.g., Stripe.js, Adyen Drop-in) with the `client_secret` to securely collect payment details. Card data never touches your server — it goes directly to the payment provider, ensuring [PCI compliance](/developer/security/pci_compliance). If the payment requires **3D Secure** authentication or redirects to an offsite gateway (CashApp, Klarna, etc.), the gateway SDK handles it automatically.
@@ -379,8 +381,9 @@ stateDiagram-v2
<Note>
There is no cancel endpoint. A session reaches `canceled` when the provider
- says so through its webhook, and `expired` when it passes `expires_at`.
- Neither is something a storefront drives.
+ says so through its webhook, or after the order is placed while the session
+ is still pending with nothing paid through it. It reaches `expired` when it
+ passes `expires_at`. Neither is something a storefront drives.
</Note>
#### API
diff --git a/docs/developer/how-to/custom-payment-method.mdx b/docs/developer/how-to/custom-payment-method.mdx
index 19fc8e2375..f20a72f6b9 100644
--- a/docs/developer/how-to/custom-payment-method.mdx
+++ b/docs/developer/how-to/custom-payment-method.mdx
@@ -158,12 +158,24 @@ class MyGateway < Spree::PaymentMethod
payment_session
end
+ # Cancel a session the customer left behind, so it can no longer be paid.
+ # Spree calls this from a background job, once the order is placed, for
+ # every session still pending with nothing paid through it.
+ def cancel_payment_session(payment_session:)
+ MyProvider::Client.new(preferred_api_key).cancel_session(payment_session.external_id)
+ payment_session.cancel
+ end
+
def payment_icon_name
'my-gateway'
end
end
```
+<Warning>
+If your provider lets each open session be paid on its own (as Stripe does with PaymentIntents), a customer with two open sessions can be charged twice — for example, with checkout open in two tabs. Have `create_payment_session` cancel the cart's open sessions for your gateway before opening a new one, and implement `cancel_payment_session`. Leave a session the provider has already accepted, and do not open another. The built-in Stripe gateway does both. If you leave out `cancel_payment_session`, sessions still pending when the order is placed stay open at your provider.
+</Warning>
+
### How the Frontend Uses It
The frontend creates a session, then uses the provider's SDK to collect payment:
@@ -195,7 +207,7 @@ const order = await client.carts.complete(cart.id, options)
```
<Info>
-**Important:** Always create the payment session **after** shipping is selected. If the order total changes (shipping rate change, coupon applied), create a new payment session with the updated amount. The `complete` call in step 5 only handles payment — step 6 finalizes the order.
+**Important:** Always create the payment session **after** shipping is selected. If the order total changes (shipping rate change, coupon applied), update the session with the new amount (`client.carts.paymentSessions.update`) rather than creating another one. The `complete` call in step 5 only handles payment — step 6 finalizes the order.
</Info>
## Step 4: Handle Webhooks (Recommended)
diff --git a/docs/plans/6.0-payment-gateways-monorepo.md b/docs/plans/6.0-payment-gateways-monorepo.md
index 5add8377b7..41358671ed 100644
--- a/docs/plans/6.0-payment-gateways-monorepo.md
+++ b/docs/plans/6.0-payment-gateways-monorepo.md
@@ -145,8 +145,13 @@ session, off-session confirmation, and the storefront's redirect/confirm flow.
(core-table STI subclasses)
- Payment sources (Klarna, Affirm, Alipay, iDEAL, Link, SEPA, bank transfer,
Przelewy24, AfterPay), services (CreatePayment, CreateSource,
- CreatePaymentSession, CreateGatewayWebhooks, UpdateCustomer), jobs, the
+ CreateGatewayWebhooks, UpdateCustomer), jobs, the
`.stripe` scopes on `PaymentMethod`/`GatewayCustomer`
+- `CreatePaymentSession` came over and was deleted as unused (2026-08-12).
+ The pending-session reuse it did for the Rails storefront was briefly in
+ `Gateway::PaymentSessions#create_payment_session` (2026-09-30, V-3726) and
+ removed on 2026-10-04: creating a session always opens a new one, and the
+ earlier open sessions for that gateway are canceled first.
**Apple Pay / Google Pay domain registration is dropped too** (2026-08-10).
It assumed Spree knows the storefront's domain, which a headless install does
@@ -254,6 +259,14 @@ admin" with no conditional-SDK logic. Webhook endpoints are the core v3 ones
`Spree::Payments::HandleWebhook`, the v3 session/webhook endpoints) must be
checked against both gateway implementations — after the port, monorepo CI
does this; until then, coordinate with the external repos before merging.
+- **A cart holds at most one open provider session per gateway**
+ (2026-09-30, V-3726; revised 2026-10-04). A gateway whose sessions can be
+ paid independently cancels the owner's open sessions from
+ `create_payment_session` before opening a new one, and implements
+ `cancel_payment_session`, which a job also calls after placement for the
+ sessions a buyer left behind. An intent the provider has already accepted
+ is not canceled, and no second session is opened. The default
+ `cancel_payment_session` leaves the session pending.
- New payment gateways (e.g. `spree_paypal_checkout`) follow this plan's
shape: own `spree/<provider>` gem, existing name kept if published, lockstep
version, exact `spree` pin, SDK as the gem's own dependency.
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 84e08a0f4b..c711600d8b 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -1,3 +1,23 @@
+## 2026-10-04: Creating a payment session always opens a new one
+
+**Context:** Handing back the cart's open Stripe session and re-pricing it (2026-09-30) drifts from the intent Stripe actually holds. The amount, the saved card, the customer and the ephemeral key are each updated on their own, and a failure partway through leaves Spree and Stripe describing different sessions. The storefront asks for a session every time the payment step loads, so that drift is the common path.
+
+**Decision:** `create_payment_session` opens a new session on every call. Every earlier session for that gateway that can still be paid — open, or failed after a declined confirm — is canceled at the provider first, so a reloaded checkout still cannot pay two intents. The cancel waits until each of those intents has been read: one Stripe has already accepted (paid, authorized, or a debit in flight, including a card charge still processing) fails the request with `payment_in_progress`, and nothing is canceled or opened. A session this cart has already completed is the same refusal, with no call to Stripe. A timeout, a rate limit or an outage while canceling fails the request the same way and leaves the existing intent open. An intent already canceled at Stripe, or one the account the keys now reach does not have, is marked canceled locally and the new session still opens. The placement job that cancels sessions left with no payment is unchanged, and it now includes a failed session.
+
+**Consequences:** A second request answers 201 with a new session, and the previous one is canceled. Checkout that reloads the payment step opens a new PaymentIntent each time. A buyer who already paid still gets `payment_in_progress` rather than a second charge.
+
+**Plans amended:** `6.0-payment-gateways-monorepo.md` (the one-open-session constraint now says the previous session is canceled, not handed back).
+## 2026-09-30: A cart keeps one open Stripe intent, and the ones left behind are canceled once the order is placed
+
+**Context:** Two Stripe payment sessions on one cart could both be paid (V-3726). Reproduced on `main`: a $55.00 cart, two `POST /carts/:id/payment_sessions` answering 201 with two $55.00 PaymentIntents, both confirmed through their own client secrets, and order R1001 placed with one $55.00 payment while Stripe held $110.00. Two concurrent requests are not needed, since the endpoint's cart lock already runs them one after the other: `SpreeStripe::Gateway#create_payment_session` opened a new intent on every call. The standalone gem reused the order's intent (`CreatePaymentIntent`, then `CreatePaymentSession`), but only its Rails checkout called that service, the port left the service with no callers, and it was deleted on 2026-08-12. The storefront creates a session every time the payment step loads, and whenever the buyer picks another saved card, so a second tab was enough. Switching payment method had the same result: a Stripe session followed by a Check payment placed order R1002, paid by check, and the abandoned intent could still be confirmed for $55.00 afterwards. Stripe's notification for the extra charge then fails the payment's cap on what is still owed, is reported, and records nothing.
+
+**Decision:** Creating a Stripe session hands back the owner's open session for that gateway (pending, or being settled), re-priced, with a fresh ephemeral key, since Stripe expires those after an hour. A session opened for another Stripe customer, currency or saved card, or one Stripe will not re-price, is canceled at Stripe before its replacement opens, so no refusal can lock a cart out of paying by card. The exception is an intent Stripe has already accepted: paid, authorized, or a debit in flight. Stripe would cancel an authorization or a processing debit, so the request fails with `payment_in_progress` instead, and nothing is canceled or opened. An intent canceled at Stripe, or one the account the keys now reach does not have, is replaced. Core's payment-session contract gains `PaymentMethod#cancel_payment_session`. When `Orders::Complete` places an order that still has sessions pending with no payment, it enqueues `Payments::CancelUnusedSessionsJob`, which calls it for each one. The cancel is one provider call per session, so it runs in a job rather than holding up placement (review on #14777); the job enqueues only after the surrounding transaction commits, since a webhook places the order inside its own. The Stripe gateway cancels the intent, and the default leaves the session untouched, because a gateway that cannot cancel at its provider must not show as canceled a session that can still be paid. A provider refusal is reported and not retried, and the job's cursor keeps a resumed run from asking the provider again. The reuse lives in the gateway rather than the endpoint because only the gateway can tell a re-priceable intent from one that is paid or canceled.
+
+Rejected: canceling every earlier session whenever a new one is created, which would open a new intent on every checkout load and was not how the gem behaved before. Rejected: refunding or flagging money that arrives for an order already paid; money should not be taken twice in the first place.
+
+**Consequences:** Stripe is left holding at most one charge for the issue's steps: the second confirm is refused as already succeeded. The buyer can still pay twice in one case: they confirm Stripe, and then pay with another method before Stripe's notification completes the cart. That money has already moved, so the cancel is refused and reported, and nothing refunds it. Between placement and the job running, a leftover session can still be paid; the window is how long the queue takes to reach the job. Re-creating a session now answers 201 with an existing session. A buyer who paid in one tab and closed it, on a store without Stripe webhooks, gets `payment_in_progress` in the next tab rather than a second charge; the order still waits for the webhook, as it did before. The cancel runs only at placement, not when `Orders::Complete` replays a placed order: 6.1's pay-balance sessions live on placed orders, and a replay would cancel them. So a crash between placement and the enqueue leaves the leftover payable. Gateways outside the monorepo keep today's behaviour until they implement `cancel_payment_session` and reuse their own pending session; `spree_adyen` has not been checked. The intent's `transfer_group` and `metadata.spree_order_id` still carry the cart's prefixed id and raw database id rather than the order number; that is a separate issue.
+
+**Plans amended:** `6.0-payment-gateways-monorepo.md` (the Stripe keep-set note on `CreatePaymentSession`, a Constraints on Current Work bullet on one open session per gateway).
## 2026-10-02: Adding a fulfillment moves only bought units, and re-prices only the new parcel
**Context:** Adding a fulfillment for an exchanged line could fulfil the replacement instead of the line's own goods (V-3708). Reproduced on `main`, after the 2026-09-25 replacement flag: order R1004, one Stainless kettle at $79.99 plus $5.00 Standard delivery, shipped, exchanged for Matte Black, then raised to 2. The extra Stainless unit joined the replacement's $0.00 fulfillment behind the Matte Black unit. `POST .../fulfillments` for one unit of the line answered 201 with a new fulfillment holding the Matte Black replacement, and delivery went from $5.00 to $15.00. There were two causes. `Fulfillments::Create#fulfillable_units` offered every unshipped unit filed under the line, replacements included, sorted in-stock first and then oldest first, so whether the merchant got the line's goods depended on which unit happened to be created first. Then `reprice_pending_fulfillments` re-quoted every unshipped fulfillment on the order, not just the new one, so the replacement's $0.00 became $5.00 on an order nobody had asked to re-price. The re-pricing loop came over from the old updater's completed-order branch and was never a recorded decision.
diff --git a/spree/core/app/jobs/spree/payments/cancel_unused_sessions_job.rb b/spree/core/app/jobs/spree/payments/cancel_unused_sessions_job.rb
new file mode 100644
index 0000000000..e491d8d72e
--- /dev/null
+++ b/spree/core/app/jobs/spree/payments/cancel_unused_sessions_job.rb
@@ -0,0 +1,61 @@
+module Spree
+ module Payments
+ # Cancels the payment sessions an order was placed without, so none of
+ # them can still be paid. The cursor is the last session handled. A
+ # refusal is handled: asking again cannot change it. A session the
+ # provider could not be reached about is not, so a later run asks
+ # again. The buyer already holds that session's client secret.
+ class CancelUnusedSessionsJob < Spree::BaseJob
+ include ActiveJob::Continuable
+
+ # Continuable resumes only after a cursor is saved. The first session
+ # has none, so an outage there would drop the job and leave the intent
+ # payable. A refusal never reaches this retry: #cancel reports it.
+ retry_on StandardError, wait: :polynomially_longer, attempts: 5
+ # Must come after `retry_on StandardError` so DeserializationError lands in discard.
+ discard_on ActiveJob::DeserializationError
+
+ # Placement can run inside a webhook's transaction; enqueued before it
+ # commits, the job could read the order before its sessions moved onto it.
+ self.enqueue_after_transaction_commit = true
+
+ def perform(order_id)
+ # Outside the step on purpose: runs on every execution, resumes included.
+ @order = Spree::Order.find_by(id: order_id)
+ return if @order.nil?
+
+ Spree::Current.store = @order.store
+
+ step :cancel_sessions
+ end
+
+ private
+
+ def cancel_sessions(step)
+ payment_sessions = @order.payment_sessions.unused.order(:id)
+ payment_sessions = payment_sessions.where(Spree::PaymentSession.arel_table[:id].gt(step.cursor)) if step.cursor
+
+ payment_sessions.each do |payment_session|
+ cancel(payment_session)
+ step.set!(payment_session.id)
+ end
+ end
+
+ def cancel(payment_session)
+ payment_session.payment_method.cancel_payment_session(payment_session: payment_session)
+ rescue Spree::Core::GatewayError => error
+ # An unknown outcome is not a refusal. Cancel can be asked again;
+ # counting it handled leaves the intent payable.
+ raise if error.is_a?(Spree::Core::AmbiguousGatewayError)
+
+ # A refusal means the session was paid after all; retrying
+ # cannot change that, and the order is placed either way.
+ Rails.error.report(
+ error,
+ context: { payment_session_id: payment_session.id, order_id: @order.id },
+ source: 'spree.payments.cancel_unused_sessions'
+ )
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/concerns/spree/payment_session_transitions.rb b/spree/core/app/models/concerns/spree/payment_session_transitions.rb
index 2efc627e94..e249d2b683 100644
--- a/spree/core/app/models/concerns/spree/payment_session_transitions.rb
+++ b/spree/core/app/models/concerns/spree/payment_session_transitions.rb
@@ -24,10 +24,16 @@ module Spree
pending?
end
- %w[complete fail cancel expire].each do |transition|
+ %w[complete fail expire].each do |transition|
define_method(:"can_#{transition}?") { pending? || processing? }
end
+ # A failed confirm can leave the provider intent payable. Cancel is how
+ # placement retires it; the other transitions stay closed.
+ def can_cancel?
+ pending? || processing? || failed?
+ end
+
def process
return false unless transition_to('processing', from: %w[pending])
@@ -50,7 +56,7 @@ module Spree
end
def cancel
- return false unless transition_to('canceled', from: %w[pending processing])
+ return false unless transition_to('canceled', from: %w[pending processing failed])
publish_canceled_event
true
diff --git a/spree/core/app/models/spree/gateway/bogus.rb b/spree/core/app/models/spree/gateway/bogus.rb
index fa764f4856..65ddfd543e 100644
--- a/spree/core/app/models/spree/gateway/bogus.rb
+++ b/spree/core/app/models/spree/gateway/bogus.rb
@@ -117,6 +117,10 @@ module Spree
payment_session.complete
end
+ def cancel_payment_session(payment_session:)
+ payment_session.cancel
+ end
+
def setup_session_supported?
true
end
diff --git a/spree/core/app/models/spree/payment_method.rb b/spree/core/app/models/spree/payment_method.rb
index 867104e926..d9f3ef0677 100644
--- a/spree/core/app/models/spree/payment_method.rb
+++ b/spree/core/app/models/spree/payment_method.rb
@@ -136,6 +136,25 @@ module Spree
raise ::NotImplementedError, 'You must implement complete_payment_session method for this gateway.'
end
+ # Cancels a session nobody is going to complete, so the provider can no
+ # longer take money against it. Called for the sessions left pending when
+ # an order is placed. The default leaves the session untouched: a
+ # gateway that cannot cancel at the provider must not report as canceled
+ # a session that can still be paid.
+ #
+ # Raise Spree::Core::GatewayError only for a refusal, such as a session
+ # that was already paid. A timeout, a rate limit, an outage, or rejected
+ # credentials is raised as itself. Callers that treat those as a refusal
+ # leave a session the buyer can still pay.
+ #
+ # @param payment_session [Spree::PaymentSession]
+ # @return [Boolean] whether the session was canceled
+ # @raise [Spree::Core::GatewayError] when the provider refuses, e.g. the
+ # session has already been paid
+ def cancel_payment_session(payment_session:)
+ false
+ end
+
# Parses an incoming webhook payload from the payment provider.
# Override in gateway subclasses to implement provider-specific webhook parsing.
#
diff --git a/spree/core/app/models/spree/payment_method/session_instrumentation.rb b/spree/core/app/models/spree/payment_method/session_instrumentation.rb
index 27d6832810..9d18c9642c 100644
--- a/spree/core/app/models/spree/payment_method/session_instrumentation.rb
+++ b/spree/core/app/models/spree/payment_method/session_instrumentation.rb
@@ -16,6 +16,7 @@ module Spree
create_payment_session
update_payment_session
complete_payment_session
+ cancel_payment_session
create_payment_setup_session
complete_payment_setup_session
].freeze
diff --git a/spree/core/app/models/spree/payment_session.rb b/spree/core/app/models/spree/payment_session.rb
index 684c940806..611e2fd2f9 100644
--- a/spree/core/app/models/spree/payment_session.rb
+++ b/spree/core/app/models/spree/payment_session.rb
@@ -28,6 +28,9 @@ module Spree
scope :not_expired, -> { where('expires_at IS NULL OR expires_at > ?', Time.current) }
scope :active, -> { not_expired.where(status: %w[pending processing]) }
+ # A declined confirm marks the session failed while its intent can still
+ # be paid, so placement has to cancel those too.
+ scope :unused, -> { where(status: %w[pending failed]).where.missing(:payment) }
before_validation :set_defaults_from_order, on: :create
diff --git a/spree/core/app/workflows/spree/orders/complete.rb b/spree/core/app/workflows/spree/orders/complete.rb
index 9ee249a527..4fd8dcd0af 100644
--- a/spree/core/app/workflows/spree/orders/complete.rb
+++ b/spree/core/app/workflows/spree/orders/complete.rb
@@ -52,6 +52,7 @@ module Spree
step :ensure_placed_status
step :release_stock_reservations
+ step :cancel_unused_payment_sessions
step :update_statuses
step :publish_order_placed
step :complete_sibling_orders
@@ -212,6 +213,15 @@ module Spree
Spree::StockReservations::Release.call(owner: order)
end
+ # A session left behind by a switched method or a second tab could still
+ # be paid, charging the buyer twice. One provider call per session, so
+ # it runs in a job rather than holding up placement.
+ def cancel_unused_payment_sessions
+ return unless order.payment_sessions.unused.exists?
+
+ Spree::Payments::CancelUnusedSessionsJob.perform_later(order.id)
+ end
+
def update_statuses
Spree::Orders::UpdateStatuses.call(order: order)
end
diff --git a/spree/core/spec/jobs/spree/base_job_spec.rb b/spree/core/spec/jobs/spree/base_job_spec.rb
index 94b6323215..1cac718a09 100644
--- a/spree/core/spec/jobs/spree/base_job_spec.rb
+++ b/spree/core/spec/jobs/spree/base_job_spec.rb
@@ -30,33 +30,4 @@ RSpec.describe Spree::BaseJob, type: :job do
expect(retry_handler_classes).not_to include('StandardError')
end
end
-
- # ActiveJob handler lookup is reverse-declaration-order. A subclass that declares
- # `retry_on StandardError` shadows the parent's `discard_on ActiveJob::DeserializationError`
- # (since DeserializationError < StandardError) unless the subclass re-declares the
- # discard *after* its retry. These jobs intentionally do broad retry and must
- # re-declare the discard to keep deserialization failures from retrying forever.
- describe 'broad-retry subclasses re-declare discard_on DeserializationError' do
- # Loading the API gem job from the core spec context: the spec_helper boots the
- # core dummy app, which doesn't load spree_api, so reference it conditionally.
- job_classes = [
- 'Spree::SearchProvider::IndexJob',
- 'Spree::SearchProvider::RemoveJob',
- 'Spree::Events::SubscriberJob'
- ]
-
- job_classes.each do |class_name|
- it "#{class_name} discards DeserializationError instead of retrying" do
- klass = class_name.constantize
- last_matching = klass.rescue_handlers.reverse_each.detect do |class_or_name, _|
- rescued = class_or_name.is_a?(String) ? class_or_name.constantize : class_or_name
- rescued >= ActiveJob::DeserializationError
- end
- expect(last_matching&.first.to_s).to eq('ActiveJob::DeserializationError'),
- "expected #{class_name} to discard DeserializationError, but the most-recently-declared " \
- "matching handler is for #{last_matching&.first.inspect}. Re-declare " \
- "`discard_on ActiveJob::DeserializationError` AFTER `retry_on StandardError`."
- end
- end
- end
end
diff --git a/spree/core/spec/jobs/spree/payments/cancel_unused_sessions_job_spec.rb b/spree/core/spec/jobs/spree/payments/cancel_unused_sessions_job_spec.rb
new file mode 100644
index 0000000000..f73bd78af3
--- /dev/null
+++ b/spree/core/spec/jobs/spree/payments/cancel_unused_sessions_job_spec.rb
@@ -0,0 +1,134 @@
+require 'spec_helper'
+require 'active_job/continuation/test_helper'
+
+RSpec.describe Spree::Payments::CancelUnusedSessionsJob, type: :job do
+ let(:store) { @default_store }
+ let(:order) { create(:order_ready_to_ship, store: store) }
+ let!(:unused_session) { create(:bogus_payment_session, order: order) }
+
+ it 'cancels the sessions left pending with nothing paid through them' do
+ described_class.perform_now(order.id)
+
+ expect(unused_session.reload.status).to eq('canceled')
+ end
+
+ it 'asks the provider to cancel a failed session nothing was paid through' do
+ unused_session.update_columns(status: 'failed')
+
+ described_class.perform_now(order.id)
+
+ expect(unused_session.reload.status).to eq('canceled')
+ end
+
+ it 'leaves a session that settled a payment alone' do
+ order.payments.first.update_columns(response_code: unused_session.external_id)
+
+ described_class.perform_now(order.id)
+
+ expect(unused_session.reload.status).to eq('pending')
+ end
+
+ it 'reports a refusal and carries on with the other sessions' do
+ other_session = create(:bogus_payment_session, order: order, payment_method: unused_session.payment_method)
+ allow_any_instance_of(Spree::PaymentSessions::Bogus).to receive(:cancel).and_wrap_original do |method, *arguments|
+ raise Spree::Core::GatewayError, 'already paid' if method.receiver.id == unused_session.id
+
+ method.call(*arguments)
+ end
+ allow(Rails.error).to receive(:report)
+
+ described_class.perform_now(order.id)
+
+ expect(unused_session.reload.status).to eq('pending')
+ expect(other_session.reload.status).to eq('canceled')
+ expect(Rails.error).to have_received(:report).
+ with(an_instance_of(Spree::Core::GatewayError), hash_including(source: 'spree.payments.cancel_unused_sessions'))
+ end
+
+ it 'does nothing for an order that no longer exists' do
+ expect { described_class.perform_now('nonexistent') }.not_to raise_error
+ end
+
+ describe 'interruption and resume' do
+ include ActiveJob::Continuation::TestHelper
+
+ around do |example|
+ original = ActiveJob::Base.queue_adapter
+ ActiveJob::Base.queue_adapter = :test
+ example.run
+ ensure
+ ActiveJob::Base.queue_adapter = original
+ end
+
+ it 'asks again about a session the provider could not be reached about' do
+ other_session = create(:bogus_payment_session, order: order, payment_method: unused_session.payment_method)
+ second_session = [unused_session, other_session].max_by(&:id)
+ attempts = 0
+ allow_any_instance_of(Spree::PaymentSessions::Bogus).to receive(:cancel).and_wrap_original do |method, *arguments|
+ if method.receiver.id == second_session.id
+ attempts += 1
+ raise Timeout::Error, 'timed out' if attempts == 1
+ end
+
+ method.call(*arguments)
+ end
+
+ described_class.perform_later(order.id)
+ perform_enqueued_jobs
+
+ expect(second_session.reload.status).to eq('pending')
+
+ perform_enqueued_jobs
+
+ expect(attempts).to eq(2)
+ expect(second_session.reload.status).to eq('canceled')
+ end
+
+ it 'asks again about the first session when the provider could not be reached' do
+ attempts = 0
+ allow_any_instance_of(Spree::PaymentSessions::Bogus).to receive(:cancel).and_wrap_original do |method, *arguments|
+ attempts += 1
+ raise Spree::Core::AmbiguousGatewayError, 'connection timed out' if attempts == 1
+
+ method.call(*arguments)
+ end
+ allow(Rails.error).to receive(:report)
+
+ described_class.perform_later(order.id)
+ perform_enqueued_jobs
+
+ expect(unused_session.reload.status).to eq('pending')
+ expect(attempts).to eq(1)
+
+ perform_enqueued_jobs(at: 1.hour.from_now)
+
+ expect(attempts).to eq(2)
+ expect(unused_session.reload.status).to eq('canceled')
+ expect(Rails.error).not_to have_received(:report).
+ with(anything, hash_including(source: 'spree.payments.cancel_unused_sessions'))
+ end
+
+ it 'does not ask the provider again about a session it already refused' do
+ other_session = create(:bogus_payment_session, order: order, payment_method: unused_session.payment_method)
+ first_session, second_session = [unused_session, other_session].sort_by(&:id)
+ refusals = 0
+ allow_any_instance_of(Spree::PaymentSessions::Bogus).to receive(:cancel).and_wrap_original do |method, *arguments|
+ next method.call(*arguments) unless method.receiver.id == first_session.id
+
+ refusals += 1
+ raise Spree::Core::GatewayError, 'already paid'
+ end
+ allow(Rails.error).to receive(:report)
+
+ described_class.perform_later(order.id)
+
+ interrupt_job_during_step(described_class, :cancel_sessions, cursor: first_session.id) do
+ perform_enqueued_jobs
+ end
+ perform_enqueued_jobs
+
+ expect(refusals).to eq(1)
+ expect(second_session.reload.status).to eq('canceled')
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/payment_session_spec.rb b/spree/core/spec/models/spree/payment_session_spec.rb
index 1a35632dfe..a203fcd3f3 100644
--- a/spree/core/spec/models/spree/payment_session_spec.rb
+++ b/spree/core/spec/models/spree/payment_session_spec.rb
@@ -101,6 +101,12 @@ RSpec.describe Spree::PaymentSession, type: :model do
expect(payment_session.cancel).to be true
expect(payment_session.status).to eq('canceled')
end
+
+ it 'transitions from failed to canceled' do
+ payment_session.fail
+ expect(payment_session.cancel).to be true
+ expect(payment_session.status).to eq('canceled')
+ end
end
describe '#expire' do
diff --git a/spree/core/spec/workflows/spree/orders/complete_spec.rb b/spree/core/spec/workflows/spree/orders/complete_spec.rb
index 23a99fa13d..5dc84ac944 100644
--- a/spree/core/spec/workflows/spree/orders/complete_spec.rb
+++ b/spree/core/spec/workflows/spree/orders/complete_spec.rb
@@ -60,6 +60,27 @@ module Spree
end
end
+ # A buyer who switched method, or checked out in a second tab, leaves a
+ # session behind that could still be paid after placement (V-3726).
+ describe 'payment sessions left unused' do
+ let(:draft) { create(:order_ready_to_ship, store: store) }
+ let!(:unused_session) { create(:bogus_payment_session, order: draft) }
+
+ before { draft.update_columns(status: 'draft', completed_at: nil) }
+
+ it 'queues their cancellation' do
+ expect { described_class.call(order: draft, payment_pending: true) }.
+ to have_enqueued_job(Spree::Payments::CancelUnusedSessionsJob).with(draft.id)
+ end
+
+ it 'queues nothing when every session settled a payment' do
+ draft.payments.first.update_columns(response_code: unused_session.external_id)
+
+ expect { described_class.call(order: draft, payment_pending: true) }.
+ not_to have_enqueued_job(Spree::Payments::CancelUnusedSessionsJob)
+ end
+ end
+
it 'is idempotent — an already placed order halts successfully with no side effects' do
order.update_columns(completed_at: Time.current, status: 'placed')
diff --git a/spree/providers/stripe/app/models/spree_stripe/gateway/payment_sessions.rb b/spree/providers/stripe/app/models/spree_stripe/gateway/payment_sessions.rb
index 496ab939d2..b533e02311 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
@@ -15,6 +15,18 @@ module SpreeStripe
MANUAL_CAPTURE_METHOD = 'manual'.freeze
SETUP_FUTURE_USAGE = 'off_session'.freeze
+ # Not a decision about the intent. A timeout and an outage may not have
+ # arrived; a rate limit was turned away before Stripe looked; a bad key
+ # or a missing permission never reached the intent. A refusal of the
+ # cancel itself is an InvalidRequestError and stays out of this list.
+ RETRYABLE_STRIPE_ERRORS = [
+ Stripe::APIConnectionError,
+ Stripe::RateLimitError,
+ Stripe::APIError,
+ Stripe::AuthenticationError,
+ Stripe::PermissionError
+ ].freeze
+
def session_required?
true
end
@@ -23,17 +35,29 @@ module SpreeStripe
Spree::PaymentSessions::Stripe
end
+ # Opens a new session on every call. Each earlier session that can still
+ # be paid is canceled first: every open intent can be paid on its own,
+ # so a reloaded checkout would charge the buyer twice. A session Stripe
+ # has already accepted, a card charge still in flight, or one this cart
+ # has already completed is left as it is and the request fails, because
+ # that money is not dropped to make room for another session.
+ #
# @param order [Spree::Cart, Spree::Order]
# @return [Spree::PaymentSessions::Stripe]
+ # @raise [Spree::Core::GatewayError] when a session has already been
+ # paid, or an earlier one could not be canceled
def create_payment_session(order:, amount: nil, external_data: {})
total = amount.presence || order.total_minus_store_credits
amount_in_cents = Spree::Money.new(total, currency: order.currency).cents
raise Spree::Core::GatewayError, Spree.t('stripe.payment_session_errors.zero_amount') if amount_in_cents.zero?
- gateway_customer = fetch_or_create_customer(order: order)
stripe_payment_method_id = external_data[:stripe_payment_method_id] || external_data['stripe_payment_method_id']
+ replace_open_sessions(order)
+
+ gateway_customer = fetch_or_create_customer(order: order)
+
response = create_payment_intent(
amount_in_cents, order,
payment_method_id: stripe_payment_method_id,
@@ -110,6 +134,29 @@ module SpreeStripe
payment_session
end
+ # Stripe refuses once money has moved, and that refusal is raised so the
+ # session is never shown as canceled while its money stands. An intent
+ # already canceled at Stripe, or unknown to the account the keys now
+ # reach, can no longer be paid, so its session is canceled all the same.
+ # A timeout, a rate limit, an outage, or rejected credentials is raised
+ # as Stripe's own error: wrapped as a refusal, the unused-session job
+ # would count the intent handled while the buyer can still pay it.
+ #
+ # @param payment_session [Spree::PaymentSessions::Stripe]
+ # @return [Boolean] whether the session was canceled
+ # @raise [Spree::Core::GatewayError] when Stripe refuses
+ # @raise [Stripe::StripeError] when Stripe could not be asked
+ def cancel_payment_session(payment_session:)
+ cancel_payment_intent(payment_session.external_id)
+ payment_session.cancel
+ rescue *RETRYABLE_STRIPE_ERRORS
+ raise
+ rescue Stripe::StripeError => error
+ raise Spree::Core::GatewayError, error.message unless payment_intent_unpayable?(payment_session.external_id)
+
+ payment_session.cancel
+ end
+
def retrieve_payment_intent(payment_intent_id)
send_request { |opts| Stripe::PaymentIntent.retrieve({ id: payment_intent_id, expand: ['payment_method'] }, opts) }
end
@@ -170,6 +217,60 @@ module SpreeStripe
private
+ # Nothing is canceled until every still-payable intent has been read. A
+ # later one that Stripe has already accepted must not be reached after
+ # an earlier one was dropped. A completed session is the same refusal
+ # with no provider call: the cart already has its payment.
+ def replace_open_sessions(order)
+ sessions = order.payment_sessions.where(payment_method: self)
+ if sessions.exists?(status: 'completed')
+ raise Spree::Core::GatewayError, Spree.t('stripe.payment_session_errors.payment_in_progress')
+ end
+
+ # A failed confirm leaves the intent payable. It is canceled with the
+ # open ones, unless its charge is still in flight.
+ open_sessions = sessions.active.order(:id).to_a + sessions.where(status: 'failed').order(:id).to_a
+ return if open_sessions.empty?
+
+ open_sessions.each do |payment_session|
+ payment_intent = find_payment_intent(payment_session.external_id)
+ next unless payment_intent && payment_intent_in_progress?(payment_intent)
+
+ raise Spree::Core::GatewayError, Spree.t('stripe.payment_session_errors.payment_in_progress')
+ end
+
+ open_sessions.each do |payment_session|
+ cancel_payment_session(payment_session: payment_session)
+ end
+ rescue *RETRYABLE_STRIPE_ERRORS => error
+ # Checkout speaks GatewayError. The unused-session job does not: it
+ # retries these, and has to see them unwrapped.
+ raise Spree::Core::GatewayError, error.message
+ end
+
+ # A card can sit in `processing` while its charge is in flight.
+ # `payment_intent_accepted?` does not record that yet, and canceling
+ # the intent can drop or refund the charge.
+ def payment_intent_in_progress?(payment_intent)
+ payment_intent.status == 'processing' || payment_intent_accepted?(payment_intent)
+ end
+
+ # nil when the account the keys now reach has no such intent.
+ def find_payment_intent(payment_intent_id)
+ retrieve_payment_intent(payment_intent_id)
+ rescue Stripe::InvalidRequestError => error
+ raise Spree::Core::GatewayError, error.message unless error.code == 'resource_missing'
+ rescue *RETRYABLE_STRIPE_ERRORS
+ raise
+ rescue Stripe::StripeError => error
+ raise Spree::Core::GatewayError, error.message
+ end
+
+ def payment_intent_unpayable?(payment_intent_id)
+ payment_intent = find_payment_intent(payment_intent_id)
+ payment_intent.nil? || payment_intent.status == 'canceled'
+ end
+
# @param order [Spree::Cart, Spree::Order]
# @return [Spree::PaymentResponse]
def create_payment_intent(amount_in_cents, order, payment_method_id: nil, customer_profile_id: nil)
diff --git a/spree/providers/stripe/config/locales/en.yml b/spree/providers/stripe/config/locales/en.yml
index 5fb745d115..78a6ef2e21 100644
--- a/spree/providers/stripe/config/locales/en.yml
+++ b/spree/providers/stripe/config/locales/en.yml
@@ -8,4 +8,5 @@ en:
secret_key_invalid: Secret key is invalid
stripe_unavailable: Something went wrong with Stripe. Try again later.
payment_session_errors:
+ payment_in_progress: A payment for this checkout is already in progress.
zero_amount: Payment session amount must be greater than zero
diff --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.rb
index f35402f808..e51f7a647d 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
@@ -145,6 +145,87 @@ RSpec.describe SpreeStripe::Gateway::PaymentSessions do
end
end
+ describe '#cancel_payment_session' do
+ let(:payment_session) { create(:stripe_payment_session, owner: order, payment_method: gateway, external_id: 'pi_unused_123') }
+
+ it 'cancels the intent and the session' do
+ expect(gateway).to receive(:cancel_payment_intent).with('pi_unused_123')
+
+ gateway.cancel_payment_session(payment_session: payment_session)
+
+ expect(payment_session.reload.status).to eq('canceled')
+ end
+
+ context 'when Stripe refuses' do
+ before do
+ allow(gateway).to receive(:cancel_payment_intent).
+ and_raise(Stripe::InvalidRequestError.new("You cannot cancel this PaymentIntent because it has a status of #{status}.", nil))
+ allow(gateway).to receive(:retrieve_payment_intent).with('pi_unused_123').
+ and_return(Stripe::StripeObject.construct_from(id: 'pi_unused_123', status: status, payment_method: { type: 'card' }))
+ end
+
+ let(:status) { 'succeeded' }
+
+ it 'raises and leaves the session pending while its money stands' do
+ expect { gateway.cancel_payment_session(payment_session: payment_session) }.to raise_error(Spree::Core::GatewayError)
+ expect(payment_session.reload.status).to eq('pending')
+ end
+
+ context 'because the intent was already canceled' do
+ let(:status) { 'canceled' }
+
+ it 'cancels the session' do
+ gateway.cancel_payment_session(payment_session: payment_session)
+
+ expect(payment_session.reload.status).to eq('canceled')
+ end
+ end
+
+ context 'and the follow-up read cannot reach Stripe' do
+ before do
+ allow(gateway).to receive(:retrieve_payment_intent).with('pi_unused_123').
+ and_raise(Stripe::APIConnectionError, 'timed out')
+ end
+
+ it 'raises the timeout instead of a refusal' do
+ expect { gateway.cancel_payment_session(payment_session: payment_session) }.
+ to raise_error(Stripe::APIConnectionError)
+ expect(payment_session.reload.status).to eq('pending')
+ end
+ end
+
+ context 'and the follow-up read is rejected before Stripe looks at the intent' do
+ before do
+ allow(gateway).to receive(:retrieve_payment_intent).with('pi_unused_123').
+ and_raise(Stripe::AuthenticationError, 'Invalid API Key provided')
+ end
+
+ it 'raises that error instead of a refusal' do
+ expect { gateway.cancel_payment_session(payment_session: payment_session) }.
+ to raise_error(Stripe::AuthenticationError)
+ expect(payment_session.reload.status).to eq('pending')
+ end
+ end
+ end
+
+ context 'when Stripe cannot be asked' do
+ [
+ [Stripe::APIConnectionError, 'timed out'],
+ [Stripe::RateLimitError, 'rate limit'],
+ [Stripe::APIError, 'internal error'],
+ [Stripe::AuthenticationError, 'Invalid API Key provided'],
+ [Stripe::PermissionError, 'The provided key does not have the required permissions']
+ ].each do |error_class, message|
+ it "raises #{error_class} and leaves the session pending" do
+ allow(gateway).to receive(:cancel_payment_intent).and_raise(error_class, message)
+
+ expect { gateway.cancel_payment_session(payment_session: payment_session) }.to raise_error(error_class)
+ expect(payment_session.reload.status).to eq('pending')
+ end
+ end
+ end
+ end
+
describe '#update_payment_session' do
let(:payment_session) do
create(:stripe_payment_session,