Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

19.9 KB
Raw Blame

Payment Gateways in the Monorepo

Status: In Progress — Stripe implemented; Adyen pending Target: Spree 6.0 Depends on: Payment sessions infrastructure (shipped in core), 6.0-multi-vendor-marketplace.md (Phase 3b consumes the Stripe gem) Author: Damian Legawiec Last updated: 2026-10-28

Summary

Move the payment-session-compatible gateway code from the standalone spree_stripe and spree_adyen repos into the monorepo as two separate, optional, lockstep-versioned gems: spree/providers/stripe (gem spree_stripe) and spree/providers/adyen (gem spree_adyen). (Directory updated 2026-08-07: provider gems live under spree/providers/ — established with spree/providers/easypost; gem names stay flat.) Only the v3 payment-session path comes over — the gateway class, its session/setup-session models and services, payment sources, and webhook parsing. Everything serving the classic Rails storefront, the legacy admin, the legacy webhook engines, and the Storefront API v2 stays behind in the old repos, which become 5.x maintenance branches.

Why: the gateways are the only real implementations of core's payment-session contract (Spree::PaymentMethod#create_payment_session / #parse_webhook_event / #complete_payment_session, Spree::PaymentSession STI), and that contract is still evolving through 6.0. In-repo gateways give core CI real coverage (today the only in-repo implementation is Spree::PaymentSessions::Bogus), remove the cross-repo version dance on every contract change, and put the code where contributors and agents can find it. The 6.0 marketplace plan independently forces Stripe into the monorepo: Spree::PayoutProvider::StripeConnect ships OSS in-repo and needs the stripe SDK, a configured client, and webhook plumbing — keeping the gateway external would split Stripe integration across two repos.

This amends the 2026-07-15 decision's "likely into spree/core" placement: dedicated gems, not core.

Competitor context

  • Vendure bundled Stripe/Braintree/Mollie/PayPal in one in-monorepo @vendure/payments-plugin (SDKs as optional peerDependencies), then removed it in v3.6.0 to a separate community-plugins repo with one package per gateway — for community ownership and decoupled releases, after the handler contract had been stable for years. Their situation doesn't transfer: Spree's gateways are first-party (Vendo-maintained) and our contract is still moving.
  • Medusa v2 keeps exactly one first-party payment provider in the monorepo (packages/modules/providers/payment-stripe → @medusajs/payment-stripe, hard stripe dependency, framework peer pinned to the exact matching version), down from five in v1; the rest are community plugins. This — the strategic gateway in-repo as the contract's reference implementation — is the model we're following, extended to Adyen.
  • Solidus (separate gem per gateway, own repos) and Saleor (external payment apps) never bundled.
  • The one-fat-package model (spree_payments) is ruled out: RubyGems has no optional dependencies, so a single gem must either hard-depend on every gateway SDK or declare none and fail at runtime. Per-gateway gems with their own SDK dependency are the Ruby translation of Vendure's optional peer deps.

