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
Route the payment lifecycle through its workflows
Damian Legawiecd30512b65753
diff --git a/docs/plans/6.0-service-workflows.md b/docs/plans/6.0-service-workflows.mdindex c6dea5c8f2..c18d54bf9b 100644--- a/docs/plans/6.0-service-workflows.md+++ b/docs/plans/6.0-service-workflows.md@@ -480,8 +480,27 @@ admin draft-order edits without touching storefront carts.| Workflow | Seam | Hooks | ||---|---|---|---|| `Payments::Capture` | `payment_capture_workflow` | `validate` (V), `before_capture` (L), `after_capture` (L) | ✅ |-| `Payments::Refund` | `payment_refund_workflow` | `validate` (V), `before_refund` (L), `after_refund` (L) | ✅ |+| `Payments::Void` | `payment_void_workflow` | `validate` (V), `before_void` (L), `after_void` (L) | ✅ |+| `Refunds::Create` | `refund_create_workflow` | `validate` (V), `before_refund` (L), `after_refund` (L) | ✅ || `Payments::HandleWebhook` | `payments_handle_webhook_workflow` | `after_handle` (L) | ✅ |+| `PaymentSessions::Complete` | `payment_session_complete_workflow` | `validate` (V), `after_complete` (L) | ✅ |++The admin capture, void and refund endpoints and the storefront session+confirm endpoint route through these workflows — none of them wraps the call+in `with_order_lock`, because the workflows call the gateway from an+`external_step` and every flow is an idempotent success on replay.+`Refunds::Create` (renamed from `Payments::Refund` before any release of the+key) owns the whole refund lifecycle: `Refund#after_create :perform!` is gone,+the row commits first, the gateway credit is an explicit `external_step`, and+a cleanly declined credit destroys the uncredited row (credit_allowed sums+every row, so a dangling one would block the retry). The returns, exchange and+claim workflows call `Refund#perform!` explicitly from their own external+steps. Two callback exorcisms rode along: `Payment after_save+:create_payment_profile` became an explicit call owned by creation flows (the+card number never persists, so only the creating flow's in-memory instance+can store a profile — which is also why no subscriber can do this), and+`process_payments!` no longer holds the order row lock across gateway round+trips.### Returns@@ -590,11 +609,11 @@ Not new workflows — things wrong or missing in what already shipped.sidebar count, a menu firing without a dialog, a disabled button with noexplanation). A Playwright walk through open → approve → resolve assertingmenu contents at each step would cover most of them.-- ⬜ **Wave B leftovers.** `Payments::Capture` and `Refund` own the transaction- boundary and guards, but the money movement still lives in the model- (`Payment#capture!`, `Refund#perform!` in an `after_create`). Moving it into- the workflows is a larger change than the boundary fix and has not been- scheduled.+- ✅ **Wave B leftovers — resolved 2026-08-12.** The admin endpoints route+ through `Payments::Capture`/`Void` and `Refunds::Create`; the refund credit+ left its `after_create` for an explicit `external_step`. Money movement+ deliberately stays in the model (`Payment#capture!`, `Refund#perform!`) —+ the workflows own boundary, guards and hooks, per the doctrine.- ⬜ **`get_provider_data` has no consumer.** Declared on`Fulfillments::Create`, but no fulfillment provider reads the merged hashyet. It is a published contract with no proof it fits the providers' needs.diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 968e823e08..d63997bf83 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -330,6 +330,53 @@ 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 — The payment lifecycle routes through its workflows; refund creation owns the credit++An audit found the two payment workflows were dead code: `Payments::Capture`+and `Payments::Refund` existed with hooks, but the admin API called+`payment.capture!` and `Refund.create` directly — inside `with_order_lock`, a+row lock held across gateway round trips — and `Refund#after_create :perform!`+fired the gateway credit from a save callback, the exact shape the workflow+doctrine prohibits. The boundary the plan says workflows own was owned by+controllers.++Five changes close the gap:++- **`Refunds::Create`** (renamed from `Payments::Refund`, key+ `refund_create_workflow`, before any release of the old key) owns refund+ creation end to end. The `after_create` is gone: the row commits, then the+ credit runs as an explicit `external_step` via a now-public+ `Refund#perform!` (idempotent — a present transaction_id is a no-op). A+ cleanly declined credit destroys the uncredited row, because+ `credit_allowed` sums every refund row and a dangling one would block the+ retry; a crash between commit and credit leaves the row for reconciliation.+ Returns, exchanges, claims and Stripe's cancel verb call `perform!`+ explicitly from their own external steps.+- **`Payments::Void`** exists (mirror of Capture) and the admin void endpoint+ routes through it; capture routes through `Payments::Capture`. Neither+ wraps in `with_order_lock` — replays are idempotent successes.+- **`PaymentSessions::Complete`** is the synchronous twin of `HandleWebhook`:+ same settlement through `settle_payment!`, plus the one veto point the sync+ path lacked (`validate` before money is recorded — the webhook path+ deliberately has none, money that moved cannot be rejected).+- **`create_payment_profile` left its save callback and became an explicit+ call.** No subscriber replaced it — a first attempt proved why: the card+ number never persists, so profile creation only works on the in-memory+ instance the creation flow holds, and an observer that reloads the payment+ can never do it. Creation flows that take raw card data call+ `payment.create_payment_profile` after the commit; session gateways store+ profile ids during source creation and never call it. Row save alone no+ longer talks to a gateway.+- **`process_payments!` dropped its `with_lock`** around the gateway loop;+ re-entry is guarded by `started_processing!` and the per-payment gateway+ idempotency key.++**Consequences:** hook keys `refunds.create.*`, `payments.void.*` and+`payment_sessions.complete.*` are public API from 6.0. Controllers never wrap+gateway-calling workflows in `with_order_lock`. Anything creating a+`Spree::Refund` row must either call `Refund#perform!` from an external step+or accept an uncredited row — creation alone no longer moves money.+## 2026-08-12 — Providers never decorate core models; risk codes become a gateway interfaceThe Stripe provider shipped with three decorators on core models, and all threediff --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 a4e29e6c76..9c3b38902d 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@@ -36,23 +36,32 @@ module Spreeend# PATCH /api/v3/admin/orders/:order_id/payments/:id/capture+ #+ # Capture and void deliberately skip with_order_lock: the workflows+ # call the gateway from an external_step, and holding a row lock+ # across a network round trip is exactly what that boundary exists+ # to prevent. Both flows are idempotent on replay — an+ # already-captured or already-void payment returns success.def capture- with_order_lock do- amount = params[:amount] ? (params[:amount].to_f * 100).round : nil- @resource.capture!(amount)- render json: serialize_resource(@resource.reload)- rescue Spree::Core::GatewayError => e- render_service_error(e.message)+ amount = params[:amount] ? (params[:amount].to_f * 100).round : nil++ result = Spree.payment_capture_workflow.call(payment: @resource, amount: amount)++ if result.success?+ render json: serialize_resource(result.value)+ else+ render_result_error(result)endend# PATCH /api/v3/admin/orders/:order_id/payments/:id/voiddef void- with_order_lock do- @resource.void_transaction!- render json: serialize_resource(@resource.reload)- rescue Spree::Core::GatewayError => e- render_service_error(e.message)+ result = Spree.payment_void_workflow.call(payment: @resource)++ if result.success?+ render json: serialize_resource(result.value)+ else+ render_result_error(result)endenddiff --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 8ffd991e6e..daf6691a67 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@@ -7,24 +7,30 @@ module Spreescoped_resource :refunds# POST /api/v3/admin/orders/:order_id/refunds+ #+ # Deliberately not wrapped in with_order_lock: the workflow calls+ # the gateway from an external_step, and holding a row lock across+ # a network round trip is exactly what that boundary exists to+ # prevent. Refund#perform! is a no-op on a credited refund, so a+ # double submit cannot credit twice.def create- with_order_lock do- payment = @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-- @resource = payment.refunds.build(- amount: params[:amount],- reason: reason,- transaction_id: nil- )- authorize_resource!(@resource, :create)-- if @resource.save- render json: serialize_resource(@resource), status: :created- else- render_validation_error(@resource.errors)- end+ payment = @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++ authorize_resource!(payment.refunds.build(amount: params[:amount], reason: reason), :create)++ result = Spree.refund_create_workflow.call(+ payment: payment,+ amount: params[:amount],+ reason: reason,+ refunder: try_spree_current_user+ )++ if result.success?+ render json: serialize_resource(result.value), status: :created+ else+ render_result_error(result)endenddiff --git a/spree/api/app/controllers/spree/api/v3/store/carts/payment_sessions_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts/payment_sessions_controller.rbindex c4e2a86b85..9cda3cde65 100644--- a/spree/api/app/controllers/spree/api/v3/store/carts/payment_sessions_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/carts/payment_sessions_controller.rb@@ -54,25 +54,25 @@ module Spreeend# PATCH /api/v3/store/carts/:cart_id/payment_sessions/:id/complete+ #+ # Deliberately not wrapped in with_order_lock: the workflow verifies+ # the session with the gateway from an external_step, and holding a+ # row lock across that round trip is what the boundary exists to+ # prevent. The race against the webhook is settled inside — both+ # paths go through PaymentSession#settle_payment!, and a replay on+ # a completed session is an idempotent success.def complete- with_order_lock do- @payment_session.reload-- if @payment_session.completed?- render json: serialize_resource(@payment_session)- return- end-- @payment_session.payment_method.complete_payment_session(- payment_session: @payment_session,- params: complete_params- )-- if @payment_session.errors.empty?- render json: serialize_resource(@payment_session.reload)- else- render_errors(@payment_session.errors)- end+ result = Spree.payment_session_complete_workflow.call(+ payment_session: @payment_session.reload,+ params: complete_params+ )++ if result.success? && @payment_session.errors.empty?+ render json: serialize_resource(result.value)+ elsif result.success?+ render_errors(@payment_session.errors)+ else+ render_result_error(result)endenddiff --git a/spree/core/app/models/concerns/spree/purchase/payment_processing.rb b/spree/core/app/models/concerns/spree/purchase/payment_processing.rbindex 1c3f220c29..7c585a8aa1 100644--- a/spree/core/app/models/concerns/spree/purchase/payment_processing.rb+++ b/spree/core/app/models/concerns/spree/purchase/payment_processing.rb@@ -5,8 +5,18 @@ module Spree# Processes any pending payments, recording a gateway failure on# +errors+. The completion workflows check whether payments actually# cover the total rather than trusting the return value.+ #+ # Deliberately not locked: holding the order's row lock across gateway+ # round trips is what the workflow external_step boundary exists to+ # prevent. Concurrent processing of the same payment is guarded twice —+ # started_processing! refuses re-entry, and the gateway idempotency key+ # (spree-<payment.number>) makes a duplicate charge a no-op at the+ # provider.def process_payments!- with_lock { process_payments_with(:process!) }+ # with_lock used to reload the record as a side effect; callers create+ # payments right before processing, so the association must refresh.+ payments.reset+ process_payments_with(:process!)enddef authorize_payments!diff --git a/spree/core/app/models/spree/payment.rb b/spree/core/app/models/spree/payment.rbindex dce77e284b..f0cc632ef4 100644--- a/spree/core/app/models/spree/payment.rb+++ b/spree/core/app/models/spree/payment.rb@@ -52,7 +52,6 @@ module Spree## Callbacksbefore_create :assign_risk_codes_from_source- after_save :create_payment_profile, if: :profiles_supported?# update the order totals, etc.after_save :update_order, unless: -> { capture_on_dispatch }# invalidate previously entered payments@@ -297,6 +296,29 @@ module Spreeendend+ def profiles_supported?+ payment_method.respond_to?(:payment_profiles_supported?) && payment_method.payment_profiles_supported?+ end++ # Stores the payment source at the gateway for later off-session use.+ # Gateway I/O — creation flows that take raw card data call this+ # explicitly after the payment commits, on the same in-memory instance+ # (the card number never persists, and some gateways need it). Session+ # gateways store profile ids during source creation and never call this.+ def create_payment_profile+ # Don't attempt to create on bad payments.+ return if has_invalid_state?+ # Payment profile cannot be created without source+ return unless source+ # Imported payments shouldn't create a payment profile.+ # Imported is only available on Spree::CreditCard, non-credit card payments should not have this attribute.+ return if source.respond_to?(:imported) && source.imported++ payment_method.create_profile(self)+ rescue Spree::PaymentConnectionError => e+ gateway_error e+ end+private# Session-created payments never pass through the gateway response path@@ -362,23 +384,7 @@ module Spreeerrors.add(Spree.t(source.class.to_s.demodulize.underscore), "#{field_name} #{message}")end- def profiles_supported?- payment_method.respond_to?(:payment_profiles_supported?) && payment_method.payment_profiles_supported?- end- def create_payment_profile- # Don't attempt to create on bad payments.- return if has_invalid_state?- # Payment profile cannot be created without source- return unless source- # Imported payments shouldn't create a payment profile.- # Imported is only available on Spree::CreditCard, non-credit card payments should not have this attribute.- return if source.respond_to?(:imported) && source.imported-- payment_method.create_profile(self)- rescue Spree::PaymentConnectionError => e- gateway_error e- enddef split_uncaptured_amountif uncaptured_amount > 0diff --git a/spree/core/app/models/spree/refund.rb b/spree/core/app/models/spree/refund.rbindex 83bc3378fe..d237d20ce3 100644--- a/spree/core/app/models/spree/refund.rb+++ b/spree/core/app/models/spree/refund.rb@@ -21,14 +21,12 @@ module Spreewith_options presence: true dovalidates :payment, :reason- # can't require this on create because the perform! in after_create needs to run first+ # not required on create — perform! sets it after the gateway creditvalidates :transaction_id, on: :updatevalidates :amount, numericality: { greater_than: 0, allow_nil: true }endvalidate :amount_is_less_than_or_equal_to_allowed_amount, on: :create, if: :amount- after_create :perform!-attr_reader :responsedelegate :order, :currency, to: :payment@@ -62,10 +60,13 @@ module Spree!payment.order.canceled?end- private-- # attempts to perform the refund.- # raises an error if the refund fails.+ # Credits the refund back at the gateway — the money movement, called+ # explicitly from a workflow's external_step, never from a callback. A+ # blank transaction_id means the credit has not happened yet; a present+ # one makes this a no-op, so replays are safe.+ #+ # @raise [Spree::Core::GatewayError] when the gateway declines or is down+ # @return [true]def perform!return true if transaction_id.present?@@ -76,8 +77,11 @@ module Spreeself.transaction_id = @response.authorizationupdate_columns(transaction_id: transaction_id)update_order+ trueend+ private+# return a payment response object if successful or else raise an errordef process!(credit_cents)refund_total_in_cents = calculate_refund_amount(credit_cents)diff --git a/spree/core/app/workflows/spree/claims/resolve.rb b/spree/core/app/workflows/spree/claims/resolve.rbindex fd28f09cf2..8ba5d07e37 100644--- a/spree/core/app/workflows/spree/claims/resolve.rb+++ b/spree/core/app/workflows/spree/claims/resolve.rb@@ -133,6 +133,7 @@ module Spreedef refund_at_gatewayremaining = @amount_to_refund+ refund = nilclaim.order.payments.completed.each do |payment|break unless remaining.positive?@@ -140,17 +141,21 @@ module Spreecreditable = [payment.credit_allowed.to_d, remaining].minnext unless creditable.positive?- @refunds << payment.refunds.create!(+ refund = payment.refunds.create!(amount: creditable,reason: Spree::RefundReason.return_processing_reason(claim.store),refunder: resolver,originator: claim)+ refund.perform!+ @refunds << refundremaining -= 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)enddiff --git a/spree/core/app/workflows/spree/exchanges/fulfill.rb b/spree/core/app/workflows/spree/exchanges/fulfill.rbindex 043ed479f0..d162dac719 100644--- a/spree/core/app/workflows/spree/exchanges/fulfill.rb+++ b/spree/core/app/workflows/spree/exchanges/fulfill.rb@@ -112,6 +112,7 @@ module Spreedef refund_at_gatewayremaining = credit_amount+ refund = nilexchange.order.payments.completed.each do |payment|break unless remaining.positive?@@ -119,15 +120,19 @@ module Spreecreditable = [payment.credit_allowed.to_d, remaining].minnext unless creditable.positive?- @refunds << payment.refunds.create!(+ refund = payment.refunds.create!(amount: creditable,reason: Spree::RefundReason.return_processing_reason(exchange.store),refunder: refunder,originator: exchange)+ refund.perform!+ @refunds << refundremaining -= creditableendrescue 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)enddiff --git a/spree/core/app/workflows/spree/payment_sessions/complete.rb b/spree/core/app/workflows/spree/payment_sessions/complete.rbnew file mode 100644index 0000000000..6e1445f5ab--- /dev/null+++ b/spree/core/app/workflows/spree/payment_sessions/complete.rb@@ -0,0 +1,44 @@+module Spree+ module PaymentSessions+ # Completes a payment session when the customer returns from the gateway —+ # the synchronous twin of Spree::Payments::HandleWebhook, which settles the+ # same session when the gateway reports out of band. Either can arrive+ # first; both settle through PaymentSession#settle_payment!.+ #+ # In the workflow tier because completion is network I/O (the gateway+ # verifies the session before settling), and because this is the one+ # moment a host can veto settlement on the synchronous path — the webhook+ # path deliberately has no veto, since money that already moved cannot be+ # rejected.+ class Complete < Spree::Workflow+ hooks :validate, :after_complete++ # @param payment_session [Spree::PaymentSession]+ # @param params [Hash] gateway-specific completion params from the client+ def perform(payment_session:, params: {})+ super++ # A replayed confirm on a settled session is idempotent, not an error.+ halt!(payment_session) if payment_session.completed?++ run_hooks :validate++ external_step :complete_at_gateway++ run_hooks :after_complete+ success(payment_session.reload)+ end++ private++ def complete_at_gateway+ payment_session.payment_method.complete_payment_session(+ payment_session: payment_session,+ params: params+ )+ rescue Spree::Core::GatewayError => error+ failure(payment_session, error.message)+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/payments/void.rb b/spree/core/app/workflows/spree/payments/void.rbnew file mode 100644index 0000000000..5db50ef17e--- /dev/null+++ b/spree/core/app/workflows/spree/payments/void.rb@@ -0,0 +1,46 @@+module Spree+ module Payments+ # Voids an authorized payment at the gateway.+ #+ # In the workflow tier because the void is network I/O — the external_step+ # keeps it out of any transaction the workflow opened. Money movement+ # stays in the model (Payment#void_transaction! and the state machine are+ # unchanged); this owns the boundary, the guards and the extension points+ # around it.+ class Void < Spree::Workflow+ hooks :validate, :before_void, :after_void++ # @param payment [Spree::Payment] an already-void payment is a no-op+ def perform(payment:)+ super++ step :ensure_voidable+ # Veto point — before the authorization is released.+ run_hooks :validate+ run_hooks :before_void++ external_step :void_at_gateway++ run_hooks :after_void+ success(payment.reload)+ end++ private++ # An already-void payment returns success rather than failing: void is+ # naturally idempotent and double-submitted admin actions must not+ # surface as errors.+ def ensure_voidable+ halt!(payment) if payment.void?+ failure(payment, :payment_not_voidable) unless payment.can_void?+ end++ # The payment.voided event publishes from the state transition itself.+ def void_at_gateway+ payment.void_transaction!+ rescue Spree::Core::GatewayError => error+ failure(payment, error.message)+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/payments/refund.rb b/spree/core/app/workflows/spree/refunds/create.rbsimilarity index 54%rename from spree/core/app/workflows/spree/payments/refund.rbrename to spree/core/app/workflows/spree/refunds/create.rbindex ce34ff2b4e..22853c5ec8 100644--- a/spree/core/app/workflows/spree/payments/refund.rb+++ b/spree/core/app/workflows/spree/refunds/create.rb@@ -1,15 +1,14 @@module Spree- module Payments- # Refunds a captured payment at the gateway.+ module Refunds+ # Creates a refund and credits it back at the gateway.#- # In the workflow tier because the refund is network I/O. Today- # `Spree::Refund` fires its gateway call from an `after_create` callback,- # so the request runs inside whatever transaction the caller happens to- # hold. Creating the refund through this workflow puts the call in an- # `external_step` instead, which refuses to run inside a workflow-opened- # transaction — the record is committed first, then the gateway is- # called, then the totals are refreshed.- class Refund < Spree::Workflow+ # In the workflow tier because the credit is network I/O. The refund row+ # commits first, then the gateway is called from an external_step — a row+ # with no transaction_id is recoverable, a gateway credit with no record+ # is not. On a clean gateway failure the uncredited row is destroyed+ # (credit_allowed sums every refund row, so a dangling one would block the+ # retry); a crash between the two leaves the row for reconciliation.+ class Create < Spree::Workflowhooks :validate, :before_refund, :after_refund# The created refund — hook handlers read it (nil during :validate).@@ -21,7 +20,9 @@ module Spree# @param reason [Spree::RefundReason, nil] defaults to the store's# return-processing reason# @param refunder [Object, nil] the admin issuing the refund- def perform(payment:, amount: nil, reason: nil, refunder: nil)+ # @param originator [Object, nil] what triggered the refund — a+ # Spree::Return, Exchange or Claim; nil for a manual refund+ def perform(payment:, amount: nil, reason: nil, refunder: nil, originator: nil)superstep :ensure_refundable@@ -33,10 +34,8 @@ module Spreerun_hooks :validaterun_hooks :before_refund- # Committed before the gateway call: a refund row with no- # transaction_id is recoverable, a gateway credit with no record is- # not.- external_step :issue_refund+ step :create_refund, on_flow_failure: :destroy_uncredited_refund+ external_step :credit_at_gatewayrun_hooks :after_refundpayment.publish_event('payment.refunded')@@ -55,17 +54,26 @@ module Spreefailure(payment, :refund_amount_exceeds_balance)end- # Spree::Refund performs the gateway credit in an after_create- # callback; creating it here keeps that call outside any transaction- # this workflow opened.- def issue_refund+ def create_refund@refund = payment.refunds.create!(amount: @amount_to_refund,reason: reason || Spree::RefundReason.return_processing_reason(payment.order&.store),- refunder: refunder+ refunder: refunder,+ originator: originator)+ end++ def credit_at_gateway+ refund.perform!rescue Spree::Core::GatewayError => error- failure(payment, error.message)+ failure(refund, error.message)+ end++ # Runs when a step after create_refund fails. Only an uncredited row is+ # destroyed — a present transaction_id means the money moved, and the+ # record must survive whatever failed afterwards.+ def destroy_uncredited_refund+ refund.destroy! if refund&.transaction_id.blank?endendenddiff --git a/spree/core/app/workflows/spree/returns/refund.rb b/spree/core/app/workflows/spree/returns/refund.rbindex 63b4114273..5e2a265690 100644--- a/spree/core/app/workflows/spree/returns/refund.rb+++ b/spree/core/app/workflows/spree/returns/refund.rb@@ -112,12 +112,13 @@ module Spree@refunds = [credit]end- # Spree::Refund performs the gateway credit in an after_create callback,- # so creating it here keeps that call out of any transaction this- # workflow opened. Payments are drained newest-first until the amount- # is covered — a split-tender order needs more than one refund.+ # Each refund row commits, then Refund#perform! credits it at the+ # gateway — explicitly, never from a callback. Payments are drained+ # newest-first until the amount is covered — a split-tender order needs+ # more than one refund.def refund_at_gatewayremaining = @amount_to_refund+ refund = nilreturn_record.order.payments.completed.each do |payment|break unless remaining.positive?@@ -125,17 +126,21 @@ module Spreecreditable = [payment.credit_allowed.to_d, remaining].minnext unless creditable.positive?- @refunds << payment.refunds.create!(+ refund = payment.refunds.create!(amount: creditable,reason: Spree::RefundReason.return_processing_reason(return_record.store),refunder: refunder,originator: return_record)+ refund.perform!+ @refunds << refundremaining -= 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)enddiff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rbindex 734845f9f2..b7793440ee 100644--- a/spree/core/lib/spree/core/dependencies.rb+++ b/spree/core/lib/spree/core/dependencies.rb@@ -147,8 +147,10 @@ module Spreepayment_create_service: 'Spree::Payments::Create',payment_capture_workflow: 'Spree::Payments::Capture',- payment_refund_workflow: 'Spree::Payments::Refund',+ payment_void_workflow: 'Spree::Payments::Void',+ refund_create_workflow: 'Spree::Refunds::Create',payments_handle_webhook_workflow: 'Spree::Payments::HandleWebhook',+ payment_session_complete_workflow: 'Spree::PaymentSessions::Complete',# finderscurrent_store_finder: 'Spree::Stores::FindDefault',diff --git a/spree/core/spec/models/spree/order/payment_spec.rb b/spree/core/spec/models/spree/order/payment_spec.rbindex 16b89194b2..6e09c1489a 100644--- a/spree/core/spec/models/spree/order/payment_spec.rb+++ b/spree/core/spec/models/spree/order/payment_spec.rb@@ -13,7 +13,9 @@ module Spreeendit 'processes the checkout payment' do- payment = create(:payment, amount: 100, order: order)+ # The creation flow stores the gateway profile while the card number is+ # still in memory — row save alone no longer does.+ payment = create(:payment, amount: 100, order: order).tap(&:create_payment_profile)order.process_payments!order.update_statuses!@@ -40,7 +42,7 @@ module Spreeendcontext 'with a store credit payment method captured manually' do- let!(:payment) { create(:payment, order: order, amount: payment_amount) }+ let!(:payment) { create(:payment, order: order, amount: payment_amount).tap(&:create_payment_profile) }let!(:store_credit_payment) docreate(:store_credit_payment,diff --git a/spree/core/spec/models/spree/payment_spec.rb b/spree/core/spec/models/spree/payment_spec.rbindex 11be2752c1..1a67b51682 100644--- a/spree/core/spec/models/spree/payment_spec.rb+++ b/spree/core/spec/models/spree/payment_spec.rb@@ -229,10 +229,10 @@ describe Spree::Payment, type: :model docontext 'when payment method supports profiles' docontext 'when source is a credit card' dolet(:source) { create(:credit_card) }- let(:payment) { build(:payment, source: source) }+ let(:payment) { create(:payment, source: source) }it 'creates a payment profile' do- expect { payment.save! }.to change { source.gateway_customer_profile_id }.from(nil).to(/BGS-/)+ expect { payment.create_payment_profile }.to change { source.gateway_customer_profile_id }.from(nil).to(/BGS-/)endend@@ -241,10 +241,10 @@ describe Spree::Payment, type: :model dolet(:order) { create(:order, customer: user, total: 100) }let(:gateway) { create(:custom_payment_method) }let(:source) { create(:payment_source, customer: user, payment_method: gateway) }- let(:payment) { build(:custom_payment, source: source, amount: 100, payment_method: gateway) }+ let(:payment) { create(:custom_payment, source: source, amount: 100, payment_method: gateway) }it 'creates a payment profile' do- expect { payment.save! }.to change { source.gateway_customer_profile_id }.from(nil).to("CUSTOMER-#{user.id}")+ expect { payment.create_payment_profile }.to change { source.gateway_customer_profile_id }.from(nil).to("CUSTOMER-#{user.id}")endendend@@ -891,69 +891,61 @@ describe Spree::Payment, type: :model doallow(payment.source).to receive_messages has_payment_profile?: falseend+ it 'never creates the profile from the save itself' do+ expect(gateway).not_to receive(:create_profile)++ Spree::Payment.create(+ amount: 100,+ order: order,+ source: card,+ payment_method: gateway+ )+ end+context 'when there is an error connecting to the gateway' doit 'calls gateway_error' do- message = 'gateway_error'- connection_error = Spree::PaymentConnectionError.new(message)+ connection_error = Spree::PaymentConnectionError.new('gateway_error')expect(gateway).to receive(:create_profile).and_raise(connection_error)- expect do- Spree::Payment.create(- amount: 100,- order: order,- source: card,- payment_method: gateway- )- end.to raise_error(Spree::Core::GatewayError)- end- end- context 'with multiple payment attempts' do- let(:attributes) { attributes_for(:credit_card) }+ saved_payment = Spree::Payment.create(+ amount: 100,+ order: order,+ source: card,+ payment_method: gateway+ )- it 'does not try to create profiles on old failed payment attempts' do- allow_any_instance_of(Spree::Payment).to receive(:payment_method) { gateway }+ expect { saved_payment.create_payment_profile }.to raise_error(Spree::Core::GatewayError)+ end+ end- order.payments.create!(- source_attributes: attributes,- payment_method: gateway,- amount: 100- )- expect(gateway).to receive(:create_profile).exactly :once- expect(order.payments.count).to eq(1)- order.payments.create!(- source_attributes: attributes,- payment_method: gateway,- amount: 100+ context 'with an invalidated payment attempt' do+ it 'does not try to create a profile' do+ saved_payment = Spree::Payment.create!(+ amount: 100,+ order: order,+ source: card,+ payment_method: gateway)+ saved_payment.invalidate!++ expect(gateway).not_to receive(:create_profile)+ saved_payment.create_payment_profileendendcontext 'when successfully connecting to the gateway' doit 'creates a payment profile' do- expect(payment.payment_method).to receive :create_profile+ expect(gateway).to receive :create_profile+Spree::Payment.create(amount: 100,order: order,source: card,payment_method: gateway- )+ ).create_payment_profileendendend-- context 'when profiles are not supported' do- before { allow(gateway).to receive_messages payment_profiles_supported?: false }-- it 'does not create a payment profile' do- expect(gateway).not_to receive :create_profile- Spree::Payment.create(- amount: 100,- order: order,- source: card,- payment_method: gateway- )- end- endenddescribe '#build_source' dodiff --git a/spree/core/spec/models/spree/refund_spec.rb b/spree/core/spec/models/spree/refund_spec.rbindex fc5f76c31e..2c9065214e 100644--- a/spree/core/spec/models/spree/refund_spec.rb+++ b/spree/core/spec/models/spree/refund_spec.rb@@ -24,8 +24,10 @@ describe Spree::Refund, type: :model doendend- describe 'create' do- subject { create(:refund, payment: payment, amount: amount, reason: refund_reason, transaction_id: nil) }+ describe '#perform!' do+ subject { refund.perform! }++ let(:refund) { create(:refund, payment: payment, amount: amount, reason: refund_reason, transaction_id: nil) }let(:amount) { 100.0 }let(:amount_in_cents) { amount * 100 }@@ -49,7 +51,7 @@ describe Spree::Refund, type: :model dolet(:gateway_response_success) { true }let(:gateway_response_message) { '' }let(:gateway_response_params) { {} }- let(:gateway_response_options) { {} }+ let(:gateway_response_options) { { authorization: authorization } }before doallow(payment.payment_method).@@ -58,36 +60,30 @@ describe Spree::Refund, type: :model doand_return(gateway_response)end- context 'transaction id exists on creation' do- subject { create(:refund, payment: payment, amount: amount, reason: refund_reason, transaction_id: transaction_id) }+ it 'is never attempted by creation alone' do+ expect(payment.payment_method).not_to receive(:credit)- let(:transaction_id) { '12kfjas0' }+ refund+ end- it 'creates a refund record' do- expect { subject }.to change { Spree::Refund.count }.by(1)- end+ context 'when the refund was already credited' do+ let(:refund) { create(:refund, payment: payment, amount: amount, reason: refund_reason, transaction_id: '12kfjas0') }- it 'maintains the transaction id' do- expect(subject.reload.transaction_id).to eq transaction_id- end+ it 'does not attempt to process a transaction' do+ expect(payment.payment_method).not_to receive(:credit)- it 'saves the amount' do- expect(subject.reload.amount).to eq amount+ subjectend- it 'does not attempt to process a transaction' do- expect(payment.payment_method).not_to receive(:credit)+ it 'maintains the transaction id' dosubject+ expect(refund.reload.transaction_id).to eq '12kfjas0'endendcontext 'processing is successful' do- let(:gateway_response_options) { { authorization: authorization } }-- it 'creates a refund' do- expect { subject }.to change { Spree::Refund.count }.by(1)- end-+ # Creation no longer credits, so the count and return-value examples moved+ # to the workflow spec; the instrumentation belongs with the call itself.it 'instruments the credit gateway call as gateway.spree_payments' donotifications = []subscriber = ActiveSupport::Notifications.subscribe('gateway.spree_payments') do |*, payload|@@ -101,24 +97,19 @@ describe Spree::Refund, type: :model doActiveSupport::Notifications.unsubscribe(subscriber)end- it 'return the newly created refund' do- expect(subject).to be_a(Spree::Refund)- end-it 'saves the returned authorization value' do- expect(subject.reload.transaction_id).to eq authorization- end-- it 'saves the passed amount as the refund amount' do- expect(subject.amount).to eq amount+ subject+ expect(refund.reload.transaction_id).to eq authorizationendit 'attempts to process a transaction' doexpect(payment.payment_method).to receive(:credit).once+subjectendit 'recalculates order totals' do+ refundexpect { subject }.to change { payment.order.reload.updated_at }endend@@ -127,10 +118,10 @@ describe Spree::Refund, type: :model dolet(:gateway_response_success) { false }let(:gateway_response_message) { 'failure message' }- it 'raises error and not create a refund' do- expect do- expect { subject }.to raise_error(Spree::Core::GatewayError, gateway_response_message)- end.not_to change { Spree::Refund.count }+ it 'raises and leaves the refund uncredited for the caller to handle' do+ expect { subject }.to raise_error(Spree::Core::GatewayError, gateway_response_message)++ expect(refund.reload.transaction_id).to be_nilendend@@ -166,13 +157,12 @@ describe Spree::Refund, type: :model docontext 'with a gateway connection error' dobefore do- message = 'gateway_error'expect(payment.payment_method).to receive(:credit).with(amount_in_cents,payment.source,payment.transaction_id,originator: an_instance_of(Spree::Refund)- ).and_raise(Spree::PaymentConnectionError.new(message))+ ).and_raise(Spree::PaymentConnectionError.new('gateway_error'))endit 'raises Spree::Core::GatewayError' do@@ -184,8 +174,8 @@ describe Spree::Refund, type: :model dolet(:payment_amount) { 10 }let(:amount) { payment_amount * 2 }- it 'is invalid' do- expect { subject }.to raise_error { |error|+ it 'refuses to create the refund' do+ expect { refund }.to raise_error { |error|expect(error).to be_a(ActiveRecord::RecordInvalid)expect(error.record.errors.full_messages).to eq ["Amount #{I18n.t('activerecord.errors.models.spree/refund.attributes.amount.greater_than_allowed')}"]}diff --git a/spree/core/spec/workflows/spree/payment_sessions/complete_spec.rb b/spree/core/spec/workflows/spree/payment_sessions/complete_spec.rbnew file mode 100644index 0000000000..a0ab5827ee--- /dev/null+++ b/spree/core/spec/workflows/spree/payment_sessions/complete_spec.rb@@ -0,0 +1,68 @@+require 'spec_helper'++RSpec.describe Spree::PaymentSessions::Complete do+ let(:store) { @default_store }+ let(:order) { create(:order, store: store, total: 50) }+ let(:payment_method) { create(:bogus_payment_method, store: store) }+ let(:payment_session) { create(:bogus_payment_session, order: order, payment_method: payment_method, amount: 50) }++ before { Spree.hooks.clear! }+ after { Spree.hooks.clear! }++ it 'completes the session through the gateway' do+ result = described_class.call(payment_session: payment_session)++ expect(result).to be_success+ expect(result.value.status).to eq('completed')+ end++ it 'passes the client params through to the gateway' do+ expect(payment_method).to receive(:complete_payment_session).+ with(payment_session: payment_session, params: { 'session_result' => 'ok' })+ allow(payment_session).to receive(:payment_method).and_return(payment_method)++ described_class.call(payment_session: payment_session, params: { 'session_result' => 'ok' })+ end++ it 'is an idempotent success on an already-completed session' do+ payment_session.update_column(:status, 'completed')+ expect_any_instance_of(Spree::PaymentMethod).not_to receive(:complete_payment_session)++ result = described_class.call(payment_session: payment_session)++ expect(result).to be_success+ end++ it 'surfaces a gateway error as a failure result' do+ allow(payment_session).to receive(:payment_method).and_return(payment_method)+ allow(payment_method).to receive(:complete_payment_session).+ and_raise(Spree::Core::GatewayError, 'verification failed')++ result = described_class.call(payment_session: payment_session)++ expect(result).to be_failure+ expect(result.error.value).to eq('verification failed')+ end++ describe 'hooks' do+ it 'lets a validate handler veto settlement before the gateway is called' do+ expect_any_instance_of(Spree::PaymentMethod).not_to receive(:complete_payment_session)+ Spree.hooks.register('payment_sessions.complete.validate') { |flow| flow.reject!('on fraud hold') }++ result = described_class.call(payment_session: payment_session)++ expect(result).to be_failure+ expect(result.error.value).to eq('on fraud hold')+ expect(payment_session.reload.status).to eq('pending')+ end++ it 'runs after_complete with the settled session' do+ seen = nil+ Spree.hooks.register('payment_sessions.complete.after_complete') { |flow| seen = flow.payment_session.status }++ described_class.call(payment_session: payment_session)++ expect(seen).to eq('completed')+ end+ end+enddiff --git a/spree/core/spec/workflows/spree/payments/void_spec.rb b/spree/core/spec/workflows/spree/payments/void_spec.rbnew file mode 100644index 0000000000..55714e4171--- /dev/null+++ b/spree/core/spec/workflows/spree/payments/void_spec.rb@@ -0,0 +1,65 @@+require 'spec_helper'++RSpec.describe Spree::Payments::Void do+ let(:payment) { create(:payment, state: 'pending', amount: 45.75) }++ before { Spree.hooks.clear! }+ after { Spree.hooks.clear! }++ describe 'voiding' do+ it 'voids the payment at the gateway' do+ expect(payment).to receive(:void_transaction!).and_return(true)++ expect(described_class.call(payment: payment)).to be_success+ end++ it 'is a no-op for an already-void payment' do+ voided = create(:payment, state: 'void')+ expect(voided).not_to receive(:void_transaction!)++ expect(described_class.call(payment: voided)).to be_success+ end++ it 'fails without calling the gateway when the payment cannot be voided' do+ failed = create(:payment, state: 'failed')+ expect(failed).not_to receive(:void_transaction!)++ result = described_class.call(payment: failed)++ expect(result).to be_failure+ expect(result.error.value).to eq(:payment_not_voidable)+ end++ it 'surfaces a gateway error as a failure result' do+ allow(payment).to receive(:void_transaction!).and_raise(Spree::Core::GatewayError, 'cannot void')++ result = described_class.call(payment: payment)++ expect(result).to be_failure+ expect(result.error.value).to eq('cannot void')+ end+ end++ describe 'hooks' do+ it 'lets a validate handler veto the void before the gateway is called' do+ expect(payment).not_to receive(:void_transaction!)+ Spree.hooks.register('payments.void.validate') { |flow| flow.reject!('under review') }++ result = described_class.call(payment: payment)++ expect(result).to be_failure+ expect(result.error.value).to eq('under review')+ end++ it 'runs after_void once the gateway call succeeds' do+ allow(payment).to receive(:void_transaction!).and_return(true)++ voided = false+ Spree.hooks.register('payments.void.after_void') { |_flow| voided = true }++ described_class.call(payment: payment)++ expect(voided).to be(true)+ end+ end+enddiff --git a/spree/core/spec/workflows/spree/payments/refund_spec.rb b/spree/core/spec/workflows/spree/refunds/create_spec.rbsimilarity index 56%rename from spree/core/spec/workflows/spree/payments/refund_spec.rbrename to spree/core/spec/workflows/spree/refunds/create_spec.rbindex d2b3594fd6..44e1fbdb36 100644--- a/spree/core/spec/workflows/spree/payments/refund_spec.rb+++ b/spree/core/spec/workflows/spree/refunds/create_spec.rb@@ -1,19 +1,19 @@require 'spec_helper'-RSpec.describe Spree::Payments::Refund do+RSpec.describe Spree::Refunds::Create dolet(:payment) { create(:payment, state: 'completed', amount: 45.75) }before doSpree.hooks.clear!- # Spree::Refund performs the gateway credit in an after_create callback.allow_any_instance_of(Spree::Refund).to receive(:perform!).and_return(true)endafter { Spree.hooks.clear! }describe 'refunding' do- it 'creates a refund for the full creditable balance by default' do+ it 'creates a refund for the full creditable balance and credits it at the gateway' docreditable = payment.credit_allowed+ expect_any_instance_of(Spree::Refund).to receive(:perform!)result = described_class.call(payment: payment)@@ -28,6 +28,14 @@ RSpec.describe Spree::Payments::Refund doexpect(result.value.amount).to eq(10)end+ it 'records the originator' do+ originator = create(:return)++ result = described_class.call(payment: payment, originator: originator)++ expect(result.value.originator).to eq(originator)+ end+it 'refuses to refund a payment that was never captured' dopending_payment = create(:payment, state: 'pending')@@ -49,11 +57,35 @@ RSpec.describe Spree::Payments::Refund doit 'refuses a non-positive amount' doexpect(described_class.call(payment: payment, amount: 0)).to be_failureend++ it 'destroys the uncredited refund when the gateway declines' do+ allow_any_instance_of(Spree::Refund).to receive(:perform!).+ and_raise(Spree::Core::GatewayError, 'declined')++ result = described_class.call(payment: payment)++ expect(result).to be_failure+ expect(result.error.value).to eq('declined')+ expect(payment.refunds.reload).to be_empty+ end++ it 'keeps a credited refund even when a later step fails' do+ allow_any_instance_of(Spree::Refund).to receive(:perform!) do |refund|+ refund.update_columns(transaction_id: 'txn_123')+ end+ Spree.hooks.register('refunds.create.after_refund') { |flow| flow.reject!('observer exploded') }++ result = described_class.call(payment: payment)++ expect(result).to be_failure+ expect(payment.refunds.reload.count).to eq(1)+ expect(payment.refunds.first.transaction_id).to eq('txn_123')+ endenddescribe 'hooks' doit 'lets a validate handler veto the refund before the record is created' do- Spree.hooks.register('payments.refund.validate') { |flow| flow.reject!('refunds disabled') }+ Spree.hooks.register('refunds.create.validate') { |flow| flow.reject!('refunds disabled') }result = described_class.call(payment: payment)@@ -64,7 +96,7 @@ RSpec.describe Spree::Payments::Refund doit 'exposes the created refund to after_refund' doseen = nil- Spree.hooks.register('payments.refund.after_refund') { |flow| seen = flow.refund }+ Spree.hooks.register('refunds.create.after_refund') { |flow| seen = flow.refund }described_class.call(payment: payment, amount: 5)diff --git a/spree/providers/stripe/app/models/spree_stripe/gateway.rb b/spree/providers/stripe/app/models/spree_stripe/gateway.rbindex 5d9f6cd4b9..2428e86b7a 100644--- a/spree/providers/stripe/app/models/spree_stripe/gateway.rb+++ b/spree/providers/stripe/app/models/spree_stripe/gateway.rb@@ -108,6 +108,13 @@ module SpreeStriperefunder_id: payment.order.canceler_id)+ begin+ refund.perform!+ rescue Spree::Core::GatewayError+ refund.destroy! if refund.transaction_id.blank?+ raise+ end+# 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)