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.

Added the PayPal payment provider plan for Spree 6

Łukasz Adamczyk838386a8d4bf
diff --git a/docs/plans/6.0-payment-gateways-monorepo.md b/docs/plans/6.0-payment-gateways-monorepo.md
index cb3db96e82..d0171b9810 100644
--- a/docs/plans/6.0-payment-gateways-monorepo.md
+++ b/docs/plans/6.0-payment-gateways-monorepo.md
@@ -4,7 +4,7 @@
**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-08-10
+**Last updated:** 2026-10-28
## Summary
@@ -269,15 +269,18 @@ admin" with no conditional-SDK logic. Webhook endpoints are the core v3 ones
is not canceled, and no second session is opened. The default
`cancel_payment_session` leaves the session pending.
- New payment gateways (e.g. `spree_paypal_checkout`) follow this plan's
- shape: own `spree/<provider>` gem, existing name kept if published, lockstep
- version, exact `spree` pin, SDK as the gem's own dependency.
+ 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 runner resolves steps through
- `Rake::Task[…]`, which raises when the gem isn't installed; the flag makes it
- skip with a note instead (added for the Stripe webhook-key backfill, and the
- pattern every future gateway gem uses). `invoke` returns whether the step
- ran, so a skipped step doesn't print a completion line.
+ `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
@@ -315,11 +318,12 @@ admin" with no conditional-SDK logic. Webhook endpoints are the core v3 ones
bodies**, which the request-side key filters never saw — two committed
cassettes had real signing secrets in them and were redacted.
-## Open Questions
+- **`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
-- **`spree_paypal_checkout` timing**: same treatment, but in-scope for 6.0 or
- after? Not blocking this plan.
- **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
diff --git a/docs/plans/6.0-paypal-payment-provider.md b/docs/plans/6.0-paypal-payment-provider.md
new file mode 100644
index 0000000000..2dbe7242c1
--- /dev/null
+++ b/docs/plans/6.0-paypal-payment-provider.md
@@ -0,0 +1,654 @@
+# PayPal Payment Provider
+
+**Status:** Draft — design finalized 2026-10-27, nothing built
+**Target:** Spree 6.0 (next patch release)
+**Depends on:** `6.0-payment-gateways-monorepo.md` (the provider gem shape, Stripe as the worked example), payment sessions in core, `6.0-money-correctness.md` (`accepts_money_amounts`), `6.0-json-preferences.md` (secret preferences), `6.0-maintenance-tasks.md` (upgrade steps)
+**Author:** Łukasz Adamczyk
+**Last updated:** 2026-10-28
+**Tracking:** Linear V-3764 · GitHub —
+
+## Summary
+
+Bring PayPal to Spree 6 as an optional provider gem at `spree/providers/paypal`,
+publishing the existing gem name `spree_paypal_checkout` and released with
+Spree, because 6.0.0 is out and the standalone
+[`spree/spree_paypal_checkout`](https://github.com/spree/spree_paypal_checkout)
+gem (0.7.1, built for 5.4–5.6) does not run on it, so a merchant taking PayPal
+on 5.x cannot upgrade. This is a rewrite of that gem's payment-session half on
+the 6.0 contract, not a copy: it predates the cart/order split, the single
+`metadata` column, money amounts and `settle_payment!`, and several of its
+behaviours are wrong under 6.0. The first release covers what PayPal's own
+buttons offer (PayPal, Pay Later, Venmo, and a card typed into PayPal's window
+by a buyer without an account) and honors the store's capture setting. The
+Next.js storefront and `spree add paypal` already exist; the classic Rails
+storefront, legacy admin and Storefront API v2 code stays behind, and the old
+repository becomes a 5.x maintenance branch.
+
+## Key Decisions (do not deviate without discussion)
+
+1. **Ships in the next 6.0 patch release** (decided 2026-10-27). The gem
+ changes no core behaviour (core only gains its two upgrade-manifest
+ entries), so it can ride a patch release, and PayPal merchants
+ cannot upgrade to 6.0 until it exists. Waiting for 6.1 was rejected for
+ that reason.
+2. **Same shape as Stripe.** Directory `spree/providers/paypal`, gem
+ `spree_paypal_checkout`, `s.version = Spree.version`, exact pin on
+ `spree_core`, hard dependency on PayPal's official `paypal-server-sdk`
+ pinned `~> 2.4` (decided 2026-10-28; 2.4.0 is the latest, from
+ 2026-08-21; the 5.x gem was stuck on `~> 1.1`), Rails engine registering the gateway in a late
+ `after_initialize`. The `spree` meta gem does not depend on it; the
+ `spree_admin` dependency is dropped.
+3. **Every stored class name is kept**: `SpreePaypalCheckout::Gateway`,
+ `Spree::PaymentSessions::PaypalCheckout`,
+ `SpreePaypalCheckout::PaymentSources::Paypal`. These live in `type`
+ columns, so an upgrading installation keeps its rows. The wire name stays
+ `paypal_checkout` (already the `Spree::Gateway.api_type` example and the
+ storefront's mapping).
+4. **Only the payment-session path is ported, and core behaviour does not
+ change.** The gem implements the existing contract: `create_payment_session`,
+ `update_payment_session`, `complete_payment_session`,
+ `cancel_payment_session`, `parse_webhook_event`, the session's
+ `prepare_for_settlement!` / `payment_source_for_settlement` /
+ `apply_settlement_metadata`, and the money verbs. The only core file
+ touched is the 5.6 → 6.0 upgrade manifest, which gains two entries.
+5. **First release: PayPal's buttons only** (decided 2026-10-27). PayPal,
+ Pay Later, Venmo, and guest card payment inside PayPal's window, all
+ through one PayPal order flow and the storefront component that exists
+ today. Card fields on the store's own page and Apple Pay / Google Pay
+ through PayPal are deferred. Rejected for now because
+ each needs new storefront components, card source handling and 3-D Secure,
+ and PayPal's approval of the merchant for advanced card processing.
+ Stores that want those today get them from the Stripe provider.
+ The storefront enforces this scope with a list of allowed buttons
+ (decided 2026-10-28): PayPal's button component otherwise shows every
+ method the buyer is eligible for, which can include alternative payment
+ methods (iDEAL, BLIK, Przelewy24 and the like) that send the buyer to
+ their bank and need the approval backup this release leaves out (Key
+ Decision 12). Hiding methods with `disable-funding` was rejected because
+ its list goes stale whenever PayPal adds a method.
+6. **The store's capture setting is honored** (decided 2026-10-27). A method
+ that captures at checkout creates PayPal orders with the `CAPTURE` intent;
+ one set to capture on dispatch or manually uses `AUTHORIZE`, and the money
+ is taken when Spree captures the payment. **Accepted trade-off:** PayPal
+ honors an authorization for 3 days and allows capture until day 29: a
+ capture on days 4–29 may be declined, and one after day 29 always is.
+ The failure is reported with PayPal's reason, never swallowed.
+ Authorizations are not renewed (decided 2026-10-28), the same as Stripe,
+ whose card holds expire and cannot be renewed at all. PayPal's one-time
+ reauthorization (days 4–29, a fresh 3-day guarantee, a new authorization
+ id, and it can itself be declined) is left to a later release if
+ merchants who ship after day 3 need it. Always
+ capturing at checkout was rejected because it charges a store's buyers
+ against the store's own setting.
+7. **A payment's `response_code` is always the PayPal order id.** Core links
+ a session to its payment through `response_code = external_id`, and
+ `handle_response` overwrites `response_code` with whatever authorization a
+ gateway call returns. So every gateway call returns the PayPal order id.
+ The capture and authorization ids PayPal issues are recorded in the
+ payment's `metadata` at settlement, and read from the order
+ (`GET /v2/checkout/orders/:id`) whenever a refund, void or capture needs
+ them. The 5.x gem stored the capture id instead, which breaks the
+ session-to-payment link in 6.0.
+8. **Payments taken before the upgrade are rewritten by an upgrade task**
+ (decided 2026-10-27). An optional upgrade step gives each old PayPal
+ payment the 6.0 shape: the PayPal order id becomes `response_code`, and
+ the old capture id moves to `metadata['paypal_capture_id']`, so runtime
+ code has one path. **Accepted trade-off:** this changes historical
+ payment rows, and payments from the old non-session flow can only be
+ matched to their PayPal order through `spree_paypal_checkout_orders`, so
+ the step must run before that table is dropped. A payment the step cannot
+ match is left as it was, counted in the run's record and logged by
+ payment id; refunding it
+ fails with PayPal's own "not found" reason, and the merchant refunds it in
+ PayPal. Accepting both shapes at refund time was rejected: it keeps a
+ second code path forever and costs a wasted PayPal call per old refund.
+9. **No tables.** The `SpreePaypalCheckout::Order` model goes with the
+ legacy flow. Its `spree_paypal_checkout_orders` table is left in place
+ for the payment upgrade step (Key Decision 8), and the merchant drops it
+ afterwards, as the upgrade guide says. Configuration lives in payment-method preferences;
+ ad-hoc PayPal data lives in `metadata`. The install generator stays as a
+ no-op, as Stripe's does.
+10. **Webhooks register themselves.** On create, and when the credentials
+ change, a job finds or creates the PayPal webhook for this payment
+ method's URL with exactly the events the gem handles, and stores its id
+ in an internal `webhook_id` preference. A webhook it finds for that URL
+ has its event list replaced with the gem's: upgraded stores created one
+ by hand under the 5.x guide, subscribed to other events. One already
+ subscribed to exactly those events is kept as it is, since PayPal refuses
+ an update that changes nothing (found in the sandbox, 2026-10-30). The operator types a client id
+ and secret and nothing else. Every webhook is verified against PayPal's
+ signature-verification API with that id; there is no development or test
+ bypass (the 5.x gem skipped verification in development and test
+ whenever no webhook id was set).
+11. **The server is the only thing that moves money.** A PayPal order is
+ inert until the backend captures or authorizes it, so canceling a session
+ that never reached Complete is local (no PayPal call), and a session
+ that is not open is never captured or authorized.
+12. **The buyer's approval is not acted on by webhook** (decided
+ 2026-10-28). PayPal takes money in two steps: the buyer approves in
+ PayPal's window, then the store's server captures or authorizes. The
+ storefront calls the server as soon as the buyer approves, as PayPal's
+ own button guide does, so the gem does not subscribe to
+ `CHECKOUT.ORDER.APPROVED` and webhooks only report money that has moved,
+ the same as Stripe's. Every PayPal order passes through approval, but
+ PayPal's docs recommend the approval webhook as a capture backup for
+ payment methods that send the buyer away to their bank or bank app
+ (BLIK, Przelewy24, Trustly and the like); its button guide does not
+ use it.
+ **Accepted trade-off:** a buyer who closes the store's tab in the second
+ after approving, or never returns from the PayPal or Venmo app on
+ mobile, gets no order. No money is taken, and PayPal reverses the
+ approval. Capturing from the gem's own job, queued inside
+ `parse_webhook_event`, was rejected because parsing an event must not
+ act on it. When a backup is needed (bank methods, or orders lost on
+ mobile), it is a fifth webhook outcome in core, `:approved`, which
+ `HandleWebhook` handles by running the storefront's completion workflow
+ (`Spree.payment_session_complete_workflow`) and then placing the order.
+13. **Money is decimal strings in PayPal's own precision.** The gateway sets
+ `accepts_money_amounts = true`. A `SpreePaypalCheckout::Amounts` module
+ (the twin of `SpreeStripe::Units`) formats an amount for PayPal: the ISO
+ exponent, except that PayPal takes HUF, JPY and TWD only in whole units.
+ An amount PayPal would refuse raises, naming the rule, instead of being
+ rounded to a sum Spree did not record. PayPal is not offered
+ (`available_for_order?` is false) for a currency it does not support.
+14. **Every money-moving request carries a `PayPal-Request-Id`** derived from
+ the Spree record (the session id, the action and the attempt number, or
+ the refund id), so a retry or a double click can never charge or refund
+ twice. The attempt number only moves after a recoverable decline (see
+ Payment sessions), so a buyer's second try is a new request rather than
+ an answer replayed from the first. The SDK's own defaults protect
+ nothing (a 60-second timeout, no retries, and only GET and PUT retried
+ even when retries are on), so the gem configures the client explicitly
+ (decided 2026-10-28): a 30-second timeout, `max_retries: 2` with the
+ SDK's exponential backoff on its default statuses (408, 413, 429, 500,
+ 502, 503, 504, 521, 522, 524), and `retry_methods` of GET, POST and
+ PATCH. Retrying a POST is only safe because of this header; retrying a
+ PATCH is safe because the gem only replaces the amount and the whole
+ purchase unit, never adds or removes items one by one. **Accepted trade-off:** the slowest call is
+ about 95 seconds (three 30-second attempts and the waits between them),
+ within Key Decision 15's outage trade-off.
+ The calls the SDK does not cover, webhook signature verification and
+ webhook registration under `/v1/notifications`, go through a small client
+ on Ruby's `Net::HTTP`, adding no dependency, with explicit open and read
+ timeouts of a few seconds. It takes its access token from the SDK's own
+ OAuth client (`OAuthAuthorizationController#request_token`), so token
+ handling lives in one place. None
+ of them moves money; a failed verification is redelivered by PayPal and
+ a failed registration is retried by its job.
+15. **No circuit breaker, the same as Stripe** (decided 2026-10-27). The gem
+ protects its calls to PayPal exactly as Stripe's gem protects its calls
+ to Stripe: timeouts and retries (Key Decision 14), nothing more. A
+ breaker in one gateway would make PayPal and Stripe behave differently in
+ an outage. **Accepted trade-off:** this departs from the project rule
+ that calls to third-party services use a circuit breaker, and during a
+ PayPal outage each checkout waits for the timeout before it fails. If
+ outage protection is wanted, it goes into core for every gateway, never
+ into one gem.
+16. **The buyer ships where Spree says.** Orders are created with
+ `shipping_preference: SET_PROVIDED_ADDRESS` when the cart has a shipping
+ address and `NO_SHIPPING` when it needs none, so the buyer cannot pick a
+ different address inside PayPal than the one Spree charged shipping and
+ tax for. The preference and the store's `brand_name` go in the order's
+ `application_context` (decided 2026-10-28), because the order is created
+ with the session, before the buyer picks a button, and PayPal's newer
+ place for them (`payment_source.<paypal|venmo>.experience_context`)
+ needs the payment method up front. **Accepted trade-off:** PayPal marks
+ `application_context` deprecated, with no removal date. SDK 2.4.0 still
+ sends it, and PayPal accepts orders that carry it (every sandbox checkout
+ did); whether PayPal's window still locks the address and shows the brand
+ name was not checked (skipped, 2026-10-30). Creating the order on button click with
+ the per-method context was rejected for now: it needs a bigger
+ storefront and session-flow change, and the Card button's shape is
+ unconfirmed. It is the natural move when card fields arrive, which need
+ the per-method style anyway.
+17. **The itemized breakdown is sent only when it adds up.** Items and the
+ amount breakdown are included only when they reconcile exactly to the
+ amount being charged; otherwise the order carries the amount alone.
+ PayPal refuses an order whose breakdown does not add up, and 6.0 carts
+ have fees, line-level discounts, included tax and store credit that the
+ 5.x presenter did not account for.
+18. **No request or response bodies in logs.** The 5.x client logged
+ request bodies, which carry buyer names, emails and addresses, and
+ response headers. The 6.0 client (the SDK's logging configuration with
+ `log_body` and `log_headers` off, their defaults)
+ logs status lines only, at a level set by `PAYPAL_LOG_LEVEL`.
+
+## Design Details
+
+### Monorepo layout
+
+```
+spree/providers/paypal/
+ spree_paypal_checkout.gemspec
+ lib/spree_paypal_checkout.rb
+ lib/spree_paypal_checkout/engine.rb
+ lib/spree_paypal_checkout/factories.rb # + testing_support/factories/
+ lib/generators/spree_paypal_checkout/install/ # no-op, like Stripe's
+ lib/tasks/ # register_paypal_webhooks upgrade step
+ app/models/spree_paypal_checkout/gateway.rb # credentials, money verbs, client
+ app/models/spree_paypal_checkout/gateway/payment_sessions.rb
+ app/models/spree_paypal_checkout/gateway/webhooks.rb
+ app/models/spree_paypal_checkout/amounts.rb
+ app/models/spree_paypal_checkout/payment_sources/paypal.rb
+ app/models/spree/payment_sessions/paypal_checkout.rb
+ app/presenters/spree_paypal_checkout/order_presenter.rb
+ app/models/spree_paypal_checkout/notifications_client.rb # Net::HTTP calls the SDK lacks
+ app/services/spree_paypal_checkout/register_webhook.rb
+ app/jobs/spree_paypal_checkout/register_webhook_job.rb
+ app/maintenance_tasks/spree_paypal_checkout/maintenance_tasks/migrate_payments.rb
+ config/locales/en.yml
+ spec/ (VCR cassettes under spec/vcr, record: :none by default)
+```
+
+### Gateway
+
+`SpreePaypalCheckout::Gateway < Spree::Gateway`:
+
+- Preferences: `client_id` (`:password`), `client_secret` (`:password`),
+ `test_mode` (boolean, default true; the credentials do not say which
+ environment they belong to), `webhook_id` (`internal: true`, written by
+ registration). The 5.x `webhook_secret` preference, which held a webhook
+ id despite its name, is not declared; webhook registration replaces it.
+- Validation on save asks PayPal for an access token with the credentials.
+ A refusal names what to fix ("PayPal sandbox rejected this client id and
+ secret — check that Test mode matches the credentials"), the way Stripe's
+ `validate_secret_key` does. Skipped in the test environment.
+- `logo_url` / `docs_url` for the dashboard gallery card.
+- `gateway_dashboard_payment_url` (decided 2026-10-28) links to PayPal's
+ activity page for the payment's transaction: `paypal_capture_id` from
+ the payment's `metadata`, otherwise `paypal_authorization_id` (whose
+ page lists its captures), on the sandbox site in test mode. No id means
+ no link. PayPal's activity page lists transactions, so the order id kept
+ in `response_code` cannot build it. The page,
+ `https://www.sandbox.paypal.com/activity/payment/<id>` in test mode, opens
+ for the merchant signed in with the sandbox Business account (confirmed in
+ the sandbox, 2026-10-30); the buyer's own account sees another id for the
+ same payment. 5.x had no link; Stripe's gem has one.
+- `session_required?` true. `payment_profiles_supported?` false: there are
+ no saved PayPal accounts in this release (Open Questions), so core calls
+ `credit(amount, order_id, options)` and never `create_profile`.
+- `authorize` / `purchase`: called by core when a session-created payment
+ moves on. The order is already captured or authorized by then, so they
+ read it back, as Stripe's do.
+- `capture(amount, order_id, gateway_options)`: captures the order's authorization (partial
+ amounts allowed, `final_capture: true`); for an order whose capture has
+ completed, succeeds without a call. An expired authorization raises with
+ PayPal's reason. Returns the order id. **A capture PayPal leaves `PENDING`
+ is not reported as taken** (decided 2026-10-28): `capture` raises a
+ `GatewayError` naming PayPal's pending reason ("PayPal is holding this
+ capture: … It completes when PayPal releases it"), so the payment stays
+ pending and, on dispatch, the dispatch is refused. The
+ `PAYMENT.CAPTURE.COMPLETED` webhook later completes the waiting payment
+ through `HandleWebhook`, and dispatching again then succeeds without a
+ PayPal call. **Accepted trade-off:** dispatch waits on PayPal, and staff
+ see a failure for a capture that will probably succeed. Two details of
+ that: dispatch buys the shipping label and tells the fulfillment provider
+ the parcel shipped before the capture is refused, and those outside
+ effects are not rolled back with it; and a capture staff start from the
+ dashboard runs outside dispatch's transaction, so the payment is left
+ `processing` rather than `pending` until the webhook completes it. Reporting it as
+ captured was rejected because a later denial would leave Spree showing
+ paid, with the goods shipped, for money that never arrived; a `pending`
+ capture result in core is the clean fix and is outside this release (Key
+ Decision 4).
+- `credit(amount, order_id, options)`: finds the capture on the order and
+ refunds it. Returns the refund id, which is stored on the `Spree::Refund`,
+ not the payment.
+- `void(order_id, gateway_options)`: voids the authorization when there is
+ one; an uncaptured `CAPTURE` order has nothing to void and succeeds
+ without a call. A capture PayPal still holds as `PENDING` raises a
+ `GatewayError` ("PayPal is still holding a capture on this payment;
+ refund it once it completes"): the money may yet arrive, and a payment
+ voided in Spree could not be revived by the `PAYMENT.CAPTURE.COMPLETED`
+ webhook, since `confirm!` does nothing on a void payment. So canceling
+ an order with a pending capture stops with that message.
+- `cancel(order_id, payment, refund:)`: same as Stripe. A completed payment
+ is refunded through `Spree.refund_create_workflow` unless `refund: false`;
+ anything else is voided.
+- PayPal SDK errors are wrapped as `Spree::Core::GatewayError` carrying
+ PayPal's own issue code and description (`ORDER_NOT_APPROVED`,
+ `INSTRUMENT_DECLINED`, `AUTHORIZATION_EXPIRED`, …) rather than the SDK's
+ generic message. A timeout or connection failure on a money-moving call
+ raises `Spree::Core::AmbiguousGatewayError`, because its outcome is
+ unknown. `cancel_payment_session` follows core's stricter rule, as
+ Stripe's does: only PayPal's refusal is a `GatewayError`; a timeout, a
+ rate limit, a server error or rejected credentials is raised as the SDK's
+ own error, so the unused-session job retries instead of counting a
+ payable session as handled.
+
+### Payment sessions
+
+**Create.** Refuses a zero amount and a cart with a completed PayPal session.
+Replaces the cart's open PayPal sessions first (the gateways plan's rule: one
+open session per gateway per cart). Creates a PayPal order through
+`OrderPresenter`:
+
+- intent `CAPTURE` when the method captures at checkout, otherwise
+ `AUTHORIZE` (Key Decision 6);
+- `custom_id` set to the cart's prefixed id for reconciliation, never
+ `invoice_id`, which PayPal requires to be unique and would make a replaced
+ session fail;
+- the shipping preference from Key Decision 16, and the store name as
+ `brand_name`, both in `application_context`.
+
+Stores the PayPal order id as `external_id` and puts what the storefront
+needs in `external_data`: `client_id` (public; the JS SDK needs it, and
+taking it from the session means it always matches the credentials that
+created the order) and `intent` (the JS SDK must load with the matching
+intent, or the buttons refuse the order).
+
+**Update.** When the amount changes, patches the PayPal order before
+updating the session (allowed while the order is created or approved). It
+replaces the whole purchase unit, because Key Decision 17 can add or drop
+the items and breakdown between updates and PayPal patches items only by
+adding or removing them one at a time. The 5.x gem updated only the local amount, so PayPal captured
+the old total.
+
+**Complete.** Refuses a session that is not open. Reads the PayPal order and
+checks, before any money moves, that its amount and currency equal the
+session's; a mismatch fails the session without capturing. Then it captures
+the PayPal order (`CAPTURE`) or authorizes it (`AUTHORIZE`) with a
+`PayPal-Request-Id` and merges the result into `external_data` (keeping
+`client_id` and `intent`). Once money has moved the session is never failed:
+a captured amount that still differs is settled and reported, because
+failing it would let the `PAYMENT.CAPTURE.COMPLETED` webhook place the order
+while the storefront opened a second session and charged again. Then it calls
+`settle_payment!(captured: …)`: `true` for a `COMPLETED` capture, `false` for
+an authorization or a `PENDING` capture (eCheck, PayPal review), which the
+later `PAYMENT.CAPTURE.COMPLETED` webhook completes. As core's contract
+requires, it leaves the session completed once settled, or failed when
+PayPal declines. It never completes the cart; the storefront's
+cart-complete call or `HandleWebhook` does that.
+
+**A declined funding source is retried in PayPal's window** (decided
+2026-10-28). When the capture or authorization fails with
+`INSTRUMENT_DECLINED`, the buyer's chosen card or account was refused and
+PayPal lets them pick another. Complete then leaves the session open,
+increments an attempt counter in the session's `external_data`, and raises
+a `GatewayError` naming `INSTRUMENT_DECLINED`. Every other decline fails the
+session. The storefront cannot rely on the code: core turns the error into
+a general failure and carries the code only in the message text. So it
+reads the session after a failed Complete: still open means
+`actions.restart()`, the buyer chooses again, and the next Complete is a
+new request (Key Decision 14); failed means a new session. The gem owns the
+`external_data` keys it writes (`client_id`, `intent`, the attempt counter,
+the PayPal result) and ignores values a client sends for them through the
+session create and update endpoints. This is
+PayPal's documented handling and matches Stripe, whose declined card leaves
+the payment usable for another try. PayPal's guides do not say outright
+that a restart keeps the same PayPal order; the sandbox confirmed it
+(2026-10-30): after a forced `INSTRUMENT_DECLINED` the buyer chose again in
+PayPal's window and the same order was captured, once. Failing on every decline was rejected
+because the buyer would go through PayPal from the start for a card PayPal
+itself offers to swap.
+
+**Cancel.** A session that never reached Complete (no attempt and no PayPal
+result in `external_data`) is canceled locally, with no PayPal call (Key
+Decision 11). Otherwise it reads the order, because a capture that timed
+out may have gone through: nothing moved, cancel locally; an
+authorization, void it and cancel; captured, raise a `GatewayError` so the
+unused-session job reports a paid session instead of hiding it. Errors
+follow core's cancel rule (see Gateway).
+
+**Settlement hooks on `Spree::PaymentSessions::PaypalCheckout`.**
+`prepare_for_settlement!` fetches the PayPal order (outside the lock).
+`payment_source_for_settlement` builds the source from the order's
+`payment_source`: a PayPal or Venmo wallet becomes
+`SpreePaypalCheckout::PaymentSources::Paypal`, with email, name, account id,
+verification status and which wallet in `metadata`. A guest card paid in
+PayPal's window is recorded on the same source, with `card` as its wallet
+and the brand and last four digits PayPal reports in `metadata`, if it
+reports them. In the sandbox PayPal reported a guest card as a `paypal`
+source with `account_status: UNVERIFIED` and no card details, so it is
+recorded as an unverified PayPal wallet (accepted, 2026-10-30). It is
+not a `Spree::CreditCard`, as Stripe's cards are (decided 2026-10-28):
+PayPal issues no reusable card id without vaulting, so the record would
+need an expiry and name PayPal may not report, and it would appear among
+the customer's saved cards, where choosing it fails. A kind the gem does not model leaves the payment without a
+source instead of raising, as 5.x did for anything that was not a PayPal
+wallet. `apply_settlement_metadata` records `paypal_capture_id` or
+`paypal_authorization_id` on the payment. A capture taken later, on
+dispatch or from the dashboard, records its `paypal_capture_id` beside the
+authorization id, so the dashboard link opens the capture (found in the
+sandbox, 2026-10-30).
+
+### Webhooks
+
+Handled events, and nothing else (registration subscribes to exactly this
+list):
+
+| PayPal event | Result |
+|---|---|
+| `PAYMENT.CAPTURE.COMPLETED` | `:captured` |
+| `PAYMENT.CAPTURE.PENDING` | `:authorized` (the payment pends) |
+| `PAYMENT.AUTHORIZATION.CREATED` | `:authorized` |
+| `PAYMENT.CAPTURE.DENIED`, `PAYMENT.CAPTURE.DECLINED` | `:failed` |
+
+Every event is handled in the background: core's endpoint verifies it,
+answers PayPal at once, and queues `Spree::Payments::HandleWebhookJob` to run
+30 seconds later. `parse_webhook_event` only translates, as Stripe's does.
+
+**Accepted trade-off: `PAYMENT.CAPTURE.DECLINED` stays subscribed,
+unconfirmed** (2026-10-30). If PayPal sends it for the `INSTRUMENT_DECLINED`
+decline a buyer is retrying, its `:failed` would close the session left open
+for them once they take longer than the 30-second delay. The sandbox cannot
+settle it: its declines are simulated with `PayPal-Mock-Response`, which
+sent no event, and a real one cannot be caused. Complete already reports
+every decline as it happens, so if production shows that event, the gem
+stops subscribing to it and keeps only `PAYMENT.CAPTURE.DENIED`.
+
+**Known gap: a pending capture that PayPal later denies.** `:failed` only
+fails a session that is still pending or processing
+(`PaymentSessionTransitions#fail`). After a `PENDING` capture the session is
+already completed and the order placed, with the payment pending, so a
+later `PAYMENT.CAPTURE.DENIED` changes nothing in Spree: the order stays
+placed with a pending payment that will never complete. The merchant sees
+the pending payment in the dashboard and the denial in PayPal. Failing the
+payment of a completed session is a core change (`HandleWebhook`), outside
+this release by Key Decision 4.
+
+The 5.x gem mapped `CHECKOUT.ORDER.APPROVED` to `:authorized`, which in 6.0
+would place the order with no money taken; the event is no longer
+subscribed to (Key Decision 12). It also mapped refunds and
+reversals to `:canceled`, which cannot cancel a completed session and
+records no refund. Both are gone. Refunds and disputes made in the PayPal
+dashboard are not synced, as with Stripe.
+
+Signature verification posts the headers, body and `webhook_id` to
+`/v1/notifications/verify-webhook-signature`, with timeouts. A missing id, a
+failed check, a malformed body or an unreachable PayPal all raise
+`WebhookSignatureError`, so PayPal delivers again later. The event is matched
+to a session by PayPal order id (for capture and authorization events,
+`related_ids.order_id`), scoped to this payment method.
+
+### Order presenter
+
+Builds one purchase unit from the cart:
+
+- the amount, in PayPal precision;
+- items: name cut to 127 characters, SKU, unit price, quantity,
+ `DIGITAL_GOODS` or `PHYSICAL_GOODS`;
+- the breakdown: `item_total`, `shipping`, `tax_total`, `handling` for fees,
+ and `discount` for promotions and store credit;
+- the shipping address.
+
+Key Decision 17 decides whether items and breakdown are sent. Built with the
+SDK's request models.
+
+### Upgrading from the 5.x gem
+
+| 5.x | 6.0 |
+|---|---|
+| Payments whose `response_code` is a capture id | Rewritten by the `migrate_paypal_payments` upgrade step (Key Decision 8) |
+| `webhook_secret` preference (a webhook id) | The `register_paypal_webhooks` upgrade step finds or creates each method's webhook, replaces the event list of one created by hand under the 5.x guide (keeping one already subscribed to the gem's events), and records its id |
+| `spree_paypal_checkout_orders` table, `SpreePaypalCheckout::Order` | Model gone. The table is left in place; the upgrade guide says it can be dropped after the payment step has run |
+| `use_legacy_api` configuration, Storefront API v2 `paypal_orders` routes | Gone. Apps still on that flow must move to payment sessions before upgrading |
+| `payment_profiles_supported?` true, admin "saved PayPal accounts" picker | False, picker gone. In 5.x nothing was ever saved at PayPal, and charging a picked account failed |
+| `Spree::PaymentMethod.paypal_checkout`, `Store#paypal_checkout_gateway` decorators | Gone; use `where(type:)` (providers never decorate core models) |
+| Rails storefront assets, importmap, ERB partials, admin views | Gone |
+| `NEXT_PUBLIC_PAYPAL_CLIENT_ID` in the storefront | Still read as a fallback; the session's `client_id` is preferred |
+
+Both upgrade steps are added to the 5.6 → 6.0 manifest in the patch
+release that ships the gem, as `migrate_paypal_payments` and
+`register_paypal_webhooks`. Following the 2026-10-25 decision (a step is a
+rake task or a task class, never both):
+
+- `migrate_paypal_payments` walks payment rows, so it names a `task_class`,
+ `SpreePaypalCheckout::MaintenanceTasks::MigratePayments`, a
+ `Spree::MaintenanceTask` with a collection (progress, resume, dry run) and
+ no rake twin. It tallies converted and unmatched payments in the run's
+ record, like core's `CaptureMethods` step.
+- `register_paypal_webhooks` is one pass over a handful of payment methods,
+ so it names a rake `task`, `spree:upgrade:register_paypal_webhooks`, run
+ through core's shared `UpgradeStep` runner, with no class of its own.
+
+Both are `optional: true`, so an installation without the gem skips them,
+and both are safe to run again.
+
+That manifest is the right home even though 6.0.0 has shipped: the stores
+that need these steps are leaving 5.x, cannot be on 6.0 before the gem
+exists, and walk exactly this manifest when they upgrade. Upgrades are
+tracked per minor release, so there is no manifest for a patch release, and
+the 6.0 → 6.1 one would never reach a store moving to 6.0. **Accepted
+trade-off:** a store that upgraded to 6.0.0 without the gem and kept old
+PayPal payments is already recorded as upgraded to 6.0, so the dashboard's
+upgrade page will not list the new steps. The command line still runs them
+(`spree upgrade` walks every manifest each time, and `--step <id>` runs one),
+and the upgrade guide tells those stores to.
+
+### Storefront and dashboard
+
+The dashboard needs nothing: the payment method form is generated from the
+preference schema, `webhook_id` is hidden as internal, and the gallery card
+reads `logo_url` / `docs_url`. The Next.js storefront already renders PayPal
+buttons from a session. Small changes land in the `spree/storefront`
+repository:
+
+- read the PayPal order id from the session's `external_id`; today it reads
+ `external_data.id` (`PaymentSection.tsx`), which the 6.0 gem no longer
+ writes;
+- read `client_id` and `intent` from the session's `external_data`, with
+ the `NEXT_PUBLIC_PAYPAL_CLIENT_ID` environment variable only as a
+ fallback. The component currently renders nothing unless that variable is
+ set (`isPayPalConfigured`), so that check goes;
+- load the JS SDK with that intent instead of the hard-coded `capture`;
+- when completion fails, read the session: still open means
+ `actions.restart()` from `onApprove`, so the buyer picks another funding
+ source; failed means show the message and start a new session;
+- render one button per allowed method instead of PayPal's all-eligible
+ component: `PayPalButtons` with `fundingSource` set to each of `paypal`,
+ `paylater`, `venmo` and `card`, each shown only when PayPal says the
+ buyer is eligible for it. The list is a single constant in the component.
+- load the JS SDK with `enable-funding=paylater,venmo`, without which PayPal
+ hides Pay Later outside the US. Checked in the sandbox (2026-10-30) with
+ `buyer-country` US, GB, DE, FR and AU and both intents: PayPal and Card
+ show everywhere, Pay Later outside the US only with it, and intent makes
+ no difference. Venmo, which PayPal offers mostly on phones, did not show
+ on desktop; it is asked for on PayPal's own guidance, unconfirmed. Which
+ buttons a merchant offers is not a setting in this release.
+
+### Docs and catalog
+
+- `docs/integrations/payments/paypal.mdx`: drop the manual webhook steps and
+ the Webhook ID field, including its promise that webhooks finish orders
+ when a shopper closes the browser mid-checkout (Key Decision 12 gives
+ that up); document the capture settings, including the 3-day
+ and 29-day authorization limits; document the storefront change,
+ including that a storefront built on the API must show only the four
+ supported buttons.
+- The 5.6 → 6.0 upgrade guide: a PayPal section (the table above), with the
+ two upgrade steps and the order to drop the old table in, plus a note for
+ stores that upgraded to 6.0 before installing the gem: run both steps by
+ name (`spree upgrade --step migrate_paypal_payments`, then
+ `register_paypal_webhooks`), shown with the Spree CLI / Without CLI tabs.
+- `packages/cli/src/extensions.json`: mark `paypal_checkout` as
+ `"release": "spree"`, so `spree add paypal` pins it to the project's Spree
+ version instead of resolving to 0.7.1.
+
+## Migration Path
+
+1. Scaffold `spree/providers/paypal` from Stripe's gemspec, engine, spec
+ helper and VCR setup. Wire it into `tests.yml` (both install loops and
+ both providers shard entries); `scripts/test/rspec` finds provider
+ folders on its own.
+2. Gateway, amounts, presenter and payment sessions, with
+ sandbox VCR cassettes recorded by the author (credentials and tokens
+ redacted in request headers and response bodies).
+3. Webhooks: verification and the registration job.
+4. The two upgrade steps (a row-walking task class and a rake task) and
+ their entries in the 5.6 → 6.0 manifest.
+5. Docs, upgrade guide, CLI catalog entry. No dashboard E2E test, the same
+ as Stripe (decided 2026-10-28): the dashboard's test backend
+ (`spree/api`'s test app) loads no provider gem, and PayPal's payment
+ method form is the generic one the existing payment-method tests cover.
+ **Accepted trade-off:** this departs from the rule that a change visible
+ in the dashboard ships with an E2E test; the gem's own specs cover it.
+6. Storefront change in `spree/storefront` (client id, intent, allowed
+ buttons).
+7. Release with the next 6.0 patch. Add the gem to `SPREE_PROVIDER_GEMS` in
+ `spree/Rakefile` in this step, not earlier: without it the release
+ neither builds nor publishes the gem, and once it is listed the next
+ `v6.0.x` tag publishes it whether or not it is ready (merging alone
+ publishes nothing). Before the tag, an owner of
+ `spree_paypal_checkout` on RubyGems adds this repository's release
+ workflow as a trusted publisher, since `release.yml` publishes without a
+ stored key; otherwise the release fails on this gem after publishing the
+ rest. The starter Gemfile lists the gem.
+ `spree/spree_paypal_checkout` gets a README banner pointing here and a
+ `5-x` branch for critical fixes.
+
+## Constraints on Current Work
+
+- No new feature work in the standalone `spree/spree_paypal_checkout`
+ repository; critical 5.x fixes only.
+- Don't rename `SpreePaypalCheckout` or the session and source classes in
+ docs, examples or seeds; their names are stored data.
+- Never drop `spree_paypal_checkout_orders` before the
+ `migrate_paypal_payments` upgrade step has run: it is the only link from
+ a pre-session payment to its PayPal order.
+- Every PayPal call that moves money carries a `PayPal-Request-Id`. A new
+ call that skips it is a bug.
+- Don't give this gem network protection that Stripe's lacks, such as a
+ circuit breaker. Outage handling goes into core for every gateway, so
+ PayPal and Stripe keep behaving the same.
+- The storefront's allowed PayPal buttons stay PayPal, Pay Later, Venmo and
+ card. Adding an alternative payment method, or switching to PayPal's
+ all-eligible button component, needs the approval backup from Key
+ Decision 12 first.
+- A PayPal authorization is not capturable forever. Code that captures later
+ (on dispatch, by staff) must surface a failed capture rather than treating
+ the goods as paid.
+- Changes to the core payment-session contract are checked against PayPal
+ as well as Stripe once this lands: PayPal is the one gateway where the
+ server, not the browser, moves the money.
+
+## Open Questions
+
+- **Saved PayPal accounts (vault).** Left out of the first release at the
+ author's call (2026-10-27), but may be needed straight after it. 5.x never
+ had a working version. The design when it comes: orders ask PayPal to save
+ the account (`store_in_vault: ON_SUCCESS`), a setup session saves one
+ without a purchase (PayPal's setup tokens), `payment_profiles_supported?`
+ becomes true, and a `Spree::GatewayCustomer` holds the PayPal customer id.
+ It needs PayPal to enable vaulting on each merchant's account and a
+ "saved accounts" list in the storefront. Unblocked by the author deciding
+ it is needed.
+- **Partner onboarding ("Connect with PayPal").** Replaces typing
+ credentials with PayPal's partner referral flow, through the
+ `payment_method.form.paypal_checkout` dashboard slot. Unblocked by a PayPal
+ partner account for Spree.
+
+## References
+
+- `docs/plans/6.0-payment-gateways-monorepo.md`: the provider gem shape and
+ its constraints; this plan settles its "`spree_paypal_checkout` timing"
+ question
+- `docs/plans/decisions.md`: 2026-10-27 entry (this plan)
+- `docs/plans/6.0-money-correctness.md`: `accepts_money_amounts`
+- `docs/plans/6.0-json-preferences.md`: secret preferences
+- `docs/plans/6.0-cli-add-extensions.md`: `spree add paypal`
+- `docs/plans/6.0-admin-spa.md`: payment method editor slots
+- Source: `spree/spree_paypal_checkout` at 0.7.1 (`4f179a1`)
+- Reference implementation: `spree/providers/stripe`
+- PayPal: Orders v2, Payments v2, Webhooks (`verify-webhook-signature`),
+ currency codes and decimal support, authorization honor period
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index fed0466685..004ee0d7c8 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -1,3 +1,13 @@
+## 2026-10-27: PayPal becomes a provider gem in a 6.0 patch release
+
+**Context:** `spree_paypal_checkout` 0.7.1 does not run on 6.0, so merchants taking PayPal on 5.x cannot upgrade. Its payment-session code predates the cart/order split, `settle_payment!` and money amounts, and several of its behaviours are wrong under 6.0: it stores the capture id as the payment's reference, maps the buyer's approval to an authorization, which in 6.0 would place an order with no money taken, and logs buyer details.
+
+**Decision:** Port the payment-session half to `spree/providers/paypal`, keeping the gem name and every stored class name, with no core behaviour changes (core gains only two upgrade-manifest entries), and ship it in the next 6.0 patch release. The first release covers PayPal's own buttons (PayPal, Pay Later, Venmo, guest card in PayPal's window), which the storefront renders from a list of allowed buttons so alternative payment methods never appear (amended 2026-10-28), and honors the store's capture setting through PayPal's `AUTHORIZE` intent. A payment's `response_code` is always the PayPal order id; an optional upgrade step rewrites payments taken before the upgrade to that shape. Webhooks register themselves, are always verified, and only report money that has moved: as soon as the buyer approves, the storefront calls the server, which takes the money, as in PayPal's own button guide, so the buyer's approval is not acted on by webhook (amended 2026-10-28). Like Stripe's gem, it has no circuit breaker.
+
+**Consequences:** A PayPal authorization can only be captured for 29 days (honored for 3), and this release does not reauthorize, the same as Stripe, whose card holds cannot be renewed. A later capture that PayPal leaves pending is reported as not taken, so dispatch waits until PayPal releases it (amended 2026-10-28). `spree_paypal_checkout_orders` must not be dropped before the payment upgrade step runs. A buyer who closes the tab right after approving gets no order and is not charged; a core `:approved` webhook outcome is the planned fix once payment methods that send the buyer to their bank are added. During a PayPal outage each checkout waits for the timeout before failing, as with Stripe; outage handling, if added, goes into core for every gateway. Card fields and Apple Pay / Google Pay through PayPal are deferred; whether saved PayPal accounts are needed straight after the first release is still open.
+
+**Plan:** `6.0-paypal-payment-provider.md`. **Plan amended:** `6.0-payment-gateways-monorepo.md` (its PayPal timing question is resolved).
+
## 2026-10-27: Stripe transfer reversals on refund move to open source
**Context:** A refund on a seller's order wrote the reversal row, and the next payout to the seller's bank subtracted it, but the open-source Stripe provider never reversed the transfer. The seller's share stayed on their connected account while the marketplace had refunded the customer from its own balance, and nothing in the books said where that money now was. The 2026-07-15 decision kept the pullback in Enterprise.