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
Payment Session Webhooks infrastructure (#13776)
Damian Legawiec51f34ab241a3
diff --git a/docs/developer/core-concepts/payments.mdx b/docs/developer/core-concepts/payments.mdxindex daab708fdd..5e499ddef9 100644--- a/docs/developer/core-concepts/payments.mdx+++ b/docs/developer/core-concepts/payments.mdx@@ -182,7 +182,7 @@ Spree supports two payment flows depending on the payment method type:### Session-Based Flow (Stripe, Adyen, PayPal, etc.)-Modern payment gateways use a two-phase approach: first a **Payment Session** is created with the gateway, then after the customer completes payment on the frontend, Spree creates a **Payment** record to track the result. This ensures full PCI compliance, 3D Secure support, and compatibility with all payment method types.+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).```mermaidsequenceDiagram@@ -201,36 +201,89 @@ sequenceDiagramrect rgb(240, 255, 240)note right of Frontend: Phase 2: Customer PaysFrontend->>Payment Provider: Collect payment (using client_secret)- Note over Frontend,Payment Provider: 3DS challenge handled here if needed+ Note over Frontend,Payment Provider: 3DS / offsite redirect handled herePayment Provider-->>Frontend: Payment resultend- rect rgb(255, 245, 240)- note right of Frontend: Phase 3: Payment Created- alt Webhook-driven completion- Payment Provider->>Spree API: Webhook (payment succeeded)- Spree API->>Spree API: Create Payment (completed)- else Client-driven completion- Frontend->>Spree API: Complete Payment Session- Spree API->>Payment Provider: Verify result- Spree API->>Spree API: Create Payment (completed)+ rect rgb(255, 248, 240)+ note right of Frontend: Phase 3: Complete Payment Session+ Frontend->>Spree API: Complete Payment Session+ Spree API->>Payment Provider: Verify payment status+ Spree API->>Spree API: Create Payment record+ Spree API-->>Frontend: PaymentSession (completed)end- Spree API-->>Frontend: Order completed++ rect rgb(255, 240, 245)+ note right of Frontend: Phase 4: Complete Order+ Frontend->>Spree API: POST /carts/:id/complete+ Spree API->>Spree API: Validate & finalize order+ Spree API-->>Frontend: Completed orderend```<Steps><Step title="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 `client_secret` for the frontend SDK.++ <Info>+ The payment session should be created (or recreated) **after** the shipping method is selected, so the amount includes shipping costs. If the order total changes (e.g., customer selects a different shipping rate or applies a coupon), create a new payment session with the updated amount.+ </Info></Step><Step title="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, the gateway SDK automatically presents the challenge.+ 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.</Step>- <Step title="Payment is created and order is completed">- After the customer completes payment, the session is completed either via a webhook from the provider or by the frontend calling the complete endpoint. Spree creates a `Payment` record (in `completed` or `pending` state depending on auto-capture settings), creates the appropriate payment source (Credit Card, Klarna, etc.), and completes the order.+ <Step title="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.+ </Step>+ <Step title="Complete Order">+ The frontend calls `POST /carts/:id/complete` to finalize the order. Spree validates the order is ready (addresses, shipments, payment), advances through any remaining checkout states, and marks the order as complete.++ This separation ensures the same flow works for all payment types — inline cards, offsite redirects, and wallet payments.</Step></Steps>+#### 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:++```mermaid+sequenceDiagram+ participant Frontend+ participant Gateway+ participant Spree API++ Frontend->>Gateway: confirmPayment (redirects to gateway)+ Gateway-->>Frontend: Redirect back to /confirm-payment/:id?session=...+ Frontend->>Spree API: Complete Payment Session+ Spree API-->>Frontend: Session completed+ Frontend->>Spree API: POST /carts/:id/complete+ Spree API-->>Frontend: Order completed+ Frontend->>Frontend: Redirect to thank-you page+```++#### Webhook-Driven Completion (Browser Closed)++If the customer closes the browser after paying but before the frontend calls `complete`, Spree handles this via payment webhooks:++```mermaid+sequenceDiagram+ participant Payment Provider+ participant Spree API++ Payment Provider->>Spree API: POST /api/v3/webhooks/payments/:pm_id+ Spree API->>Spree API: Verify signature+ Spree API->>Spree API: Enqueue HandleWebhookJob+ Spree API-->>Payment Provider: 200 OK++ note over Spree API: Async processing+ Spree API->>Spree API: Create/update Payment+ Spree API->>Spree API: Complete order via Carts::Complete+```++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:@@ -357,6 +410,52 @@ const completed = await client.carts.paymentSessions.complete(console.log(completed.status) // 'completed'```+<Warning>+Completing a payment session does **not** complete the order. You must call `POST /carts/:id/complete` separately after the session is completed. This separation prevents race conditions between the frontend and payment webhooks.+</Warning>++**Complete the Order** (after the payment session is completed):++```typescript+const order = await client.carts.complete(cart.id, options)+```++### Payment Webhooks++Spree provides a generic webhook endpoint at `POST /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:++1. Verifies the webhook signature synchronously (returns `401` if invalid)+2. Enqueues a background job to process the event+3. Returns `200 OK` immediately++The background job creates/updates the Payment record, marks the session as completed, and completes the order if needed.++#### Gateway Interface++Gateway extensions implement `parse_webhook_event` to normalize provider-specific payloads:++```ruby+class MyGateway < Spree::Gateway+ def parse_webhook_event(raw_body, headers)+ # Verify signature — raise WebhookSignatureError if invalid+ event = verify_signature(raw_body, headers)++ case event.type+ when 'payment.captured'+ session = Spree::PaymentSession.find_by(external_id: event.payment_id)+ { action: :captured, payment_session: session }+ when 'payment.failed'+ session = Spree::PaymentSession.find_by(external_id: event.payment_id)+ { action: :failed, payment_session: session }+ else+ nil # unsupported event+ end+ end+end+```++Supported actions: `:captured`, `:authorized`, `:failed`, `:canceled`.+### PaymentOnce a Payment Session is completed, Spree creates a `Payment` record (`Spree::Payment`) to track the result. The Payment is linked to the session via `response_code` matching the session's `external_id`.@@ -608,3 +707,19 @@ See [Events](/developer/core-concepts/events) for more details on subscribing to- [Orders](/developer/core-concepts/orders) - Order management and state machine- [Checkout Customization](/developer/customization/checkout) - Customizing the checkout flow- [Events](/developer/core-concepts/events) - Subscribe to payment events++## Key Services++| Service | Description |+|---------|-------------|+| `Spree::Carts::Complete` | Completes the order — validates, processes payments (if not already done), advances state machine. Used by both the `POST /carts/:id/complete` endpoint and the webhook handler. |+| `Spree::Payments::HandleWebhook` | Processes a normalized webhook event — creates Payment, marks session completed, calls `Carts::Complete`. |+| `Spree::Payments::HandleWebhookJob` | Background job that wraps `HandleWebhook` — enqueued by the webhook controller for async processing. |++Both `Carts::Complete` and `HandleWebhook` are registered in `Spree::Dependencies` and can be replaced with custom implementations:++```ruby+# config/initializers/spree.rb+Spree::Dependencies.carts_complete_service = 'MyApp::CustomCartComplete'+Spree::Dependencies.payments_handle_webhook_service = 'MyApp::CustomWebhookHandler'+```diff --git a/docs/developer/how-to/custom-payment-method.mdx b/docs/developer/how-to/custom-payment-method.mdxindex bb44ca7ffb..1a1411cfcb 100644--- a/docs/developer/how-to/custom-payment-method.mdx+++ b/docs/developer/how-to/custom-payment-method.mdx@@ -126,7 +126,16 @@ class MyGateway < Spree::PaymentMethodpayment_sessionend- # Complete the session after the customer pays on the frontend+ # Complete the session after the customer pays on the frontend.+ #+ # Responsibilities:+ # - Verify payment status with the provider+ # - Create the Spree::Payment record+ # - Transition the payment to the correct state+ # - Mark the session as completed/failed+ #+ # Must NOT complete the order — that is handled by Carts::Complete+ # (called by the frontend or by the webhook handler).def complete_payment_session(payment_session:, params: {})# Verify the payment with your providerresult = MyProvider::Client.new(preferred_api_key).retrieve_session(@@ -137,23 +146,18 @@ class MyGateway < Spree::PaymentMethodpayment_session.process!# Create the Spree::Payment record- payment = payment_session.order.payments.create!(- amount: payment_session.amount,- payment_method: self,- response_code: payment_session.external_id,- state: 'checkout'- )+ payment = payment_session.find_or_create_payment!# Transition the payment to completed- payment.started_processing!- payment.complete!+ if payment.present? && !payment.completed?+ payment.started_processing! if payment.checkout?+ payment.complete! if payment.can_complete?+ endpayment_session.complete!elsepayment_session.fail!end-- payment_sessionenddef payment_icon_name@@ -173,7 +177,7 @@ const methods = await client.carts.paymentMethods.list(cart.id, options)// 2. Find your gateway (check session_required flag)const myGateway = methods.find(m => m.session_required)-// 3. Create a payment session+// 3. Create a payment session (after shipping is selected so amount is correct)const session = await client.carts.paymentSessions.create(cart.id, {payment_method_id: myGateway.id,}, options)@@ -181,74 +185,82 @@ const session = await client.carts.paymentSessions.create(cart.id, {// 4. Use the client_secret with your provider's frontend SDKconst result = await MyProviderSDK.confirmPayment(session.external_data.client_secret)-// 5. Complete the session+// 5. Complete the payment session (creates Payment record, does NOT complete order)const completed = await client.carts.paymentSessions.complete(cart.id, session.id,{ session_result: result.id },options)-```-## Step 4: Handle Webhooks (Recommended)--Webhooks ensure payments are captured even if the customer closes their browser before the frontend can call `complete`. This is critical for production reliability.+// 6. Complete the order+const order = await client.carts.complete(cart.id, options)+```-```ruby app/controllers/my_gateway/webhooks_controller.rb-module MyGateway- class WebhooksController < ApplicationController- skip_before_action :verify_authenticity_token+<Info>+**Important:** Always create the payment session **after** shipping is selected. If the order total changes (shipping rate change, coupon applied), create a new payment session with the updated amount. The `complete` call in step 5 only handles payment — step 6 finalizes the order.+</Info>- def create- payload = request.body.read- signature = request.headers['X-Signature']+## Step 4: Handle Webhooks (Recommended)- # Verify webhook authenticity- unless MyProvider::Webhook.verify(payload, signature, gateway.preferred_webhook_secret)- head :unauthorized- return- end+Webhooks ensure payments are captured even if the customer closes their browser after paying. Spree provides a generic webhook endpoint at `POST /api/v3/webhooks/payments/:payment_method_id` — you don't need to create your own controller or routes.- event = JSON.parse(payload)+Your gateway just needs to implement `parse_webhook_event` to normalize the provider-specific payload:- case event['type']- when 'payment.succeeded'- handle_payment_succeeded(event['data'])- when 'payment.failed'- handle_payment_failed(event['data'])- end+```ruby app/models/my_gateway.rb+class MyGateway < Spree::PaymentMethod+ # ... existing code ...- head :ok+ # Parse incoming webhook from your payment provider.+ #+ # @param raw_body [String] the raw request body+ # @param headers [Hash] the request headers+ # @return [Hash, nil] normalized result, or nil for unsupported events+ # @raise [Spree::PaymentMethod::WebhookSignatureError] if signature is invalid+ def parse_webhook_event(raw_body, headers)+ # 1. Verify the webhook signature+ signature = headers['HTTP_X_SIGNATURE']+ unless MyProvider::Webhook.verify(raw_body, signature, preferred_webhook_secret)+ raise Spree::PaymentMethod::WebhookSignatureErrorend- private+ # 2. Parse the payload+ event = JSON.parse(raw_body)- def handle_payment_succeeded(data)- payment_session = Spree::PaymentSession.find_by(external_id: data['session_id'])- return unless payment_session- return if payment_session.completed?+ # 3. Return a normalized result+ case event['type']+ when 'payment.succeeded'+ session = Spree::PaymentSession.find_by(external_id: event.dig('data', 'session_id'))+ return nil unless session- gateway.complete_payment_session(payment_session: payment_session)- end-- def handle_payment_failed(data)- payment_session = Spree::PaymentSession.find_by(external_id: data['session_id'])- return unless payment_session+ { action: :captured, payment_session: session }+ when 'payment.failed'+ session = Spree::PaymentSession.find_by(external_id: event.dig('data', 'session_id'))+ return nil unless session- payment_session.fail! unless payment_session.failed?- end-- def gateway- @gateway ||= MyGateway.active.first+ { action: :failed, payment_session: session }+ else+ nil # Unsupported event — Spree will return 200 OK and ignore itendendend```-Add the webhook route:+**That's it.** Spree handles the rest:+- Verifies the signature synchronously (returns `401` if `WebhookSignatureError` is raised)+- Enqueues a background job (`Spree::Payments::HandleWebhookJob`) for async processing+- Returns `200 OK` immediately to prevent provider retries+- The job creates/updates the `Payment` record, marks the session completed, and completes the order-```ruby config/routes.rb-post '/my-gateway/webhooks', to: 'my_gateway/webhooks#create'-```+The webhook URL for your payment method is available via `payment_method.webhook_url` — register this with your provider during setup.++### Supported Webhook Actions++| Action | Description |+|--------|-------------|+| `:captured` | Payment was captured (charged). Creates payment and completes order. |+| `:authorized` | Payment was authorized (not yet captured). Creates payment and completes order. |+| `:failed` | Payment failed. Marks the session as failed. |+| `:canceled` | Payment was canceled. Marks the session as canceled. |## Step 5: Control Payment Method Visibility (Optional)diff --git a/server/Gemfile.lock b/server/Gemfile.lockindex 9254be89be..c4b9eb833f 100644--- a/server/Gemfile.lock+++ b/server/Gemfile.lock@@ -1,6 +1,6 @@GITremote: https://github.com/spree/spree_stripe.git- revision: 6039c815c75c9b5474de167ba7ee33faa77b5cb0+ revision: 71fdd71e95aa7052c7457e9d0a016640d2072eb0specs:spree_stripe (1.6.0.beta)spree (>= 5.4.0.beta)@@ -209,7 +209,7 @@ GEMactiverecord (>= 4.0.0, < 8.2)awesome_print (1.9.2)aws-eventstream (1.4.0)- aws-partitions (1.1223.0)+ aws-partitions (1.1226.0)aws-sdk-core (3.243.0)aws-eventstream (~> 1, >= 1.3.0)aws-partitions (~> 1, >= 1.992.0)@@ -221,7 +221,7 @@ GEMaws-sdk-kms (1.122.0)aws-sdk-core (~> 3, >= 3.241.4)aws-sigv4 (~> 1.5)- aws-sdk-s3 (1.215.0)+ aws-sdk-s3 (1.216.0)aws-sdk-core (~> 3, >= 3.243.0)aws-sdk-kms (~> 1)aws-sigv4 (~> 1.5)@@ -331,12 +331,12 @@ GEMgeocoder (1.8.6)base64 (>= 0.1.0)csv (>= 3.0.0)- github_changelog_generator (1.16.4)+ github_changelog_generator (1.17.0)activesupportasync (>= 1.25.0)async-http-faraday+ benchmarkfaraday-http-cache- multi_jsonoctokit (~> 4.6)rainbow (>= 2.2.1)rake (>= 10.0)@@ -463,7 +463,6 @@ GEMmoney (6.19.0)i18n (>= 0.6.4, <= 2)msgpack (1.8.0)- multi_json (1.19.1)name_of_person (1.1.3)activesupport (>= 5.2.0)net-http (0.9.1)@@ -497,12 +496,12 @@ GEMoctokit (4.25.1)faraday (>= 1, < 3)sawyer (~> 0.9)- oj (3.16.15)+ oj (3.16.16)bigdecimal (>= 3.0)ostruct (>= 0.2)orm_adapter (0.5.0)ostruct (0.6.3)- pagy (43.3.2)+ pagy (43.3.3)jsonuriyaml@@ -675,7 +674,7 @@ GEMrubocop (>= 1.72)rubocop-performance (>= 1.24)rubocop-rails (>= 2.30)- ruby-lsp (0.26.7)+ ruby-lsp (0.26.8)language_server-protocol (~> 3.17.0)prism (>= 1.2, < 2.0)rbs (>= 3, < 5)@@ -775,13 +774,13 @@ GEMtailwindcss-rails (4.4.0)railties (>= 7.0.0)tailwindcss-ruby (~> 4.0)- tailwindcss-ruby (4.2.0)- tailwindcss-ruby (4.2.0-aarch64-linux-gnu)- tailwindcss-ruby (4.2.0-aarch64-linux-musl)- tailwindcss-ruby (4.2.0-arm64-darwin)- tailwindcss-ruby (4.2.0-x86_64-darwin)- tailwindcss-ruby (4.2.0-x86_64-linux-gnu)- tailwindcss-ruby (4.2.0-x86_64-linux-musl)+ tailwindcss-ruby (4.2.1)+ tailwindcss-ruby (4.2.1-aarch64-linux-gnu)+ tailwindcss-ruby (4.2.1-aarch64-linux-musl)+ tailwindcss-ruby (4.2.1-arm64-darwin)+ tailwindcss-ruby (4.2.1-x86_64-darwin)+ tailwindcss-ruby (4.2.1-x86_64-linux-gnu)+ tailwindcss-ruby (4.2.1-x86_64-linux-musl)terminal-table (4.0.0)unicode-display_width (>= 1.1.1, < 4)thor (1.5.0)@@ -913,10 +912,10 @@ CHECKSUMSawesome_nested_set (3.9.0) sha256=3ce99e816550f97f4de118e621630070aacf24928b920fe4a68846578a8daaedawesome_print (1.9.2) sha256=e99b32b704acff16d768b3468680793ced40bfdc4537eb07e06a4be11133786eaws-eventstream (1.4.0) sha256=116bf85c436200d1060811e6f5d2d40c88f65448f2125bc77ffce5121e6e183b- aws-partitions (1.1223.0) sha256=cdc1b936c2d343c4235f8a0a276bfc27ce17b389b1848a70479b9a686e1f48f3+ aws-partitions (1.1226.0) sha256=66fde74a9b53de8df53d511fdf2d898cb647d804ba1db34a6fe9b256fed449a8aws-sdk-core (3.243.0) sha256=a014eef785124b71d28325783fa422a1512f8421ec9b6e3931c8b0ca3fbb0f1caws-sdk-kms (1.122.0) sha256=47ce3f51b26bd7d76f1270cfdfca17b40073ecd3219c8c9400788712abfb4eb8- aws-sdk-s3 (1.215.0) sha256=15e90b20d985e343cd2cd315c030226b4f8826dd2a031c237cfcd8e0893b01ce+ aws-sdk-s3 (1.216.0) sha256=a3bf6191e6f7a3dfb04b7cc73409f059394be559e4aff92d2a764341e4d90af4aws-sigv4 (1.12.1) sha256=6973ff95cb0fd0dc58ba26e90e9510a2219525d07620c8babeb70ef831826c00base64 (0.3.0) sha256=27337aeabad6ffae05c265c450490628ef3ebd4b67be58257393227588f5a97bbcrypt (3.1.21) sha256=5964613d750a42c7ee5dc61f7b9336fb6caca429ba4ac9f2011609946e4a2dcf@@ -975,7 +974,7 @@ CHECKSUMSfriendly_id-mobility (1.0.5) sha256=8c0cf4d0a1358311db1b2dcc0e4c33077ae929c7e34749485268d066adbaf2e4gem-release (2.2.4) sha256=2f11124c1580c811507c3b47e875e420cf3ed792a98105b49df11971e6e94db3geocoder (1.8.6) sha256=e0ca1554b499f466de9b003f7dff70f89a5888761c2ca68ed9f86b6e5e24e74c- github_changelog_generator (1.16.4) sha256=21d2dfe41d50cf3a7ffe896774779d9d61da6aaf08d390f8ddff0dacbdf8a611+ github_changelog_generator (1.17.0) sha256=bfbac7c69d4887ab0974368d7df7e006375ee7aa3baae689b6b340d214f0b09dglobalid (1.3.0) sha256=05c639ad6eb4594522a0b07983022f04aa7254626ab69445a0e493aa3786ff11groupdate (6.7.0) sha256=beaa8d5bf3856814681914a1d4a20e77436a2214b85d0017dc2ea5c355fb6777highline (3.1.2) sha256=67cbd34d19f6ef11a7ee1d82ffab5d36dfd5b3be861f450fc1716c7125f4bb4a@@ -1026,7 +1025,6 @@ CHECKSUMSmonetize (1.13.0) sha256=0c1f8ae28aa21bbf1a6d014138d9bb0a5ce756c1a99b8b7f7d409c258b01d3b3money (6.19.0) sha256=ec936fa1e42f2783719241ed9fd52725d0efa628f928feea1eb5c37d5de7daf3msgpack (1.8.0) sha256=e64ce0212000d016809f5048b48eb3a65ffb169db22238fb4b72472fecb2d732- multi_json (1.19.1) sha256=7aefeff8f2c854bf739931a238e4aea64592845e0c0395c8a7d2eea7fdd631b7name_of_person (1.1.3) sha256=e12291250987ef79c413314f698f15d53e7a602c42231de99c276ef9585bc18cnet-http (0.9.1) sha256=25ba0b67c63e89df626ed8fac771d0ad24ad151a858af2cc8e6a716ca4336996net-imap (0.6.3) sha256=9bab75f876596d09ee7bf911a291da478e0cd6badc54dfb82874855ccc82f2ad@@ -1043,10 +1041,10 @@ CHECKSUMSnokogiri (1.19.1-x86_64-linux-gnu) sha256=1a4902842a186b4f901078e692d12257678e6133858d0566152fe29cdb98456anokogiri (1.19.1-x86_64-linux-musl) sha256=4267f38ad4fc7e52a2e7ee28ed494e8f9d8eb4f4b3320901d55981c7b995fc23octokit (4.25.1) sha256=c02092ee82dcdfe84db0e0ea630a70d32becc54245a4f0bacfd21c010df09b96- oj (3.16.15) sha256=4d3324cac3e8fef54c0fa250b2af26a16dadd9f9788a1d6b1b2098b793a1b2cd+ oj (3.16.16) sha256=3635b36128991796434f55da8decc0de236a323535adcb36fc04e6d0253c013dorm_adapter (0.5.0) sha256=aa5d0be5d540cbb46d3a93e88061f4ece6a25f6e97d6a47122beb84fe595e9b9ostruct (0.6.3) sha256=95a2ed4a4bd1d190784e666b47b2d3f078e4a9efda2fccf18f84ddc6538ed912- pagy (43.3.2) sha256=105683fccb86c1011a96c76da610c35c64aaf4cf412165606aadcb39e733e830+ pagy (43.3.3) sha256=26b822c32ac5452f733736aa0e56bfd45d7fd02358c7d91c7d31bae61164e758parallel (1.27.0) sha256=4ac151e1806b755fb4e2dc2332cbf0e54f2e24ba821ff2d3dcf86bf6dc4ae130paranoia (3.1.0) sha256=36574a46e8df663d0da7d9008e987b72a6a9eccee13c058b7094acc810e39f52parser (3.3.10.2) sha256=6f60c84aa4bdcedb6d1a2434b738fe8a8136807b6adc8f7f53b97da9bc4e9357@@ -1109,7 +1107,7 @@ CHECKSUMSrubocop-performance (1.26.1) sha256=cd19b936ff196df85829d264b522fd4f98b6c89ad271fa52744a8c11b8f71834rubocop-rails (2.34.3) sha256=10d37989024865ecda8199f311f3faca990143fbac967de943f88aca11eb9ad2rubocop-rails-omakase (1.1.0) sha256=2af73ac8ee5852de2919abbd2618af9c15c19b512c4cfc1f9a5d3b6ef009109d- ruby-lsp (0.26.7) sha256=60a1199fc7e329348d63a2479854f94435725d833eeabf3d539b790185cbf21f+ ruby-lsp (0.26.8) sha256=fa607c342736c6ea791c945ae05025bc306ef9dd72c640b0b660478c5832f968ruby-oembed (0.18.1) sha256=877b87b3d98e8137599044277fdb82a5536973bd9df68a93129163b781ae3a5fruby-progressbar (1.13.0) sha256=80fc9c47a9b640d6834e0dc7b3c94c9df37f08cb072b7761e4a71e22cff29b33ruby-vips (2.3.0) sha256=e685ec02c13969912debbd98019e50492e12989282da5f37d05f5471442f5374@@ -1147,13 +1145,13 @@ CHECKSUMSstripe (18.4.2) sha256=fd08a73ab87fc0b0ad938ca71293e1051e593001b70de5e9fcf12d1097133831stripe_event (2.14.0) sha256=aa9e5103030745bbef2177938395fefbf2c3f961622c3dfa9a6c3fa4548da075tailwindcss-rails (4.4.0) sha256=efa2961351a52acebe616e645a81a30bb4f27fde46cc06ce7688d1cd1131e916- tailwindcss-ruby (4.2.0) sha256=9bf5fbae0ce571208446a837046505c7ff0d18d7b4ddfd5d0f02f4d73cb4403d- tailwindcss-ruby (4.2.0-aarch64-linux-gnu) sha256=9b0e0576ea7493090ae871a0b6f1b62154c2934cb07e166296f8198a15638f37- tailwindcss-ruby (4.2.0-aarch64-linux-musl) sha256=d4a47e053b16a73677249d4aa4defea37301940b2ea6ea0325631e90f3aadfe5- tailwindcss-ruby (4.2.0-arm64-darwin) sha256=809776c7b784327dc526e041e52341adb46b6416d59ba3d86886adc9a6baaad0- tailwindcss-ruby (4.2.0-x86_64-darwin) sha256=f5562db5d520a4df22c8b3c359ed846b2e0131cf6319b4a11d4b0cb2b3f735d2- tailwindcss-ruby (4.2.0-x86_64-linux-gnu) sha256=5d5822135ba81bbd81cb9a81c479bea9e5954e39d4a31f5f4dafbef952993baf- tailwindcss-ruby (4.2.0-x86_64-linux-musl) sha256=4df2f0b7d59a7d9ad474c9e92a74ae1efdd8d56a072135aab9af225c3b1c5801+ tailwindcss-ruby (4.2.1) sha256=95886a1e24b42d76792c787d34e47098b53cb3b5a6363845bca4486f52b2e66a+ tailwindcss-ruby (4.2.1-aarch64-linux-gnu) sha256=de457ddfc999c6bbbe1a59fbc11eb2168d619f6e0cb72d8d3334d372b331e36f+ tailwindcss-ruby (4.2.1-aarch64-linux-musl) sha256=e6ed27704263201f8366316354aa45f9016cc9378ce8fac46fbbe65fafd4da5e+ tailwindcss-ruby (4.2.1-arm64-darwin) sha256=bcf222fb8542cf5433925623e5e7b257897fbb8291a2350daae870a32f2eeb91+ tailwindcss-ruby (4.2.1-x86_64-darwin) sha256=b737b84f80941628d03c703b31abb204151b9d0a494d58ed06fd8220a5162f1b+ tailwindcss-ruby (4.2.1-x86_64-linux-gnu) sha256=201d0e5e5d4aba52cae4ee4bd1acd497d2790c83e7f15da964aab8ec93876831+ tailwindcss-ruby (4.2.1-x86_64-linux-musl) sha256=79fa48ad51e533545f9fdbb04227e1342a65a42c2bd1314118b95473d5612007terminal-table (4.0.0) sha256=f504793203f8251b2ea7c7068333053f0beeea26093ec9962e62ea79f94301d2thor (1.5.0) sha256=e3a9e55fe857e44859ce104a84675ab6e8cd59c650a49106a05f55f136425e73thruster (0.1.19) sha256=3246eb6ea6fe699e89d6eecc4edda856452e4ebeb9d5999791f0e88832369527diff --git a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rbindex f2313c45bf..30e204e488 100644--- a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb@@ -98,25 +98,21 @@ module Spree# POST /api/v3/store/carts/:id/complete# Completes the checkout — returns Order (not Cart).- # Idempotent: if the gateway already completed the order, find_cart!- # will 404 (carts scope is incomplete-only), so we fall back to the- # orders scope and return the completed order.- # this is temporary hack until Spree 6 when Cart and Order will be separate models+ # Idempotent: if the cart is already completed, falls back to the+ # orders scope and returns the completed order.def completefind_cart!- with_order_lock do- Spree.checkout_complete_service.call(order: @cart)- @cart.reload+ result = Spree::Dependencies.carts_complete_service.constantize.call(cart: @cart)- if @cart.complete?- render_order- else- render_service_error(- @cart.errors.full_messages.to_sentence.presence || 'Could not complete checkout',- code: ERROR_CODES[:cart_cannot_complete]- )- end+ if result.success?+ @cart = result.value+ render_order+ else+ render_service_error(+ result.error.to_s.presence || 'Could not complete checkout',+ code: ERROR_CODES[:cart_cannot_complete]+ )endrescue ActiveRecord::RecordNotFound@cart = current_store.orders.complete.find_by_prefix_id!(params[:id])diff --git a/spree/api/app/controllers/spree/api/v3/webhooks/payments_controller.rb b/spree/api/app/controllers/spree/api/v3/webhooks/payments_controller.rbnew file mode 100644index 0000000000..de2925b6b0--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/webhooks/payments_controller.rb@@ -0,0 +1,52 @@+module Spree+ module Api+ module V3+ module Webhooks+ class PaymentsController < ActionController::API+ include ActionController::RateLimiting++ RATE_LIMIT_RESPONSE = -> {+ [429, { 'Content-Type' => 'application/json', 'Retry-After' => '60' },+ [{ error: { code: 'rate_limit_exceeded', message: 'Too many requests' } }.to_json]]+ }++ rate_limit to: 120, within: 1.minute,+ store: Rails.cache,+ by: -> { request.remote_ip },+ with: RATE_LIMIT_RESPONSE++ # POST /api/v3/webhooks/payments/:payment_method_id+ #+ # Verifies the webhook signature synchronously (returns 401 if invalid),+ # then enqueues async processing and returns 200 immediately.+ def create+ payment_method = Spree::PaymentMethod.find_by_prefix_id!(params[:payment_method_id])++ # Signature verification must be synchronous — invalid = 401+ result = payment_method.parse_webhook_event(request.raw_post, request.headers)++ # Unsupported event — acknowledge receipt+ return head :ok if result.nil?++ # Process asynchronously — gateways have timeout limits and will+ # retry on timeouts, so we must return 200 quickly.+ Spree::Payments::HandleWebhookJob.perform_later(+ payment_method_id: payment_method.id,+ action: result[:action].to_s,+ payment_session_id: result[:payment_session].id+ )++ head :ok+ rescue Spree::PaymentMethod::WebhookSignatureError+ head :unauthorized+ rescue ActiveRecord::RecordNotFound+ head :not_found+ rescue StandardError => e+ Rails.error.report(e, source: 'spree.webhooks.payments')+ head :ok+ end+ end+ end+ end+ end+enddiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex 210ebe5569..a2ddb23a69 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -84,6 +84,11 @@ Spree::Core::Engine.add_routes doget 'digitals/:token', to: 'digitals#show', as: :digital_downloadend++ # Webhooks (outside of store namespace — no API key authentication)+ namespace :webhooks do+ post 'payments/:payment_method_id', to: 'payments#create', as: :payment_webhook+ endendendenddiff --git a/spree/api/spec/controllers/spree/api/v3/webhooks/payments_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/webhooks/payments_controller_spec.rbnew file mode 100644index 0000000000..16f23436d4--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/webhooks/payments_controller_spec.rb@@ -0,0 +1,85 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Webhooks::PaymentsController, type: :controller do+ render_views++ let(:store) { @default_store }+ let(:payment_method) { create(:bogus_payment_method, stores: [store]) }++ describe 'POST #create' do+ context 'when webhook event is unsupported' do+ before do+ allow_any_instance_of(Spree::PaymentMethod).to receive(:parse_webhook_event).and_return(nil)+ end++ it 'returns ok without processing' do+ post :create, params: { payment_method_id: payment_method.prefixed_id }++ expect(response).to have_http_status(:ok)+ end+ end++ context 'when signature verification fails' do+ before do+ allow_any_instance_of(Spree::PaymentMethod).to receive(:parse_webhook_event)+ .and_raise(Spree::PaymentMethod::WebhookSignatureError)+ end++ it 'returns unauthorized' do+ post :create, params: { payment_method_id: payment_method.prefixed_id }++ expect(response).to have_http_status(:unauthorized)+ end+ end++ context 'when payment method is not found' do+ it 'returns not found' do+ post :create, params: { payment_method_id: 'pm_nonexistent' }++ expect(response).to have_http_status(:not_found)+ end+ end++ context 'when an unexpected error occurs' do+ before do+ allow_any_instance_of(Spree::PaymentMethod).to receive(:parse_webhook_event)+ .and_raise(StandardError, 'unexpected')+ end++ it 'returns ok to prevent gateway retries' do+ expect(Rails.error).to receive(:report).with(kind_of(StandardError), hash_including(source: 'spree.webhooks.payments'))++ post :create, params: { payment_method_id: payment_method.prefixed_id }++ expect(response).to have_http_status(:ok)+ end+ end++ context 'when webhook is processed successfully' do+ let(:order) { create(:order_with_line_items, store: store) }+ let(:payment_session) { create(:bogus_payment_session, order: order, payment_method: payment_method) }++ before do+ allow_any_instance_of(Spree::PaymentMethod).to receive(:parse_webhook_event).and_return(+ { action: :captured, payment_session: payment_session, metadata: {} }+ )+ end++ it 'returns ok' do+ post :create, params: { payment_method_id: payment_method.prefixed_id }++ expect(response).to have_http_status(:ok)+ end++ it 'enqueues HandleWebhookJob' do+ expect {+ post :create, params: { payment_method_id: payment_method.prefixed_id }+ }.to have_enqueued_job(Spree::Payments::HandleWebhookJob).with(+ payment_method_id: payment_method.id,+ action: 'captured',+ payment_session_id: payment_session.id+ )+ end+ end+ end+enddiff --git a/spree/core/app/jobs/spree/payments/handle_webhook_job.rb b/spree/core/app/jobs/spree/payments/handle_webhook_job.rbnew file mode 100644index 0000000000..69f8095e4f--- /dev/null+++ b/spree/core/app/jobs/spree/payments/handle_webhook_job.rb@@ -0,0 +1,22 @@+module Spree+ module Payments+ class HandleWebhookJob < Spree::BaseJob+ queue_as Spree.queues.payment_webhooks++ retry_on ActiveRecord::Deadlocked, wait: 5.seconds, attempts: 3+ retry_on ActiveRecord::LockWaitTimeout, wait: 5.seconds, attempts: 3+ discard_on ActiveRecord::RecordNotFound++ def perform(payment_method_id:, action:, payment_session_id:)+ payment_method = Spree::PaymentMethod.find(payment_method_id)+ payment_session = Spree::PaymentSession.find(payment_session_id)++ Spree::Dependencies.payments_handle_webhook_service.constantize.call(+ payment_method: payment_method,+ action: action.to_sym,+ payment_session: payment_session+ )+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/payment_method.rb b/spree/core/app/models/spree/payment_method.rbindex 2735506780..0dcdbe1f00 100644--- a/spree/core/app/models/spree/payment_method.rb+++ b/spree/core/app/models/spree/payment_method.rb@@ -71,10 +71,44 @@ module Spree# Completes a payment session via the provider.# Override in gateway subclasses to implement provider-specific session completion.+ #+ # Responsibilities:+ # - Verify payment status with the provider+ # - Create/update the Spree::Payment record+ # - Patch order data from provider (e.g. wallet billing address)+ # - Transition payment session to completed/failed+ #+ # Must NOT complete the order — that is handled by Carts::Complete+ # (called by the frontend or by the webhook handler).def complete_payment_session(payment_session:, params: {})raise ::NotImplementedError, 'You must implement complete_payment_session method for this gateway.'end+ # Parses an incoming webhook payload from the payment provider.+ # Override in gateway subclasses to implement provider-specific webhook parsing.+ #+ # @param raw_body [String] the raw request body+ # @param headers [Hash] the request headers+ # @return [Hash, nil] normalized result or nil for unsupported events+ # { action: :captured/:authorized/:failed/:canceled,+ # payment_session: <Spree::PaymentSession>,+ # metadata: {} }+ # @raise [Spree::PaymentMethod::WebhookSignatureError] if signature is invalid+ def parse_webhook_event(raw_body, headers)+ raise ::NotImplementedError, 'You must implement parse_webhook_event method for this gateway.'+ end++ # Returns the webhook URL for this payment method.+ # @return [String, nil]+ def webhook_url+ store = stores.first+ return nil unless store++ "#{store.url_or_custom_domain}/api/v3/webhooks/payments/#{prefixed_id}"+ end++ class WebhookSignatureError < StandardError; end+# Whether this payment method supports setup sessions (saving payment methods for future use).# Override in gateway subclasses that support tokenization without a payment.def setup_session_supported?diff --git a/spree/core/app/models/spree/payment_session.rb b/spree/core/app/models/spree/payment_session.rbindex b66c72e6c9..b4a7590580 100644--- a/spree/core/app/models/spree/payment_session.rb+++ b/spree/core/app/models/spree/payment_session.rb@@ -76,6 +76,24 @@ module Spreeexpires_at.present? && expires_at <= Time.currentend+ # Creates or finds the Spree::Payment record for this session.+ # Gateway subclasses can override this in their PaymentSession subclass+ # to handle gateway-specific source creation (credit cards, wallets, etc).+ #+ # @param metadata [Hash] gateway-specific metadata+ # @return [Spree::Payment] the payment record+ def find_or_create_payment!(metadata = {})+ return payment if payment.present?++ order.payments.find_or_create_by!(+ payment_method: payment_method,+ response_code: external_id,+ ) do |p|+ p.amount = amount+ p.skip_source_requirement = true+ end+ end+privatedef publish_processing_eventdiff --git a/spree/core/app/models/spree/shipment.rb b/spree/core/app/models/spree/shipment.rbindex 552e036895..0b34191f6a 100644--- a/spree/core/app/models/spree/shipment.rb+++ b/spree/core/app/models/spree/shipment.rb@@ -354,6 +354,7 @@ module Spreereturn if order.completed?update_amounts+ reload # reload to pick up cost set by update_columns in update_amountsorder.set_shipments_costenddiff --git a/spree/core/app/services/spree/carts/complete.rb b/spree/core/app/services/spree/carts/complete.rbnew file mode 100644index 0000000000..ca2bbed42c--- /dev/null+++ b/spree/core/app/services/spree/carts/complete.rb@@ -0,0 +1,46 @@+# In Spree 6 this servoice will complete the Spree::Cart, and create a Spree::Order+# created based on the contents of the cart.+module Spree+ module Carts+ class Complete+ prepend Spree::ServiceModule::Base++ # Completes the cart and creates a Spree::Order based on its contents.+ # @return [Spree::Order]+ def call(cart:)+ return success(cart) if cart.completed?+ return failure(cart, 'Order is canceled') if cart.canceled?++ cart.with_lock do+ process_payments!(cart) if cart.payment_required?++ return failure(cart, cart.errors.full_messages.to_sentence) if cart.errors.any?++ advance_to_complete!(cart)++ if cart.reload.complete?+ success(cart)+ else+ failure(cart, cart.errors.full_messages.to_sentence.presence || 'Could not complete checkout')+ end+ end+ end++ private++ def process_payments!(cart)+ # If payments were already processed by the payment session+ # (e.g. Stripe charged the card during complete_payment_session),+ # skip re-processing. Only process unprocessed (checkout state) payments.+ return if cart.payment_total >= cart.total+ return if cart.payments.valid.any?(&:completed?) && cart.unprocessed_payments.empty?++ cart.process_payments!+ end++ def advance_to_complete!(cart)+ cart.next until cart.complete? || cart.errors.present?+ end+ end+ end+enddiff --git a/spree/core/app/services/spree/payments/handle_webhook.rb b/spree/core/app/services/spree/payments/handle_webhook.rbnew file mode 100644index 0000000000..0227d9b41b--- /dev/null+++ b/spree/core/app/services/spree/payments/handle_webhook.rb@@ -0,0 +1,58 @@+module Spree+ module Payments+ class HandleWebhook+ prepend Spree::ServiceModule::Base++ # @param payment_method [Spree::PaymentMethod] the payment method that received the webhook+ # @param action [Symbol] normalized action (:captured, :authorized, :failed, :canceled)+ # @param payment_session [Spree::PaymentSession] the payment session associated with the webhook+ # @param metadata [Hash] gateway-specific metadata (e.g. charge data, psp reference)+ def call(payment_method:, action:, payment_session:, metadata: {})+ return success(nil) if payment_session.nil?++ order = payment_session.order++ case action+ when :captured, :authorized+ handle_success(payment_session, order, metadata)+ when :failed+ payment_session.fail if payment_session.can_fail?+ success(payment_session)+ when :canceled+ payment_session.cancel if payment_session.can_cancel?+ success(payment_session)+ else+ failure(payment_session, "Unknown webhook action: #{action}")+ end+ end++ private++ def handle_success(payment_session, order, metadata)+ order.with_lock do+ # Ensure payment record exists+ payment = payment_session.find_or_create_payment!(metadata)++ # Mark payment as completed — the webhook confirms the gateway processed it+ if payment.present? && !payment.completed?+ payment.started_processing! if payment.checkout?+ payment.complete! if payment.can_complete?+ end++ # Mark session as completed+ payment_session.complete if payment_session.can_complete?++ # Complete order if not already done+ unless order.reload.completed?+ Spree::Dependencies.carts_complete_service.constantize.call(cart: order)+ end+ end++ success(payment_session)+ rescue StandardError => e+ Rails.error.report(e, context: { payment_session_id: payment_session.id, order_id: order.id }, source: 'spree.payments.webhook')+ failure(payment_session, e.message)+ end+ end+ end+enddiff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rbindex 2b9743926a..e0a83ecc8b 100644--- a/spree/core/lib/spree/core.rb+++ b/spree/core/lib/spree/core.rb@@ -109,6 +109,7 @@ module Spreeaddresses: :default,gift_cards: :default,webhooks: :default,+ payment_webhooks: :default,api_keys: :default)enddiff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rbindex b8313b7970..3d37722c4f 100644--- a/spree/core/lib/spree/core/dependencies.rb+++ b/spree/core/lib/spree/core/dependencies.rb@@ -23,6 +23,9 @@ module Spreecart_change_currency_service: 'Spree::Cart::ChangeCurrency',cart_remove_out_of_stock_items_service: 'Spree::Cart::RemoveOutOfStockItems',+ # carts+ carts_complete_service: 'Spree::Carts::Complete',+# checkoutcheckout_next_service: 'Spree::Checkout::Next',checkout_advance_service: 'Spree::Checkout::Advance',@@ -85,6 +88,7 @@ module Spreeline_item_destroy_service: 'Spree::LineItems::Destroy',payment_create_service: 'Spree::Payments::Create',+ payments_handle_webhook_service: 'Spree::Payments::HandleWebhook',# findersaddress_finder: 'Spree::Addresses::Find',diff --git a/spree/core/spec/jobs/spree/payments/handle_webhook_job_spec.rb b/spree/core/spec/jobs/spree/payments/handle_webhook_job_spec.rbnew file mode 100644index 0000000000..ec36b8578c--- /dev/null+++ b/spree/core/spec/jobs/spree/payments/handle_webhook_job_spec.rb@@ -0,0 +1,87 @@+require 'spec_helper'++RSpec.describe Spree::Payments::HandleWebhookJob, type: :job do+ let(:store) { @default_store }+ let(:order) { create(:order_with_line_items, store: store) }+ let(:payment_method) { create(:bogus_payment_method, stores: [store]) }+ let(:payment_session) { create(:bogus_payment_session, order: order, payment_method: payment_method, amount: order.total) }++ before do+ order.update_column(:state, 'payment')+ order.shipments.each { |s| s.update_column(:state, 'ready') }+ end++ describe '#perform' do+ it 'calls the HandleWebhook service with correct arguments' do+ handler = instance_double(Spree::Payments::HandleWebhook)+ allow(Spree::Payments::HandleWebhook).to receive(:new).and_return(handler)+ expect(handler).to receive(:call).with(+ payment_method: payment_method,+ action: :captured,+ payment_session: payment_session+ )++ described_class.new.perform(+ payment_method_id: payment_method.id,+ action: 'captured',+ payment_session_id: payment_session.id+ )+ end++ it 'converts action string to symbol' do+ handler = instance_double(Spree::Payments::HandleWebhook)+ allow(Spree::Payments::HandleWebhook).to receive(:new).and_return(handler)+ expect(handler).to receive(:call).with(+ hash_including(action: :authorized)+ )++ described_class.new.perform(+ payment_method_id: payment_method.id,+ action: 'authorized',+ payment_session_id: payment_session.id+ )+ end+ end++ describe 'queue' do+ it 'uses the payment_webhooks queue' do+ expect(described_class.new.queue_name).to eq(Spree.queues.payment_webhooks.to_s)+ end+ end++ describe 'error handling' do+ it 'discards on ActiveRecord::RecordNotFound' do+ expect {+ described_class.perform_now(+ payment_method_id: 0,+ action: 'captured',+ payment_session_id: payment_session.id+ )+ }.not_to raise_error+ end++ it 'retries on ActiveRecord::Deadlocked' do+ expect(described_class.rescue_handlers).to include(+ have_attributes(first: 'ActiveRecord::Deadlocked')+ )+ end++ it 'retries on ActiveRecord::LockWaitTimeout' do+ expect(described_class.rescue_handlers).to include(+ have_attributes(first: 'ActiveRecord::LockWaitTimeout')+ )+ end+ end++ describe 'enqueuing' do+ it 'can be enqueued with perform_later' do+ expect {+ described_class.perform_later(+ payment_method_id: payment_method.id,+ action: 'captured',+ payment_session_id: payment_session.id+ )+ }.to have_enqueued_job(described_class)+ end+ end+enddiff --git a/spree/core/spec/models/spree/payment_session_spec.rb b/spree/core/spec/models/spree/payment_session_spec.rbindex 28a609c665..61e65f8ccd 100644--- a/spree/core/spec/models/spree/payment_session_spec.rb+++ b/spree/core/spec/models/spree/payment_session_spec.rb@@ -254,4 +254,39 @@ RSpec.describe Spree::PaymentSession, type: :model doendendend++ describe '#find_or_create_payment!' do+ it 'creates a payment record for the order' do+ payment = payment_session.find_or_create_payment!++ expect(payment).to be_persisted+ expect(payment.order).to eq(order)+ expect(payment.payment_method).to eq(payment_method)+ expect(payment.response_code).to eq(payment_session.external_id)+ expect(payment.amount).to eq(payment_session.amount)+ end++ it 'returns existing payment if already present' do+ existing = create(:payment,+ order: order,+ payment_method: payment_method,+ response_code: payment_session.external_id,+ amount: payment_session.amount)++ payment = payment_session.find_or_create_payment!++ expect(payment.id).to eq(existing.id)+ end++ it 'returns the associated payment via has_one' do+ create(:payment,+ order: order,+ payment_method: payment_method,+ response_code: payment_session.external_id,+ amount: payment_session.amount)++ expect(payment_session.payment).to be_present+ expect(payment_session.find_or_create_payment!.id).to eq(payment_session.payment.id)+ end+ endenddiff --git a/spree/core/spec/services/spree/carts/complete_spec.rb b/spree/core/spec/services/spree/carts/complete_spec.rbnew file mode 100644index 0000000000..a583284344--- /dev/null+++ b/spree/core/spec/services/spree/carts/complete_spec.rb@@ -0,0 +1,105 @@+require 'spec_helper'++RSpec.describe Spree::Carts::Complete do+ subject { described_class }++ let(:store) { @default_store }+ let(:order) { create(:order_with_line_items, store: store) }++ before do+ order.update_column(:state, 'payment')+ create(:payment, order: order, amount: order.total, state: 'checkout')+ order.shipments.each { |s| s.update_column(:state, 'ready') }+ end++ describe '#call' do+ it 'completes the order' do+ result = subject.call(cart: order)++ expect(result).to be_success+ expect(order.reload.state).to eq('complete')+ expect(order.completed_at).to be_present+ end++ it 'returns the order as value' do+ result = subject.call(cart: order)++ expect(result.value).to eq(order)+ end++ context 'when order is already completed' do+ before { order.update_columns(state: 'complete', completed_at: Time.current) }++ it 'returns success without re-processing' do+ result = subject.call(cart: order)++ expect(result).to be_success+ expect(result.value).to eq(order)+ end+ end++ context 'when order is canceled' do+ before { order.update_column(:state, 'canceled') }++ it 'returns failure' do+ result = subject.call(cart: order)++ expect(result).to be_failure+ end+ end++ context 'when order cannot be completed (missing address)' do+ before { order.update_column(:state, 'cart') }++ let(:order) { create(:order, store: store) }++ it 'returns failure' do+ result = subject.call(cart: order)++ expect(result).to be_failure+ end+ end++ context 'when payments were already processed by the payment session' do+ before do+ order.payments.destroy_all+ create(:payment, order: order, amount: order.total, state: 'completed')+ order.update_column(:payment_total, order.total)+ end++ it 'completes the order without re-processing payments' do+ result = subject.call(cart: order)++ expect(result).to be_success+ expect(order.reload.state).to eq('complete')+ # Payment stays completed — not re-processed+ expect(order.payments.first.state).to eq('completed')+ end+ end++ context 'when payment_total covers order total' do+ before do+ order.update_column(:payment_total, order.total)+ end++ it 'completes the order successfully' do+ result = subject.call(cart: order)++ expect(result).to be_success+ expect(order.reload.state).to eq('complete')+ end+ end++ context 'when order does not require payment' do+ before do+ order.update_column(:total, 0)+ end++ it 'completes without payment processing' do+ result = subject.call(cart: order)++ expect(result).to be_success+ end+ end+ end+enddiff --git a/spree/core/spec/services/spree/payments/handle_webhook_spec.rb b/spree/core/spec/services/spree/payments/handle_webhook_spec.rbnew file mode 100644index 0000000000..69ee914e90--- /dev/null+++ b/spree/core/spec/services/spree/payments/handle_webhook_spec.rb@@ -0,0 +1,117 @@+require 'spec_helper'++RSpec.describe Spree::Payments::HandleWebhook do+ subject { described_class }++ let(:store) { @default_store }+ let(:order) { create(:order_with_line_items, store: store) }+ let(:payment_method) { create(:bogus_payment_method, stores: [store]) }+ let(:payment_session) { create(:bogus_payment_session, order: order, payment_method: payment_method, amount: order.total) }++ before do+ order.update_column(:state, 'payment')+ order.shipments.each { |s| s.update_column(:state, 'ready') }+ end++ describe '#call' do+ context 'with :captured action' do+ it 'creates a payment record' do+ expect {+ subject.call(payment_method: payment_method, action: :captured, payment_session: payment_session)+ }.to change { order.payments.count }.by(1)+ end++ it 'completes the payment session' do+ subject.call(payment_method: payment_method, action: :captured, payment_session: payment_session)++ expect(payment_session.reload.status).to eq('completed')+ end++ it 'completes the order' do+ subject.call(payment_method: payment_method, action: :captured, payment_session: payment_session)++ expect(order.reload.state).to eq('complete')+ end++ it 'returns success' do+ result = subject.call(payment_method: payment_method, action: :captured, payment_session: payment_session)++ expect(result).to be_success+ end+ end++ context 'with :authorized action' do+ it 'creates a payment record and completes the order' do+ result = subject.call(payment_method: payment_method, action: :authorized, payment_session: payment_session)++ expect(result).to be_success+ expect(payment_session.reload.status).to eq('completed')+ expect(order.reload.payments.count).to eq(1)+ end+ end++ context 'with :failed action' do+ it 'fails the payment session' do+ result = subject.call(payment_method: payment_method, action: :failed, payment_session: payment_session)++ expect(result).to be_success+ expect(payment_session.reload.status).to eq('failed')+ end++ it 'does not create a payment' do+ expect {+ subject.call(payment_method: payment_method, action: :failed, payment_session: payment_session)+ }.not_to change { order.payments.count }+ end++ it 'does not complete the order' do+ subject.call(payment_method: payment_method, action: :failed, payment_session: payment_session)++ expect(order.reload.state).not_to eq('complete')+ end+ end++ context 'with :canceled action' do+ it 'cancels the payment session' do+ result = subject.call(payment_method: payment_method, action: :canceled, payment_session: payment_session)++ expect(result).to be_success+ expect(payment_session.reload.status).to eq('canceled')+ end+ end++ context 'when payment_session is nil' do+ it 'returns success without processing' do+ result = subject.call(payment_method: payment_method, action: :captured, payment_session: nil)++ expect(result).to be_success+ end+ end++ context 'when order is already completed' do+ before do+ order.update_columns(state: 'complete', completed_at: Time.current)+ end++ it 'still creates the payment and completes the session' do+ result = subject.call(payment_method: payment_method, action: :captured, payment_session: payment_session)++ expect(result).to be_success+ expect(payment_session.reload.status).to eq('completed')+ expect(order.payments.count).to eq(1)+ end+ end++ context 'when payment session is already completed' do+ before do+ payment_session.update_column(:status, 'completed')+ end++ it 'does not fail on duplicate webhook' do+ result = subject.call(payment_method: payment_method, action: :captured, payment_session: payment_session)++ expect(result).to be_success+ end+ end+ end+end