Overview
Spree has a highly flexible payments model which allows multiple payment methods to be available during the checkout. The logic for processing payments is decoupled from orders, making it easy to define custom payment methods with their own processing logic. Payment methods typically represent a payment gateway. Gateways will process card payments, online bank transfers, buy-now-pay-later, wallet payments, and other types of payments. Spree also comes with a Check option for offline processing. ThePayment model in Spree tracks payments against Orders. Payments relate to a source which indicates how the payment was made, and a PaymentMethod, indicating the processor used for this payment.
A payment’s number is derived from what it belongs to — an order R1001 numbers its payments R1001-P1, R1001-P2 — so a gateway reference traces straight back to the order without a lookup.
Payment Architecture Diagram
Key relationships:- Payment tracks each payment attempt against an Order
- Payment Method defines how payments are processed (Stripe, Adyen, PayPal, Check, etc.)
- Payment Session manages the gateway-side payment lifecycle (e.g., Stripe PaymentIntent, Adyen Session)
- Payment Setup Session manages saving payment methods for future use without an immediate charge (e.g., Stripe SetupIntent)
- Source is polymorphic - can be a Credit Card, Payment Source (for alternative methods like Klarna, iDEAL), or Store Credit
- Gateway Customer stores the provider-specific customer profile (e.g., Stripe Customer ID)
- Refunds track money returned to customers
Payment Methods
Payment methods represent the different options a customer has for making a payment. Most sites will accept credit card payments through a payment gateway, but there are other options. Spree also comes with built-in support for a Check payment, which can be used to represent any offline payment. Gateway providers such as Stripe, Adyen, and PayPal provide a wide range of payment methods, including credit cards, bank transfers, buy-now-pay-later, and digital wallets (Apple Pay, Google Pay, etc.). APaymentMethod can have the following attributes:
Each payment method belongs to one store. To offer a method only on some channels, in some markets or to some customers, give it rules.
Payment method rules
Rules decide whether a payment method is offered at storefront checkout. A method with no rules is offered everywhere; with rules, every rule must pass. Rules read the cart’s own channel, market, total, customer and company, so the cart’s list of payment methods and payment and session creation all apply them. Payments created through the Admin API or the dashboard ignore rules, so staff can record any active method against an order.
An empty
channel_ids, market_ids or customer_group_ids list restricts nothing, so a rule saved half-configured never hides a method. A company_rule with no companies listed still requires a company while company_orders_only is on, which is the default. Rules are sent with the payment method as rules, which replaces the whole set, or managed one at a time. A payment method returns its rules only when asked with expand=rules:
- Admin SDK
- cURL
Spree::PaymentMethodRule, implementing eligible?(purchase), and appending the class to Spree.payment_method_rules. The provider’s own available_for_order? check still runs first.
Several accounts of one provider
A store can hold more than one payment method of the same provider. Each is a separate account, with its own credentials and webhook endpoint. Give each amarket_rule with markets that don’t overlap: rules never choose between methods, so two methods whose rules both pass are both offered.
The Store API sends each method’s public_preferences, the configuration a storefront needs to load it. Stripe lists its publishable key there, so the storefront loads Stripe.js with the account the cart was offered. A provider gem makes a preference public by listing it in public_preference_keys.
Session-based vs direct payment methods
Payment methods indicate whether they use the modern session-based flow via thesession_required? method:
Gateways like Stripe and Adyen set
session_required? to true; offline methods leave it false. Neither path is deprecated. The Store API serializer includes this as the session_required field so your frontend knows which flow to use.
Direct payment methods (manual and offline)
Payment methods wheresession_required? returns false don’t need a payment session. These are typically offline or manual payment methods such as:
- Check — built in
- Cash on Delivery — customer pays upon delivery
- Bank Transfer / Wire — customer transfers money to a bank account
- Purchase Order — common in B2B, customer provides a PO number
checkout. Completing the cart processes it — for a manual method there is no provider to call, so it succeeds immediately and lands on pending, or completed when the store charges at checkout.
Once the money actually arrives — the cheque clears, the transfer lands, the
driver is paid — staff capture the payment from the dashboard, or you do it
through the Admin API:
Admin SDK
Payment Flow
Spree supports two payment flows depending on the payment method type:Session-Based Flow (Stripe, Adyen, PayPal, etc.)
Modern payment gateways use a three-phase approach: first a Payment Session is created with the gateway, then the customer completes payment on the frontend, and finally the order is completed via an explicit API call. Payment processing and order completion are intentionally separated — this prevents race conditions and ensures reliable checkout regardless of payment method type (cards, wallets, offsite redirects).1
Create Payment Session
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 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
client_secret for the frontend SDK.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.
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.2
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. If the payment requires 3D Secure authentication or redirects to an offsite gateway (CashApp, Klarna, etc.), the gateway SDK handles it automatically.3
Complete Payment Session
After the customer completes payment, the frontend calls the Complete Payment Session endpoint. Spree verifies the payment status with the gateway, creates a
Payment record, creates the appropriate payment source (Credit Card, wallet, etc.), and marks the session as completed.This step does NOT complete the order — it only handles payment processing. For wallet payments (Apple Pay, Google Pay), the gateway also patches the order’s billing address with data from the wallet at this stage.The cart is locked once Spree records that the gateway accepted the payment: a payment session on the cart is processing or completed, or a valid payment settled from one of its sessions (any status past checkout) exists. A payment belongs to a session when its response_code is the session’s external_id under the same payment method. From then on, changing its items, addresses, delivery, discount codes or gift cards answers 409 with completion_in_progress until the cart completes. The money was taken for exactly those contents, and the gateway’s webhook places the order from them even if the frontend never calls Complete Order. Until Spree records one of those, the cart stays editable, even if the gateway has already taken the money. The cart is released when the money is no longer held: a processing or completed session releases it once the payment recorded for it is voided or fails (with no payment recorded, it holds the cart until the cart completes). A failed or canceled session does not release the cart while a valid payment settled from it exists; voiding that payment releases it. A pending session alone does not lock the cart. Nothing releases it on a timer. If the cart is only out of stock, the webhook job keeps retrying until the store’s stock reservation TTL (plus a grace period) has passed since the payment settled, since stock another cart holds comes back when its reservation expires. If the cart still cannot complete — it no longer meets another checkout requirement, lost a coupon code, or its tax provider refuses the sale — the webhook job stops retrying, keeps the payment recorded on the cart, and reports a Spree::Payments::HandleWebhookJob::CompletionBlocked error through Rails.error with the payment session, its gateway reference and the reason, for staff to refund or resolve the payment.4
Complete Order
The frontend calls
POST /carts/:id/complete to finalize the order. Spree checks the cart has everything it needs — addresses, fulfillments, payment — and turns it into an order.This separation ensures the same flow works for all payment types — inline cards, offsite redirects, and wallet payments.Offsite Payment Flow (CashApp, 3D Secure, Klarna, etc.)
For payment methods that redirect the customer away from your site, use an intermediate confirm-payment page:Webhook-Driven Completion (Browser Closed)
If the customer closes the browser after paying but before the frontend callscomplete, Spree handles this via payment webhooks:
Gateway extensions implement parse_webhook_event to normalize provider-specific payloads into a standard format. Spree core handles the rest — creating the payment record, completing the session, and finalizing the order.
Direct Payment Flow (Check, Cash on Delivery, Bank Transfer, etc.)
Non-session payment methods use a simpler flow where a payment is created directly without involving an external payment provider:1
List payment methods
The frontend reads the cart’s embedded
payment_methods (returned by GET /carts/:id) and checks the session_required flag on each method. Methods with session_required: false use this direct flow.2
Create payment
The frontend calls
POST /payments with the payment_method_id. Spree creates a payment with status checkout. No provider is contacted.Two refusals to handle: a method needing a session returns payment_session_required, and one unavailable for this order returns payment_method_unavailable — both HTTP 422 with that code.3
Complete order
The frontend completes the order. Completing the cart processes the payment. For a manual method there is nothing to call, so it succeeds immediately and lands on
pending, or completed when the store charges at checkout. Staff capture pending payments from the dashboard once the money arrives.Payment Session
A payment session represents a server-side session with the payment gateway. It is the entry point for every payment attempt and holds the provider-specific data needed by the frontend SDK.Attributes
A session also carries
order_id, but during checkout there is no order yet —
it reports the cart’s ID until the cart completes. Read cart_id while paying,
and order_id once you have an order.States
There is no cancel endpoint. A session reaches
canceled when the provider
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.API
Create a Payment Session:StorePaymentSession):
Response
Payment Webhooks
Spree provides a generic webhook endpoint atPOST /api/v3/webhooks/payments/:payment_method_id that payment gateway extensions can use. When a payment provider sends a webhook (e.g., Stripe payment_intent.succeeded), Spree:
- Verifies the webhook signature synchronously (returns
401if invalid) - Enqueues a background job to process the event
- Returns
200 OKimmediately
Gateway Interface
Gateway extensions implementparse_webhook_event to normalize provider-specific payloads:
server/app/models/my_gateway.rb
:captured, :authorized, :failed, :canceled.
A gateway may also return metadata: with a session outcome. It reaches the
session’s settlement (apply_settlement_metadata) through a background job, so
it must be JSON-safe with string keys.
Providers that answer later
Some providers, Adyen among them, accept a capture, void or refund and report the outcome later by webhook. A gateway for such a provider answers the request withrequested: true:
server/app/models/my_gateway.rb
- A capture writes a capture event in status
requested, with the provider’s reference for the capture (reference:) as itstransaction_id, and leaves the paymentrequested. - A void, or the cancel of an uncaptured payment, leaves the payment
requested.Payment#requested_actionanswerscaptureorvoid. - A refund stays
requested, with the provider’s refund reference as itstransaction_id.
requested payment: capture, void, refund and
order cancellation refuse it, and settlement leaves it alone. The provider’s
outcome arrives through the same webhook endpoint. parse_webhook_event returns
it with the reference: of the record it settles, and a background job finds
the record with the payment method’s modification_record(action, reference):
By default
modification_record matches the reference against a capture
event’s or refund’s transaction_id, and for a void against the response code
of a payment waiting on it. Override it when the provider names records
otherwise.
An outcome can arrive before Spree has written its record: the request is
still finishing, or its answer never reached Spree and a retry writes the record
later. The job looks again, quickly at first and then every few hours, for 7
days (how long a retried request still gets the provider’s first answer), and
then reports the outcome as never recorded. A capture outcome may also name the
payment: its capture was asked for and the amount taken
(metadata: { 'amount' => ... }): if the capture’s answer never reached Spree,
the payment is left processing, and once no request can still be running the
outcome records the capture on it.
Pass the provider’s reason for a failure as metadata: { 'reason' => ... }. A
repeat delivery changes nothing. A gateway that answers requested? must
report these outcomes; one that answers at once never does.
When a session settles as captured, the session’s
capture_reference_for_settlement(payment) hook (nil by default) names the
provider’s reference for that capture, written on its capture event so a late
capture failure can find it.
Payment
Once a payment session completes, Spree creates a payment to record the result, linked to the session byresponse_code matching its external_id.
Attributes
These are the fields the Store API returns:source_type is a plain name — credit_card, not a class name — so you can
switch on it directly.Payment statuses
When the money is taken follows the store’s
capture_method, which a payment
method can override for its own payments:
The last two leave the payment at
pending until capture. See
Configuration for where the store
setting lives.
There is no state machine behind these. A payment’s status is written by the
workflows that process, capture and void it, so nothing transitions on its own
and there is no sequence a client has to drive.
Order Payment Status
Each payment update also recalculates the order’spayment_status, derived from its payments and refunds against the order total:
Refunds
Refunds are an Admin API operation — there is no Store API route, so a customer cannot start one from your storefront:Admin SDK
payment.refunded and moves the order’s payment_status to
partially_refunded or refunded.
Refunds and capture events have a status: completed, or requested while a
provider that answers later has not answered, or failed. Captured and
refunded money counts completed rows only. A balance check counts every refund
that has not failed, so a requested refund keeps its amount reserved. A
requested refund publishes refund.requested; payment.refunded follows
when the provider confirms it. Rows written before the 6.0 patch release that
added the status read as completed until the backfill_settlement_statuses
upgrade step fills their status in.
Payment Sources
Payment sources represent the actual instrument used for a payment. They are created automatically when a Payment Session completes.Saved cards
Stores non-sensitive credit card information. With modern gateways, the actual card data is tokenized by the provider - Spree only stores reference IDs and display information.Spree never stores full credit card numbers. With modern gateways, card data is collected entirely by the gateway’s frontend SDK (e.g., Stripe.js, Adyen Drop-in) and never touches your server. Spree only stores the tokenized reference (
gateway_payment_profile_id) returned by the provider.Payment Sources
A generic payment source model for non-card payment methods such as digital wallets, bank transfers, and buy-now-pay-later services. Gateway integrations create subtypes for each payment method type (e.g., Klarna, Afterpay, iDEAL, Apple Pay, Google Pay, PayPal).Gateway customers
Maps a Spree customer to their provider-specific customer profile. This enables features like saved payment methods, recurring billing, and customer-level fraud detection.
A customer has at most one record per payment method, and
profile_id is encrypted with Active Record encryption where it is configured.
This one is internal — the API does not expose it. It is listed here because
gateway integrations rely on it; nothing a storefront does will read it.
Payment Setup Sessions
Payment setup sessions let customers save payment methods for future use without making an immediate payment. This maps to concepts like Stripe’s SetupIntent - a secure way to collect and tokenize payment details for later charges.Use Cases
- Saving a credit card to the customer’s account for faster future checkouts
- Authorizing a payment method for subscription billing
- Adding a payment method during account onboarding (before any purchase)
How Payment Setup Sessions Work
Payment Setup Session Attributes
Payment Setup Session API
Payment Setup Sessions require customer authentication. The customer must be logged in.
StorePaymentSetupSession):
Response
external_client_secret):
Supported Gateways
Spree team maintains several payment gateway integrations. All of these gateways are fully PCI compliant, using native gateway SDKs, meaning no sensitive payment data is stored or processed through Spree.Stripe
Stripe integration, supports all Stripe payment methods, including credit cards, bank transfers, Apple Pay, Google Pay, Klarna, Afterpay, and more. Also supports quick checkout.
Adyen
Adyen integration, supports all Adyen payment methods, including credit cards, bank transfers, Apple Pay, Google Pay, Klarna, and more.
PayPal
Native PayPal integration, supports PayPal, PayPal Credit, and PayPal Pay Later.
Payment Events
Spree publishes events throughout the payment lifecycle that you can subscribe to. For the delivered payload schemas of these events (e.g.payment.paid, payment_session.completed), see the Webhooks & Events reference:
Payment Events
Payment Session Events
Payment Setup Session Events
See Events for more details on subscribing to events.
Two paths to a completed order
A payment can finish in two places, and both have to end at the same result. The customer’s browser confirms the payment and your storefront completes the cart. Or the provider’s own webhook arrives first — sometimes seconds later, sometimes because the customer closed the tab mid-redirect. Whichever arrives first completes the order; the other finds the work already done and does nothing. That is what makes a closed tab or a flaky connection recoverable rather than a lost sale with a real charge attached. Both paths can be replaced if your integration needs different behaviour — see Dependencies.Related Documentation
- Payments (Store SDK) - SDK how-to for payment sessions, payments, and setup sessions
- Build a Custom Payment Method - Step-by-step guide to creating your own payment gateway integration
- Orders - Order lifecycle, payment and fulfillment status
- Checkout Customization - Customizing the checkout flow
- Events - Subscribe to payment events