Key Decisions (do not deviate without discussion)

  1. Two gems, not core, not one bundle. spree/providers/stripe and spree/providers/adyen directories, publishing spree_stripe and spree_adyen. Core keeps only the provider-agnostic contract (Spree::PaymentMethod session methods, Spree::PaymentSession/PaymentSetupSession, Spree::GatewayCustomer, Spree::Payments::HandleWebhook, the v3 endpoints). No spree_payments umbrella gem — nothing generic is left for it to own.
  2. Existing gem names and namespaces are kept. SpreeStripe::Gateway and SpreeAdyen::Gateway stay as-is because spree_payment_methods.type and spree_payment_sessions.type store STI class names — existing installations upgrade with no data migration and the same Gemfile line. Core's Spree::Gateway.api_type already maps these namespaces.
  3. Lockstep versioning with an exact pin. s.version = Spree.version; s.add_dependency 'spree', s.version (Rails-style) while the payment-session contract is hot through 6.0/6.1, to be relaxed to ">= #{s.version}" (the spree_emails pattern) once it stabilizes. Gateway-only fixes ship as a whole-train patch release.
  4. Optional gems. The meta spree gem does not depend on them; host apps opt in via the Gemfile (starter already lists both). The spree_admin dependency is dropped — 6.0 gateway configuration goes through the Admin API / dashboard.
  5. Each gem hard-depends on its own SDK (stripe, currently >= 10.1, < 19; adyen-ruby-api-library, currently >= 10.3, < 12). SDK constraints live in the gateway gemspec, never in core.
  6. Only the v3 path is ported; use_legacy_* toggles are removed. The 6.0 gems ship a single code path. The drop-set (see Design Details) stays in the old repos.
  7. Spree::PayoutProvider::StripeConnect lives in spree/providers/stripe, next to the gateway and the SDK it requires (marketplace plan Phase 3b).
  8. Old repos become 5.x maintenance branches. Critical fixes only; no new feature work outside the monorepo.
  9. Extraction stays cheap by construction. If a gateway ever moves to community ownership (Vendure's endgame), the per-gem structure lets it leave as a directory move with names, namespaces, and STI data untouched. Folding into core would foreclose this.

Design Details

Monorepo layout

spree/
  core/                 spree_core
  api/                  spree_api
  emails/               spree_emails    (optional, depends on spree)
  providers/
    easypost/           spree_easypost  (delivery rates + fulfillment)
    stripe/             spree_stripe    (optional, depends on spree_core + stripe SDK)
    adyen/              spree_adyen     (optional, depends on spree_core + adyen-ruby-api-library)

Gateways live under spree/providers/ alongside the other third-party integrations, following the shape spree_easypost established: gem-name LIB_NAME, a flat lib/<gem_name>/ tree, and a spree_core dependency rather than the spree meta gem.

Each gateway gem is a Rails engine following the existing optional-gem shape: version from spree/core/lib/spree/core/version.rb, engine initializer registering the gateway (config.spree.payment_methods << SpreeStripe::Gateway), migrations installable via spree:install:migrations, its own RSpec suite (VCR + webmock, as in the source repos).

Keep-set (what moves)

Both source repos already ship the v3 path alongside the legacy one; the port keeps the v3 half.

Scope narrowed at implementation (2026-08-09): payment-session API only. The keep-set below is what actually shipped for Stripe — 45 files, ~1,650 LOC of source and ~2,800 lines of spec. Everything serving the classic ActiveMerchant-style checkout came out with the storefront (see Drop-set).

The six gateway money verbs — authorize, purchase, capture, credit, void, cancel — stay, because core's payment lifecycle calls them after a session completes (Payment#process! → gateway_action). Core's own reference session gateway, Spree::Gateway::Bogus, implements the same six. What left is the machinery around them: creating intents for payments that never had a session, off-session confirmation, and the storefront's redirect/confirm flow.

Stripe (39 files, ~1,400 LOC):

  • SpreeStripe::Gateway + Gateway::PaymentSessions, Gateway::PaymentSetupSessions, Gateway::Webhooks concerns (intents are Stripe-side API objects created by the session flow — no intent AR model and no separate intents concern)
  • Spree::PaymentSessions::Stripe, Spree::PaymentSetupSessions::Stripe (core-table STI subclasses)
  • Payment sources (Klarna, Affirm, Alipay, iDEAL, Link, SEPA, bank transfer, Przelewy24, AfterPay), services (CreatePayment, CreateSource, CreateGatewayWebhooks, UpdateCustomer), jobs, the .stripe scopes on PaymentMethod/GatewayCustomer
  • CreatePaymentSession came over and was deleted as unused (2026-08-12). The pending-session reuse it did for the Rails storefront was briefly in Gateway::PaymentSessions#create_payment_session (2026-09-30, V-3726) and removed on 2026-10-04: creating a session always opens a new one, and the earlier open sessions for that gateway are canceled first.

Apple Pay / Google Pay domain registration is dropped too (2026-08-10). It assumed Spree knows the storefront's domain, which a headless install does not — the storefront is someone else's deployment, on a domain the backend never sees. Registering store.url there registers the wrong host. Merchants register their domains in the Stripe dashboard, which is where a headless setup has to do it anyway. This removes RegisterDomain, its job, the CustomDomain decorator and the domain accessors on Store.

Stripe payment intents are not a separate subsystem and have no concern of their own: creating a payment session is creating an intent, so those calls live in Gateway::PaymentSessions with the payload building private to it.

Core adaptations the port required

6.0 core moved under the gem in four ways; every one of them touched the keep-set:

6.0 core change Effect on the gateway
PaymentMethod belongs_to :store stores.first / stores.ids collapse to store; one webhook endpoint per gateway
private_metadata + public_metadata → one metadata column every store_accessor, plus the credit-card source params
user → customer (Spree.customer_class) fetch_or_create_customer, CreateSource, UpdateCustomer, wallet-address patching; Customer#full_name, not #name
Cart/Order split sessions take an owner (cart or order); Carts::Complete owns completion, so the gateway never completes an order

Core's fingerprint-dedup backport (CreditCardDecorator) is dropped outright — the column, scope and validation are all in 6.0 core.

Adyen (~98 files, ~3,400 LOC, of which 60 are one-per-method payment sources):

  • SpreeAdyen::Gateway + session/setup-session concerns, HMAC-validating parse_webhook_event, management-API auto-configuration (webhook setup, HMAC/client key generation, allowed origins)
  • Spree::PaymentSessions::Adyen, Spree::PaymentSetupSessions::Adyen (core-table STI subclasses)
  • Event processors (authorisation/capture/cancellation), webhook services, payment sources, presenters, jobs. Adyen stashes PSP references via Spree::Metafields on the payment. Amended 2026-11-02: PSP references go in payment metadata, never in custom fields, which belong to the merchant (6.0-6.1-custom-fields-roadmap.md).

Drop-set (stays in the old repos)

  • Classic Rails storefront: all app/javascript/, storefront ERB partials, checkout/store controller decorators and helpers, redirect/confirm-payment controllers, Apple Pay domain-verification file routes
  • Legacy webhook paths: the stripe_event engine mount + subscriber block and its handler services; Adyen's POST /adyen/webhooks controller and the config.spree_adyen event-code → handler registry. The stripe_event gem leaves the gemspec entirely; webhooks arrive at core's /api/v3/webhooks/payments/:id and route through #parse_webhook_event.
  • SpreeAdyen::PaymentSession standalone model and its spree_adyen_payment_sessions table + migrations (superseded by the core-table Spree::PaymentSessions::Adyen)
  • Adyen's Storefront API v2 tree (lib/spree_api_v2/) and conditional routes
  • Assorted AR decorators (order/payment/store/custom_domain/user) tied to the legacy flows
  • All use_legacy_* preferences and both branches of their conditionals
  • Apple Pay / Google Pay domain registration (2026-08-10): RegisterDomain, RegisterDomainJob, the CustomDomain decorator and the domain accessors on Store. It presumed the backend knows the storefront's domain, which is false headless — merchants register domains in the Stripe dashboard instead.
  • Classic-checkout payment machinery (2026-08-09): Stripe Tax (Calculators::StripeTax, TaxPresenter, CreateTaxTransactionJob, the shipment decorator that fired it), SpreeStripe::CompleteOrder + CompleteOrderFromSessionJob (Carts::Complete owns completion), ensure_payment_intent_exists_for_payment and off-session intents, AttachCustomerToCreditCardJob

Registration and admin surface

Nothing new. Gateways register on Rails.application.config.spree.payment_methods in their engine initializer; GET /api/v3/admin/payment_methods/types derives availability from loaded providers, so "gem in Gemfile" = "type offered in admin" with no conditional-SDK logic. Webhook endpoints are the core v3 ones (/api/v3/webhooks/payments/:payment_method_id); Gateway#webhook_url and #parse_webhook_event already target them.

Migration Path

  1. Port Stripe into spree/providers/stripe — done 2026-08-09. Gem builds and loads in a full Rails app alongside dashboard/api/emails; registers as api_type: "stripe" with no registry collision; the suite passes offline, single-process and under parallel_shard. Wired into both CI matrices (PostgreSQL + MySQL) and the bundle-install loops. The starter Gemfile change lives in the spree-starter repo — server/ is gitignored here, so that edit still has to be made upstream.
  2. Port Adyen into spree/providers/adyen the same way.
  3. Marketplace Phase 3b adds Spree::PayoutProvider::StripeConnect inside spree/providers/stripe.
  4. Old repos flip to maintenance mode: README banner pointing at the monorepo, 5.x branch for critical fixes, no 6.0 release cut from them.
  5. Host apps upgrade by bumping the gem version — same gem 'spree_stripe' / gem 'spree_adyen' lines, now resolved from the 6.0 release train. No STI data migration. Apps still on the legacy storefront/webhook paths must complete the v3 migration (the use_legacy_* off state) before 6.0, per the gems' existing 5.x migration guides.

Constraints on Current Work

  • The Adyen port takes amounts as Spree::Money (self.accepts_money_amounts = true) and converts them to Adyen's own minor units in the adapter, as SpreeStripe::Units does for Stripe (6.0-money-correctness.md, 2026-10-09). Gateways that have not opted in still receive hundredths, with a deprecation warning, until 6.1.
  • No new feature work in the standalone spree_stripe/spree_adyen repos — critical fixes only. New gateway capability lands in the monorepo port.
  • Don't rename the SpreeStripe/SpreeAdyen namespaces anywhere (docs, examples, seeds): STI columns depend on them (Key Decision 2).
  • Changes to the core payment-session contract (Spree::PaymentMethod session methods, Spree::PaymentSession, Spree::Payments::HandleWebhook, the v3 session/webhook endpoints) must be checked against both gateway implementations — after the port, monorepo CI does this; until then, coordinate with the external repos before merging.
  • A cart holds at most one open provider session per gateway (2026-09-30, V-3726; revised 2026-10-04). A gateway whose sessions can be paid independently cancels the owner's open sessions from create_payment_session before opening a new one, and implements cancel_payment_session, which a job also calls after placement for the sessions a buyer left behind. An intent the provider has already accepted is not canceled, and no second session is opened. The default cancel_payment_session leaves the session pending.
  • New payment gateways (e.g. spree_paypal_checkout) follow this plan's shape: own spree/providers/<provider> gem, existing name kept if published, lockstep version, exact spree_core pin, SDK as the gem's own dependency, and an entry in SPREE_PROVIDER_GEMS (spree/Rakefile) so the release builds and publishes it.
  • The spree meta gem must not gain a dependency on any gateway gem.
  • An upgrade step contributed by an optional gem must be marked optional: true in the manifest. The upgrade walk checks whether the step's task class is registered or its rake task is defined (Spree::Upgrade.available?) and skips an optional step whose gem isn't installed, instead of failing on it (added for the Stripe webhook-key backfill, and the pattern every future gateway gem uses). Like any step, it names a rake task or a task class, never both (decisions.md 2026-10-25).
  • Gateway configuration lives in payment-method preferences, never in new tables. The Stripe gem ships no migrations at all — a gateway that thinks it needs a table should first check whether single-store ownership has removed the reason.
  • Providers never decorate core models. A capability a provider needs from a core model goes through a core interface instead: gateway-derived risk codes through PaymentMethod#risk_codes_for(source) (asked by Payment at creation), provider-scoped gateway customers through GatewayCustomer.for_provider, provider identity through api_type and where(type:), and ad-hoc provider data through the metadata column directly — store_accessor sugar does not justify a decorator.

Resolved Questions

  • Webhook-key tables → preferences: YES (2026-08-09). The two tables held per-endpoint signing secrets in a many-to-many join, which only existed because a payment method could be shared across stores. With belongs_to :store there is one endpoint per gateway, so the secret is just preference :webhook_signing_secret, :password (plus webhook_endpoint_id). The gem now ships zero migrations and owns no tables. Note this is not an encryption upgrade: spree_payment_methods.preferences is a serialized YAML text column with no encryption at rest, whereas WebhookKey declared encrypts … deterministic: true. It is not a new exposure either — the Stripe secret key, a strictly more powerful credential, has always lived in that same column. Encrypting the preferences column is a separate, core-wide question. Existing secrets move via spree:upgrade:migrate_stripe_webhook_keys.

  • Stripe Tax: dropped (2026-08-09). Out of scope for the port; revisit as a TaxProvider under 6.0-tax-provider.md.

  • CI secrets: none needed (2026-08-09). The suite is fully VCR-backed and runs offline. Two hardening changes were made during the port: cassettes now default to record: :none (opt in with RECORD_VCR=1), because record-by-default turns any rename of a :vcr example into a live API call; and the before_record filter now scrubs whsec_ values from response bodies, which the request-side key filters never saw — two committed cassettes had real signing secrets in them and were redacted.

  • spree_paypal_checkout timing: a 6.0 patch release (2026-10-27). Same treatment as Stripe, in spree/providers/paypal; the design is in 6.0-paypal-payment-provider.md.

Open Questions

  • Wallet billing-name precedence: for a signed-in customer, core's Address#set_default_values fills the name before the Stripe billing name is applied, so the wallet name never wins. Defensible (saved name beats wallet-supplied), but it is currently incidental rather than chosen.

References

  • docs/plans/decisions.md — 2026-07-20 entry (this plan; amends 2026-07-15 "likely into spree/core")
  • docs/plans/6.0-multi-vendor-marketplace.md — Phase 3b (StripeConnect payout provider), OSS/Enterprise boundary
  • docs/plans/6.0-tax-provider.md — Stripe Tax open question
  • Source repos: spree/spree_stripe, spree/spree_adyen
  • Vendure payments extraction: vendurehq/community-plugins (v3.6.0 removal of packages/payments-plugin)
  • Medusa v2 provider packaging: medusajs/medusa → packages/modules/providers/payment-stripe (@medusajs/payment-stripe)