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
Fix the payment findings from code review
Damian Legawiecf85762e6ddeb
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 397288a126..b4fecdd457 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -330,6 +330,38 @@ ships in the OSS Admin API; first-run configures the one store.Consequences: Admin API code must never assume `current_store` is the defaultstore, and store-touching cache keys must carry the store id by construction.Plan: `6.0-store-context-and-first-run-setup.md`.+## 2026-08-12 — Code review findings on the payment surface, and what they corrected++The review of the day's work surfaced ten findings; all ten held up. The ones+that correct earlier entries in this log:++- **Profile creation had become dead code.** The after_save removal documented+ "creation flows call this explicitly" with no flow calling it. Now they do:+ `Payments::Create` profiles after its transaction, the admin payment+ endpoint after its lock (a source that cannot be profiled destroys the+ half-created payment, matching the old rollback), and specs that create+ payments programmatically call it themselves.+- **The webhook path settled with cold provider caches** — up to three Stripe+ round trips inside the order lock, contradicting settle_payment!'s own+ comment. `PaymentSession#prepare_for_settlement!` (no-op default; Stripe+ warms intent, charge and gateway customer) runs before HandleWebhook's+ lock, making the comment true.+- **capture! completed before splitting**, so a partial capture published+ payment.completed at the full amount. The split's row work now happens+ inside the lock before complete; only the remainder's authorize runs after.+- **settle_payment!'s completed? guard read a stale cached payment** — the+ same check-then-act shape one level down. Closed with a DB-state recheck+ inside the lock, not a reload (reload discards skip_source_requirement, as+ it discards card numbers in capture!).+- **The completion fence broke reads**: GET /carts/:id runs Checkout::Advance+ under with_order_lock and answered 409 for the claim window. The advance+ now skips claimed carts (`Cart#completion_claimed?`, which owns the TTL).+- Store scoping and correctness details: refund reasons resolve through+ `current_store.refund_reasons`; Stripe's cancel passes the store to+ order_canceled_reason; the customer payload sends ISO codes like the+ shipping payload; setup_intent.succeeded left SUPPORTED_EVENTS until core's+ webhook contract can route setup sessions.+## 2026-08-12 — Amount consistency during gateway operations: the completion claim, not a lockRaised as a challenge to the lock removals: shouldn't the order be locked for@@ -387,10 +419,12 @@ Two real bugs found and fixed:refunds both validated against the pre-refund balance and both credited —a double-clicked 50% refund refunded 100% (Stripe's credit carries noidempotency key). The refund row is what reserves the balance- (credit_allowed sums rows), so creation now takes `payment.with_lock` at- all five sites — Refunds::Create, the returns/exchange/claim drain loops,- and Stripe's cancel verb — making the create-time validation trustworthy.- `perform!` stays outside the lock.+ (credit_allowed sums rows), so creation takes `payment.with_lock` in one+ place: `Refunds::Create`, which the returns/exchange/claim drain loops and+ Stripe's cancel verb all route through (code review caught the first+ version duplicating the lock/credit/compensation sequence at five sites —+ which also meant refund hooks and payment.refunded fired only for admin+ refunds). `perform!` stays outside the lock.Judged acceptable, with reasons on record:diff --git a/spree/api/app/controllers/concerns/spree/api/v3/order_lock.rb b/spree/api/app/controllers/concerns/spree/api/v3/order_lock.rbindex 1a52a01f97..4d8fd50cc8 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/order_lock.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/order_lock.rb@@ -26,8 +26,7 @@ module Spree# checked after acquiring the lock so it cannot race the claim# being written. The TTL matches guard_concurrent_completion — a# crashed completion must not brick its cart.- if order.is_a?(Spree::Cart) && order.completing? &&- order.completing_at > Spree::Carts::Complete::COMPLETING_TTL.ago+ if order.is_a?(Spree::Cart) && order.completion_claimed?next render_error(code: 'completion_in_progress',message: Spree.t(:cart_completion_in_progress),diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/payments_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/payments_controller.rbindex 9c3b38902d..4f77435c6e 100644--- a/spree/api/app/controllers/spree/api/v3/admin/orders/payments_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/payments_controller.rb@@ -27,12 +27,21 @@ module Spreeauthorize_resource!(@resource, :create)- if @resource.save- render json: serialize_resource(@resource), status: :created- else- render_validation_error(@resource.errors)- end+ render_validation_error(@resource.errors) unless @resource.save+ end+ return if performed?++ # Gateway I/O — outside the order lock. A source that cannot be+ # profiled must not linger on a half-created payment; the old+ # after_save callback rolled the whole save back.+ begin+ @resource.create_payment_profile if @resource.profiles_supported?+ rescue Spree::Core::GatewayError => e+ @resource.destroy+ return render_service_error(e.message)end++ render json: serialize_resource(@resource), status: :createdend# PATCH /api/v3/admin/orders/:order_id/payments/:id/capturediff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/refunds_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/refunds_controller.rbindex daf6691a67..55f00a7f31 100644--- a/spree/api/app/controllers/spree/api/v3/admin/orders/refunds_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/refunds_controller.rb@@ -15,8 +15,10 @@ module Spree# double submit cannot credit twice.def createpayment = @parent.payments.accessible_by(current_ability, :update).find_by_prefix_id!(params[:payment_id])- reason = Spree::RefundReason.accessible_by(current_ability, :show).find_by_prefix_id!(params[:refund_reason_id]) if params[:refund_reason_id].present?- reason ||= Spree::RefundReason.accessible_by(current_ability, :show).first+ # Scoped to the store, not just the ability — a reason id from+ # another store must 404, not attach.+ reason = current_store.refund_reasons.accessible_by(current_ability, :show).find_by_prefix_id!(params[:refund_reason_id]) if params[:refund_reason_id].present?+ reason ||= current_store.refund_reasons.accessible_by(current_ability, :show).firstauthorize_resource!(payment.refunds.build(amount: params[:amount], reason: reason), :create)diff --git a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rbindex 3ec299df94..ff8bde8174 100644--- a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb@@ -17,7 +17,9 @@ module Spreedef show@cart = find_cart- if @cart.ship_address_id.present? && @cart.fulfillments.empty?+ # Never under a live completion claim — the advance mutates under+ # with_order_lock, and a read must not 409 against the fence.+ if @cart.ship_address_id.present? && @cart.fulfillments.empty? && [email protected]_claimed?ActiveRecord::Base.connected_to(role: :writing) dowith_order_lock { Spree::Checkout::Advance.call(order: @cart) }enddiff --git a/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rbindex 6cb5fc5005..d535356526 100644--- a/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb@@ -971,7 +971,7 @@ RSpec.describe Spree::Api::V3::Store::CartsController, type: :controller doendit 'completes the checkout' do- create(:payment, cart: order, amount: order.reload.total)+ create(:payment, cart: order, amount: order.reload.total).tap(&:create_payment_profile)post :complete, params: { id: order.prefixed_id }@@ -981,7 +981,7 @@ RSpec.describe Spree::Api::V3::Store::CartsController, type: :controller doendit 'releases stock reservations on successful completion' do- create(:payment, cart: order, amount: order.reload.total)+ create(:payment, cart: order, amount: order.reload.total).tap(&:create_payment_profile)line_item = order.line_items.firstline_item.variant.stock_items.first.update!(backorderable: false)line_item.variant.stock_items.first.set_count_on_hand(20)@@ -1053,7 +1053,7 @@ RSpec.describe Spree::Api::V3::Store::CartsController, type: :controller dorequest.headers['Authorization'] = nilrequest.headers['x-spree-token'] = guest_order.token- create(:payment, cart: guest_order, order: nil, amount: guest_order.reload.total)+ create(:payment, cart: guest_order, order: nil, amount: guest_order.reload.total).tap(&:create_payment_profile)post :complete, params: { id: guest_order.prefixed_id }diff --git a/spree/core/app/models/spree/cart.rb b/spree/core/app/models/spree/cart.rbindex 1379af1c04..a63096d0a4 100644--- a/spree/core/app/models/spree/cart.rb+++ b/spree/core/app/models/spree/cart.rb@@ -119,11 +119,24 @@ module Spreesuper || (completed_at.present? && !completed_at_changed?)end+ # How long a completion attempt may hold the cart before its claim goes+ # stale — a crashed completion must not brick its cart.+ COMPLETING_CLAIM_TTL = 5.minutes+# @return [Boolean] whether a completion attempt currently holds this cartdef completing?completing_at.present?end+ # Whether a live completion attempt holds this cart — its totals are fixed+ # and money may be moving, so mutations must wait until it finishes or the+ # claim goes stale.+ #+ # @return [Boolean]+ def completion_claimed?+ completing_at.present? && completing_at > COMPLETING_CLAIM_TTL.ago+ end+# Recomputes and persists money totals (item, tax, promotion, delivery)# and derived item counts. Convenience for# {Spree::Carts::RecalculateTotals}.diff --git a/spree/core/app/models/spree/payment.rb b/spree/core/app/models/spree/payment.rbindex f0cc632ef4..d40c11be69 100644--- a/spree/core/app/models/spree/payment.rb+++ b/spree/core/app/models/spree/payment.rb@@ -386,17 +386,23 @@ module Spree+ # Row work only — moves the uncaptured remainder onto a new pending+ # payment and shrinks this one to what was captured. The caller authorizes+ # the returned remainder at the gateway afterwards, outside any lock.+ #+ # @return [Spree::Payment, nil] the remainder payment, or nil when fully captureddef split_uncaptured_amount- if uncaptured_amount > 0- owner.payments.create!(- amount: uncaptured_amount,- payment_method: payment_method,- source: source,- state: 'pending',- capture_on_dispatch: true- ).authorize!- update(amount: captured_amount)- end+ return if uncaptured_amount <= 0++ remainder = owner.payments.create!(+ amount: uncaptured_amount,+ payment_method: payment_method,+ source: source,+ state: 'pending',+ capture_on_dispatch: true+ )+ update(amount: captured_amount)+ remainderenddef update_orderdiff --git a/spree/core/app/models/spree/payment/processing.rb b/spree/core/app/models/spree/payment/processing.rbindex c82a4768c5..06e6d5acfa 100644--- a/spree/core/app/models/spree/payment/processing.rb+++ b/spree/core/app/models/spree/payment/processing.rb@@ -78,6 +78,7 @@ module Spreehandle_response(response, :complete, :failure) unless response.success?already_captured = false+ remainder = nilowner.with_lock do# DB-state recheck, deliberately not a reload — reload would# discard the in-memory source (card numbers never persist).@@ -85,6 +86,9 @@ module Spreealready_captured = trueelsecapture_events.create!(amount: ::Money.new(amount, currency).to_f)+ # Split before completing, so payment.completed publishes with+ # the captured amount and the order recomputes from correct rows.+ remainder = split_uncaptured_amounthandle_response(response, :complete, :failure)endend@@ -92,7 +96,7 @@ module Spree# Authorizes the remainder at the gateway — its own network call,# so it stays outside the lock.- split_uncaptured_amount+ remainder&.authorize!trueendenddiff --git a/spree/core/app/models/spree/payment_session.rb b/spree/core/app/models/spree/payment_session.rbindex f2063d53ab..769534bfb0 100644--- a/spree/core/app/models/spree/payment_session.rb+++ b/spree/core/app/models/spree/payment_session.rb@@ -101,26 +101,44 @@ module Spree)end+ # Fetches whatever settlement will need from the provider, so a caller+ # that settles inside a lock (the webhook path) holds it across no+ # provider I/O. Gateway session subclasses override; no-op by default.+ #+ # @return [Spree::PaymentSession] self+ def prepare_for_settlement!+ self+ 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.#+ # Serialized on the owner's row: the two routes can race, and the+ # completed? guard alone is check-then-act — two concurrent settlements+ # would each record a capture event, doubling captured_amount. The lock+ # wraps only the local settlement, never gateway I/O — callers fetch+ # provider data first (the confirm path as it verifies the session, the+ # webhook path via prepare_for_settlement!) — and nests as a no-op inside+ # HandleWebhook's own owner lock.+ ## @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]- # Serialized on the owner's row: the storefront confirm and the gateway- # webhook can race, and the completed? guard alone is check-then-act — two- # concurrent settlements would each record a capture event, doubling- # captured_amount. The lock wraps only the local settlement, never gateway- # I/O (callers fetch what they need from the provider first), and nests as- # a no-op inside HandleWebhook's own owner lock.def settle_payment!(captured:, metadata: {})owner.with_lock dosettled_payment = find_or_create_payment!(metadata)- if settled_payment.present? && !settled_payment.completed?- settled_payment.confirm!(captured: captured)+ if settled_payment.present?+ # DB-state recheck, deliberately not a reload — the payment may have+ # been cached on this instance before the lock (a concurrent+ # settlement could have completed it), but reload would discard+ # in-memory state like skip_source_requirement.+ already_completed = settled_payment.completed? ||+ Spree::Payment.where(id: settled_payment.id, state: 'completed').exists?++ settled_payment.confirm!(captured: captured) unless already_completedendsettled_paymentdiff --git a/spree/core/app/services/spree/payments/create.rb b/spree/core/app/services/spree/payments/create.rbindex aaf1bfa759..c509c3321f 100644--- a/spree/core/app/services/spree/payments/create.rb+++ b/spree/core/app/services/spree/payments/create.rb@@ -9,6 +9,9 @@ module Spreerun :find_or_create_payment_sourcerun :save_paymentend+ # Gateway I/O — after the transaction, on the in-memory graph (some+ # gateways need the raw card number, which never persists).+ run :store_gateway_profileendprotected@@ -56,11 +59,23 @@ module Spreepayment = order.payments.new(payment_attributes)if payment.save- success(payment)+ success(payment: payment)elsefailure(payment)endend++ # A payment that cannot be profiled must not linger half-created — the+ # old after_save callback rolled the whole save back on gateway failure.+ def store_gateway_profile(payment:)+ return success(payment) unless payment.profiles_supported?++ payment.create_payment_profile+ success(payment)+ rescue Spree::Core::GatewayError => e+ payment.destroy+ failure(payment, e.message)+ endendendenddiff --git a/spree/core/app/workflows/spree/carts/complete.rb b/spree/core/app/workflows/spree/carts/complete.rbindex f606776d18..2edfb9b83c 100644--- a/spree/core/app/workflows/spree/carts/complete.rb+++ b/spree/core/app/workflows/spree/carts/complete.rb@@ -16,7 +16,7 @@ module Spree# cart.completed_at + UpdateStatuses;# events after commitclass Complete < Spree::Workflow- COMPLETING_TTL = 5.minutes+ COMPLETING_TTL = Spree::Cart::COMPLETING_CLAIM_TTLhooks :validate, :before_finalize, :after_finalize@@ -90,7 +90,7 @@ module Spreeenddef guard_concurrent_completion- failure(cart, code: 'completion_in_progress') if cart.completing? && cart.completing_at > COMPLETING_TTL.ago+ failure(cart, code: 'completion_in_progress') if cart.completion_claimed?end# In-lock recalculation — the totals about to be charged are computeddiff --git a/spree/core/app/workflows/spree/claims/resolve.rb b/spree/core/app/workflows/spree/claims/resolve.rbindex e7f1c2ca3c..1d39343ef9 100644--- a/spree/core/app/workflows/spree/claims/resolve.rb+++ b/spree/core/app/workflows/spree/claims/resolve.rb@@ -133,34 +133,29 @@ module Spreedef refund_at_gatewayremaining = @amount_to_refund- refund = nil-claim.order.payments.completed.each do |payment|break unless remaining.positive?creditable = [payment.credit_allowed.to_d, remaining].minnext unless creditable.positive?- # Serialized on the payment row — the balance validation must see any- # concurrently created refund rows (credit_allowed sums them).- refund = payment.with_lock do- payment.refunds.create!(- amount: creditable,- reason: Spree::RefundReason.return_processing_reason(claim.store),- refunder: resolver,- originator: claim- )- end- refund.perform!- @refunds << refund+ # One refund path for the whole system: Refunds::Create owns the+ # row-lock balance check, the gateway credit, the declined-row+ # compensation, the refund hooks and the payment.refunded event.+ result = Spree.refund_create_workflow.call(+ payment: payment,+ amount: creditable,+ reason: Spree::RefundReason.return_processing_reason(claim.store),+ refunder: resolver,+ originator: claim+ )+ failure(claim, result.error.value) if result.failure?++ @refunds << result.valueremaining -= creditableendfailure(claim, :no_refundable_payments) if @refunds.empty?- rescue Spree::Core::GatewayError => error- # An uncredited row would eat into credit_allowed and block the retry.- refund.destroy! if refund&.transaction_id.blank?- failure(claim, error.message)enddef mark_resolveddiff --git a/spree/core/app/workflows/spree/exchanges/fulfill.rb b/spree/core/app/workflows/spree/exchanges/fulfill.rbindex 5f475fdf87..6c59263fe9 100644--- a/spree/core/app/workflows/spree/exchanges/fulfill.rb+++ b/spree/core/app/workflows/spree/exchanges/fulfill.rb@@ -112,32 +112,27 @@ module Spreedef refund_at_gatewayremaining = credit_amount- refund = nil-exchange.order.payments.completed.each do |payment|break unless remaining.positive?creditable = [payment.credit_allowed.to_d, remaining].minnext unless creditable.positive?- # Serialized on the payment row — the balance validation must see any- # concurrently created refund rows (credit_allowed sums them).- refund = payment.with_lock do- payment.refunds.create!(- amount: creditable,- reason: Spree::RefundReason.return_processing_reason(exchange.store),- refunder: refunder,- originator: exchange- )- end- refund.perform!- @refunds << refund+ # One refund path for the whole system: Refunds::Create owns the+ # row-lock balance check, the gateway credit, the declined-row+ # compensation, the refund hooks and the payment.refunded event.+ result = Spree.refund_create_workflow.call(+ payment: payment,+ amount: creditable,+ reason: Spree::RefundReason.return_processing_reason(exchange.store),+ refunder: refunder,+ originator: exchange+ )+ failure(exchange, result.error.value) if result.failure?++ @refunds << result.valueremaining -= creditableend- rescue Spree::Core::GatewayError => error- # An uncredited row would eat into credit_allowed and block the retry.- refund.destroy! if refund&.transaction_id.blank?- failure(exchange, error.message)enddef mark_fulfilleddiff --git a/spree/core/app/workflows/spree/payments/handle_webhook.rb b/spree/core/app/workflows/spree/payments/handle_webhook.rbindex 8cd7157d85..a34b4adb0c 100644--- a/spree/core/app/workflows/spree/payments/handle_webhook.rb+++ b/spree/core/app/workflows/spree/payments/handle_webhook.rb@@ -44,6 +44,10 @@ module Spree# and the redelivery races the checkout request that created the# session.def settle_session+ # Provider round trips happen here, before the lock — settlement+ # inside it must be pure database work.+ payment_session.prepare_for_settlement!+order.with_lock do# Idempotency: the API endpoint or an earlier delivery may have# already settled this session. Not halt! — that is forbiddendiff --git a/spree/core/app/workflows/spree/returns/refund.rb b/spree/core/app/workflows/spree/returns/refund.rbindex 8d6b58e8a4..55af66b57b 100644--- a/spree/core/app/workflows/spree/returns/refund.rb+++ b/spree/core/app/workflows/spree/returns/refund.rb@@ -118,34 +118,29 @@ module Spree# more than one refund.def refund_at_gatewayremaining = @amount_to_refund- refund = nil-return_record.order.payments.completed.each do |payment|break unless remaining.positive?creditable = [payment.credit_allowed.to_d, remaining].minnext unless creditable.positive?- # Serialized on the payment row — the balance validation must see any- # concurrently created refund rows (credit_allowed sums them).- refund = payment.with_lock do- payment.refunds.create!(- amount: creditable,- reason: Spree::RefundReason.return_processing_reason(return_record.store),- refunder: refunder,- originator: return_record- )- end- refund.perform!- @refunds << refund+ # One refund path for the whole system: Refunds::Create owns the+ # row-lock balance check, the gateway credit, the declined-row+ # compensation, the refund hooks and the payment.refunded event.+ result = Spree.refund_create_workflow.call(+ payment: payment,+ amount: creditable,+ reason: Spree::RefundReason.return_processing_reason(return_record.store),+ refunder: refunder,+ originator: return_record+ )+ failure(return_record, result.error.value) if result.failure?++ @refunds << result.valueremaining -= creditableendfailure(return_record, :no_refundable_payments) if @refunds.empty?- rescue Spree::Core::GatewayError => error- # An uncredited row would eat into credit_allowed and block the retry.- refund.destroy! if refund&.transaction_id.blank?- failure(return_record, error.message)enddef mark_refundeddiff --git a/spree/core/spec/workflows/spree/payments/handle_webhook_spec.rb b/spree/core/spec/workflows/spree/payments/handle_webhook_spec.rbindex d7750ae416..2c57efec1b 100644--- a/spree/core/spec/workflows/spree/payments/handle_webhook_spec.rb+++ b/spree/core/spec/workflows/spree/payments/handle_webhook_spec.rb@@ -14,6 +14,12 @@ RSpec.describe Spree::Payments::HandleWebhook dodescribe '#call' docontext 'with :captured action' do+ it 'fetches provider data before taking the order lock' do+ expect(payment_session).to receive(:prepare_for_settlement!).and_call_original++ subject.call(payment_method: payment_method, action: :captured, payment_session: payment_session)+ end+it 'creates a payment record' doexpect {subject.call(payment_method: payment_method, action: :captured, payment_session: payment_session)diff --git a/spree/providers/stripe/app/models/spree/payment_sessions/stripe.rb b/spree/providers/stripe/app/models/spree/payment_sessions/stripe.rbindex d08b9f0aae..acddfc61f9 100644--- a/spree/providers/stripe/app/models/spree/payment_sessions/stripe.rb+++ b/spree/providers/stripe/app/models/spree/payment_sessions/stripe.rb@@ -37,6 +37,15 @@ module Spreepayment_method.payment_intent_charge_not_required?(stripe_payment_intent)end+ # Warms everything settlement reads from Stripe — the intent, its charge,+ # and the gateway customer a card source needs — so the webhook path's+ # locked settlement does no Stripe I/O.+ def prepare_for_settlement!+ stripe_charge+ payment_method.fetch_or_create_customer(order: owner) if owner&.customer+ self+ end+# Builds the payment together with a Stripe-specific source (card, Klarna,# SEPA, …), which core's generic implementation cannot do.def find_or_create_payment!(metadata = {})diff --git a/spree/providers/stripe/app/models/spree_stripe/gateway.rb b/spree/providers/stripe/app/models/spree_stripe/gateway.rbindex 4b041e309b..2e7f32232c 100644--- a/spree/providers/stripe/app/models/spree_stripe/gateway.rb+++ b/spree/providers/stripe/app/models/spree_stripe/gateway.rb@@ -102,26 +102,21 @@ module SpreeStripereturn success(payment_intent_id, {}) if amount.zero?return success(payment_intent_id, {}) if payment.respond_to?(:for_shipment?) && payment.for_shipment?- # Serialized on the payment row — the balance validation must see any- # concurrently created refund rows (credit_allowed sums them).- refund = payment.with_lock do- payment.refunds.create!(- amount: payment.credit_allowed,- reason: Spree::RefundReason.order_canceled_reason,- refunder_id: payment.order.canceler_id- )- end-- begin- refund.perform!- rescue Spree::Core::GatewayError- refund.destroy! if refund.transaction_id.blank?- raise- end+ # One refund path for the whole system — Refunds::Create owns the+ # balance check, the credit, the compensation and the hooks. Store+ # passed explicitly: cancellation runs from jobs and webhooks where+ # Spree::Current.store is nil, and the bare reason lookup would mint+ # a storeless row.+ result = Spree.refund_create_workflow.call(+ payment: payment,+ reason: Spree::RefundReason.order_canceled_reason(payment.owner.store),+ refunder: payment.order.canceler+ )+ raise Spree::Core::GatewayError, result.error.value.to_s if result.failure?# Spree::Refund#response holds the `credit` response. The authorization# must stay the payment intent id, or the refund id would overwrite it.- success(payment.response_code, refund.response.params)+ success(payment.response_code, result.value.response.params)elseresponse = cancel_payment_intent(payment_intent_id)success(response.id, response)diff --git a/spree/providers/stripe/app/models/spree_stripe/gateway/webhooks.rb b/spree/providers/stripe/app/models/spree_stripe/gateway/webhooks.rbindex 47c1de90a9..0bfda7e894 100644--- a/spree/providers/stripe/app/models/spree_stripe/gateway/webhooks.rb+++ b/spree/providers/stripe/app/models/spree_stripe/gateway/webhooks.rb@@ -10,11 +10,15 @@ module SpreeStripemodule Webhooksextend ActiveSupport::Concern+ # Only events with a handler — subscribing to more would silently drop+ # deliveries and bake phantom events into the endpoint's identity.+ # setup_intent.succeeded is deliberately absent: healing an abandoned+ # setup session by webhook needs core's webhook contract to learn about+ # setup sessions first (it only routes payment sessions today).SUPPORTED_EVENTS = %w[payment_intent.amount_capturable_updatedpayment_intent.payment_failedpayment_intent.succeeded- setup_intent.succeeded].freezeWEBHOOK_EVENT_ACTIONS = {diff --git a/spree/providers/stripe/app/presenters/spree_stripe/customer_presenter.rb b/spree/providers/stripe/app/presenters/spree_stripe/customer_presenter.rbindex a0879d76db..2032ca0ec1 100644--- a/spree/providers/stripe/app/presenters/spree_stripe/customer_presenter.rb+++ b/spree/providers/stripe/app/presenters/spree_stripe/customer_presenter.rb@@ -19,14 +19,17 @@ module SpreeStripeattr_reader :email, :name, :address+ # ISO codes, matching the intent's shipping payload — Stripe expects+ # ISO 3166-1 alpha-2 for country, and full names degrade Stripe-side+ # location resolution (tax, risk rules).def address_payload{city: address.city,line1: address.address1,line2: address.address2,postal_code: address.zipcode,- country: address.country_name,- state: address.state_name_text+ country: address.country_iso,+ state: address.state_abbr.presence || address.state_name_text}endenddiff --git a/spree/providers/stripe/spec/models/spree/payment_sessions/stripe_spec.rb b/spree/providers/stripe/spec/models/spree/payment_sessions/stripe_spec.rbindex b433623b18..edaad09f21 100644--- a/spree/providers/stripe/spec/models/spree/payment_sessions/stripe_spec.rb+++ b/spree/providers/stripe/spec/models/spree/payment_sessions/stripe_spec.rb@@ -82,6 +82,24 @@ RSpec.describe Spree::PaymentSessions::Stripe, type: :model doendend+ describe '#prepare_for_settlement!' do+ let(:stripe_payment_intent) do+ Stripe::StripeObject.construct_from(id: 'pi_123', status: 'succeeded', latest_charge: 'ch_123')+ end+ let(:stripe_charge) { Stripe::StripeObject.construct_from(id: 'ch_123') }++ it 'warms the intent, the charge and the gateway customer before settlement' do+ expect(gateway).to receive(:retrieve_payment_intent).once.and_return(stripe_payment_intent)+ expect(gateway).to receive(:retrieve_charge).once.and_return(stripe_charge)+ expect(gateway).to receive(:fetch_or_create_customer).once++ payment_session.prepare_for_settlement!++ # Memoized — settlement reads hit no network.+ expect(payment_session.stripe_charge).to eq(stripe_charge)+ end+ end+describe '#stripe_charge' dolet(:stripe_pi) { Stripe::StripeObject.construct_from(id: 'pi_test_abc123', status: 'succeeded', latest_charge: 'ch_123') }let(:stripe_charge) { Stripe::StripeObject.construct_from(id: 'ch_123') }diff --git a/spree/providers/stripe/spec/vcr/create_another_gateway_webhooks.yml b/spree/providers/stripe/spec/vcr/create_another_gateway_webhooks.ymlindex 134fca3738..9b883baf08 100644--- a/spree/providers/stripe/spec/vcr/create_another_gateway_webhooks.yml+++ b/spree/providers/stripe/spec/vcr/create_another_gateway_webhooks.yml@@ -89,8 +89,7 @@ http_interactions:"enabled_events": ["payment_intent.amount_capturable_updated","payment_intent.payment_failed",- "payment_intent.succeeded",- "setup_intent.succeeded"+ "payment_intent.succeeded"],"livemode": false,"metadata": {},@@ -106,8 +105,7 @@ http_interactions:"description": null,"enabled_events": ["payment_intent.payment_failed",- "payment_intent.succeeded",- "setup_intent.succeeded"+ "payment_intent.succeeded"],"livemode": false,"metadata": {},@@ -123,8 +121,7 @@ http_interactions:"description": null,"enabled_events": ["payment_intent.payment_failed",- "payment_intent.succeeded",- "setup_intent.succeeded"+ "payment_intent.succeeded"],"livemode": false,"metadata": {},@@ -280,8 +277,7 @@ http_interactions:"enabled_events": ["payment_intent.amount_capturable_updated","payment_intent.payment_failed",- "payment_intent.succeeded",- "setup_intent.succeeded"+ "payment_intent.succeeded"],"livemode": false,"metadata": {},@@ -379,8 +375,7 @@ http_interactions:"enabled_events": ["payment_intent.amount_capturable_updated","payment_intent.payment_failed",- "payment_intent.succeeded",- "setup_intent.succeeded"+ "payment_intent.succeeded"],"livemode": false,"metadata": {},@@ -397,8 +392,7 @@ http_interactions:"enabled_events": ["payment_intent.amount_capturable_updated","payment_intent.payment_failed",- "payment_intent.succeeded",- "setup_intent.succeeded"+ "payment_intent.succeeded"],"livemode": false,"metadata": {},@@ -414,8 +408,7 @@ http_interactions:"description": null,"enabled_events": ["payment_intent.payment_failed",- "payment_intent.succeeded",- "setup_intent.succeeded"+ "payment_intent.succeeded"],"livemode": false,"metadata": {},@@ -431,8 +424,7 @@ http_interactions:"description": null,"enabled_events": ["payment_intent.payment_failed",- "payment_intent.succeeded",- "setup_intent.succeeded"+ "payment_intent.succeeded"],"livemode": false,"metadata": {},diff --git a/spree/providers/stripe/spec/vcr/create_gateway_webhooks.yml b/spree/providers/stripe/spec/vcr/create_gateway_webhooks.ymlindex 45aa8782a0..6bb63a5182 100644--- a/spree/providers/stripe/spec/vcr/create_gateway_webhooks.yml+++ b/spree/providers/stripe/spec/vcr/create_gateway_webhooks.yml@@ -86,8 +86,7 @@ http_interactions:"description": null,"enabled_events": ["payment_intent.payment_failed",- "payment_intent.succeeded",- "setup_intent.succeeded"+ "payment_intent.succeeded"],"livemode": false,"metadata": {},@@ -103,8 +102,7 @@ http_interactions:"description": null,"enabled_events": ["payment_intent.payment_failed",- "payment_intent.succeeded",- "setup_intent.succeeded"+ "payment_intent.succeeded"],"livemode": false,"metadata": {},@@ -260,8 +258,7 @@ http_interactions:"enabled_events": ["payment_intent.amount_capturable_updated","payment_intent.payment_failed",- "payment_intent.succeeded",- "setup_intent.succeeded"+ "payment_intent.succeeded"],"livemode": false,"metadata": {},@@ -359,8 +356,7 @@ http_interactions:"enabled_events": ["payment_intent.amount_capturable_updated","payment_intent.payment_failed",- "payment_intent.succeeded",- "setup_intent.succeeded"+ "payment_intent.succeeded"],"livemode": false,"metadata": {},@@ -376,8 +372,7 @@ http_interactions:"description": null,"enabled_events": ["payment_intent.payment_failed",- "payment_intent.succeeded",- "setup_intent.succeeded"+ "payment_intent.succeeded"],"livemode": false,"metadata": {},@@ -393,8 +388,7 @@ http_interactions:"description": null,"enabled_events": ["payment_intent.payment_failed",- "payment_intent.succeeded",- "setup_intent.succeeded"+ "payment_intent.succeeded"],"livemode": false,"metadata": {},diff --git a/spree/providers/stripe/spec/vcr/existing_gateway_webhooks.yml b/spree/providers/stripe/spec/vcr/existing_gateway_webhooks.ymlindex a726ecd3dc..3779e4e676 100644--- a/spree/providers/stripe/spec/vcr/existing_gateway_webhooks.yml+++ b/spree/providers/stripe/spec/vcr/existing_gateway_webhooks.yml@@ -89,8 +89,7 @@ http_interactions:"enabled_events": ["payment_intent.amount_capturable_updated","payment_intent.payment_failed",- "payment_intent.succeeded",- "setup_intent.succeeded"+ "payment_intent.succeeded"],"livemode": false,"metadata": {},@@ -106,8 +105,7 @@ http_interactions:"description": null,"enabled_events": ["payment_intent.payment_failed",- "payment_intent.succeeded",- "setup_intent.succeeded"+ "payment_intent.succeeded"],"livemode": false,"metadata": {},@@ -123,8 +121,7 @@ http_interactions:"description": null,"enabled_events": ["payment_intent.payment_failed",- "payment_intent.succeeded",- "setup_intent.succeeded"+ "payment_intent.succeeded"],"livemode": false,"metadata": {},@@ -273,8 +270,7 @@ http_interactions:"enabled_events": ["payment_intent.amount_capturable_updated","payment_intent.payment_failed",- "payment_intent.succeeded",- "setup_intent.succeeded"+ "payment_intent.succeeded"],"livemode": false,"metadata": {},@@ -290,8 +286,7 @@ http_interactions:"description": null,"enabled_events": ["payment_intent.payment_failed",- "payment_intent.succeeded",- "setup_intent.succeeded"+ "payment_intent.succeeded"],"livemode": false,"metadata": {},@@ -307,8 +302,7 @@ http_interactions:"description": null,"enabled_events": ["payment_intent.payment_failed",- "payment_intent.succeeded",- "setup_intent.succeeded"+ "payment_intent.succeeded"],"livemode": false,"metadata": {},