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 Sessions API
Damian Legawiec84ed4108d7bd
diff --git a/CLAUDE.md b/CLAUDE.mdindex 0a309eebd6..d98ae50f5d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -261,7 +261,7 @@ We use [typelizer](https://github.com/skryukov/typelizer) to generate TypeScript- Types are generated to `sdk/src/types/generated/`- Store types: `StoreProduct`, `StoreOrder`, etc.- Admin types: `AdminProduct`, `AdminOrder`, etc.-- Run `bundle exec rake typelizer:generate` to regenerate types+- Run `bundle exec rake typelizer:generate` to regenerate types every time you make changes to serializers### API Authentication@@ -304,7 +304,7 @@ module Spreedef handle(event)order_id = event.payload['id']- order = Spree::Order.find_by(id: order_id)+ order = Spree::Order.find_by_prefix_id(order_id)return unless order# Your custom logic herediff --git a/backend/engines/api/app/controllers/spree/api/v3/store/orders/payment_sessions_controller.rb b/backend/engines/api/app/controllers/spree/api/v3/store/orders/payment_sessions_controller.rbnew file mode 100644index 0000000000..4d1919051f--- /dev/null+++ b/backend/engines/api/app/controllers/spree/api/v3/store/orders/payment_sessions_controller.rb@@ -0,0 +1,96 @@+module Spree+ module Api+ module V3+ module Store+ module Orders+ class PaymentSessionsController < ResourceController+ include Spree::Api::V3::OrderConcern++ skip_before_action :set_resource+ before_action :authorize_order_access!+ before_action :set_payment_session, only: [:show, :update, :complete]++ # POST /api/v3/store/orders/:order_id/payment_sessions+ def create+ payment_method = current_store.payment_methods.find_by_prefix_id!(permitted_params[:payment_method_id])++ @payment_session = payment_method.create_payment_session(+ order: @parent,+ amount: permitted_params[:amount],+ external_data: permitted_params[:external_data] || {}+ )++ if @payment_session.persisted?+ render json: serialize_resource(@payment_session), status: :created+ else+ render_errors(@payment_session.errors)+ end+ end++ # GET /api/v3/store/orders/:order_id/payment_sessions/:id+ def show+ render json: serialize_resource(@payment_session)+ end++ # PATCH /api/v3/store/orders/:order_id/payment_sessions/:id+ def update+ @payment_session.payment_method.update_payment_session(+ payment_session: @payment_session,+ amount: permitted_params[:amount],+ external_data: permitted_params[:external_data] || {}+ )++ if @payment_session.errors.empty?+ render json: serialize_resource(@payment_session.reload)+ else+ render_errors(@payment_session.errors)+ end+ end++ # PATCH /api/v3/store/orders/:order_id/payment_sessions/:id/complete+ def complete+ @payment_session.payment_method.complete_payment_session(+ payment_session: @payment_session,+ params: complete_params+ )++ if @payment_session.errors.empty?+ render json: serialize_resource(@payment_session.reload)+ else+ render_errors(@payment_session.errors)+ end+ end++ protected++ def parent_association+ :payment_sessions+ end++ def model_class+ Spree::PaymentSession+ end++ def serializer_class+ Spree.api.payment_session_serializer+ end++ def permitted_params+ params.permit(Spree::PermittedAttributes.payment_session_attributes)+ end++ def complete_params+ params.permit(:session_result, { external_data: {} })+ end++ private++ def set_payment_session+ @payment_session = @parent.payment_sessions.find_by_prefix_id!(params[:id])+ end+ end+ end+ end+ end+ end+enddiff --git a/backend/engines/api/app/serializers/spree/api/v3/payment_session_serializer.rb b/backend/engines/api/app/serializers/spree/api/v3/payment_session_serializer.rbnew file mode 100644index 0000000000..e75a9fd0dc--- /dev/null+++ b/backend/engines/api/app/serializers/spree/api/v3/payment_session_serializer.rb@@ -0,0 +1,32 @@+module Spree+ module Api+ module V3+ class PaymentSessionSerializer < BaseSerializer+ typelize status: :string, amount: :string, currency: :string,+ external_id: :string, external_data: 'Record<string, unknown>',+ expires_at: 'string | null', customer_external_id: 'string | null',+ payment_method_id: :string, order_id: :string++ attributes :status, :currency, :external_id, :external_data,+ :customer_external_id,+ expires_at: :iso8601, created_at: :iso8601, updated_at: :iso8601++ attribute :amount do |session|+ session.amount&.to_s+ end++ attribute :payment_method_id do |session|+ session.payment_method&.prefixed_id+ end++ attribute :order_id do |session|+ session.order&.prefixed_id+ end++ one :payment_method, resource: Spree.api.payment_method_serializer+ one :payment, resource: Spree.api.payment_serializer,+ if: proc { |session| session.payment.present? }+ end+ end+ end+enddiff --git a/backend/engines/api/config/routes.rb b/backend/engines/api/config/routes.rbindex 5674c49b0e..b6195acd8d 100644--- a/backend/engines/api/config/routes.rb+++ b/backend/engines/api/config/routes.rb@@ -44,6 +44,11 @@ Spree::Core::Engine.add_routes doresources :coupon_codes, only: [:create, :destroy], controller: 'orders/coupon_codes'resources :payments, only: [:index, :show], controller: 'orders/payments'resources :payment_methods, only: [:index], controller: 'orders/payment_methods'+ resources :payment_sessions, only: [:create, :show, :update], controller: 'orders/payment_sessions' do+ member do+ patch :complete+ end+ endresources :shipments, only: [:index, :show, :update], controller: 'orders/shipments'enddiff --git a/backend/engines/api/lib/spree/api/dependencies.rb b/backend/engines/api/lib/spree/api/dependencies.rbindex abe8c3a7c4..58279b3019 100644--- a/backend/engines/api/lib/spree/api/dependencies.rb+++ b/backend/engines/api/lib/spree/api/dependencies.rb@@ -101,6 +101,7 @@ module Spreeorder_serializer: 'Spree::Api::V3::OrderSerializer',line_item_serializer: 'Spree::Api::V3::LineItemSerializer',payment_serializer: 'Spree::Api::V3::PaymentSerializer',+ payment_session_serializer: 'Spree::Api::V3::PaymentSessionSerializer',payment_source_serializer: 'Spree::Api::V3::PaymentSourceSerializer',shipment_serializer: 'Spree::Api::V3::ShipmentSerializer',address_serializer: 'Spree::Api::V3::AddressSerializer',diff --git a/backend/engines/api/lib/spree/api/openapi/typelizer_converter.rb b/backend/engines/api/lib/spree/api/openapi/typelizer_converter.rbindex b2d3594d28..308cfe320e 100644--- a/backend/engines/api/lib/spree/api/openapi/typelizer_converter.rb+++ b/backend/engines/api/lib/spree/api/openapi/typelizer_converter.rb@@ -121,6 +121,14 @@ module Spreereturn parse_array_type(type_string, prop)end+ # Handle Record<K, V> types (TypeScript generic for key-value objects)+ if type_string.match?(/^Record</)+ schema = { type: :object }+ schema = { type: :array, items: schema } if prop.multi+ schema[:nullable] = true if prop.nullable+ return schema+ end+# Handle basic typesif TYPESCRIPT_TO_OPENAPI_TYPES.key?(type_string)schema = TYPESCRIPT_TO_OPENAPI_TYPES[type_string].dupdiff --git a/backend/engines/api/spec/controllers/spree/api/v3/store/orders/payment_sessions_controller_spec.rb b/backend/engines/api/spec/controllers/spree/api/v3/store/orders/payment_sessions_controller_spec.rbnew file mode 100644index 0000000000..b74368cdfc--- /dev/null+++ b/backend/engines/api/spec/controllers/spree/api/v3/store/orders/payment_sessions_controller_spec.rb@@ -0,0 +1,156 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Store::Orders::PaymentSessionsController, type: :controller do+ render_views++ include_context 'API v3 Store'++ let(:order) { create(:order_with_line_items, user: user, store: store, state: 'payment') }+ let(:payment_method) { create(:bogus_payment_method, stores: [store]) }+ let!(:payment_session) do+ create(:bogus_payment_session,+ order: order,+ payment_method: payment_method,+ amount: order.total,+ external_data: { 'client_secret' => 'secret_123' })+ end++ before do+ request.headers['X-Spree-Api-Key'] = api_key.token+ request.headers['Authorization'] = "Bearer #{jwt_token}"+ end++ describe 'POST #create' do+ it 'creates a payment session' do+ post :create, params: {+ order_id: order.to_param,+ payment_method_id: payment_method.prefixed_id+ }++ expect(response).to have_http_status(:created)+ expect(json_response['id']).to be_present+ expect(json_response['status']).to eq('pending')+ expect(json_response['payment_method_id']).to eq(payment_method.prefixed_id)+ expect(json_response['order_id']).to eq(order.prefixed_id)+ end++ it 'passes external_data to the gateway' do+ post :create, params: {+ order_id: order.to_param,+ payment_method_id: payment_method.prefixed_id,+ external_data: { channel: 'Web' }+ }++ expect(response).to have_http_status(:created)+ expect(json_response['external_data']).to include('channel' => 'Web')+ end++ context 'with order token (guest)' do+ let(:guest_order) { create(:order_with_line_items, user: nil, store: store, state: 'payment') }++ before { request.headers['Authorization'] = nil }++ it 'creates payment session with valid order token' do+ request.headers['X-Spree-Order-Token'] = guest_order.token+ post :create, params: {+ order_id: guest_order.to_param,+ payment_method_id: payment_method.prefixed_id+ }++ expect(response).to have_http_status(:created)+ end++ it 'returns not found without order token' do+ post :create, params: {+ order_id: guest_order.to_param,+ payment_method_id: payment_method.prefixed_id+ }++ expect(response).to have_http_status(:not_found)+ expect(json_response['error']['code']).to eq('order_not_found')+ end+ end++ context 'error handling' do+ it 'returns not found for non-existent order' do+ post :create, params: {+ order_id: 'invalid',+ payment_method_id: payment_method.prefixed_id+ }++ expect(response).to have_http_status(:not_found)+ expect(json_response['error']['code']).to eq('order_not_found')+ end++ it 'returns not found for non-existent payment method' do+ post :create, params: {+ order_id: order.to_param,+ payment_method_id: 'invalid'+ }++ expect(response).to have_http_status(:not_found)+ expect(json_response['error']['code']).to eq('record_not_found')+ end+ end+ end++ describe 'GET #show' do+ it 'returns a payment session' do+ get :show, params: { order_id: order.to_param, id: payment_session.to_param }++ expect(response).to have_http_status(:ok)+ expect(json_response['id']).to eq(payment_session.prefixed_id)+ expect(json_response['status']).to eq('pending')+ expect(json_response['amount']).to eq(payment_session.amount.to_s)+ expect(json_response['external_data']).to eq({ 'client_secret' => 'secret_123' })+ end++ context 'error handling' do+ it 'returns not found for non-existent payment session' do+ get :show, params: { order_id: order.to_param, id: 'invalid' }++ expect(response).to have_http_status(:not_found)+ expect(json_response['error']['code']).to eq('record_not_found')+ end++ it 'returns not found for payment session from another order' do+ other_order = create(:order_with_line_items, user: user, store: store, state: 'payment')+ other_session = create(:bogus_payment_session,+ order: other_order,+ payment_method: payment_method)++ get :show, params: { order_id: order.to_param, id: other_session.to_param }++ expect(response).to have_http_status(:not_found)+ expect(json_response['error']['code']).to eq('record_not_found')+ end+ end+ end++ describe 'PATCH #update' do+ it 'updates the payment session' do+ patch :update, params: {+ order_id: order.to_param,+ id: payment_session.to_param,+ amount: 50.00+ }++ expect(response).to have_http_status(:ok)+ expect(json_response['id']).to eq(payment_session.prefixed_id)+ expect(json_response['amount']).to eq('50.0')+ end+ end++ describe 'PATCH #complete' do+ it 'completes the payment session' do+ patch :complete, params: {+ order_id: order.to_param,+ id: payment_session.to_param,+ session_result: 'success'+ }++ expect(response).to have_http_status(:ok)+ expect(json_response['status']).to eq('completed')+ end+ end+enddiff --git a/backend/engines/api/spec/integration/spree/api/v3/store/payment_sessions_spec.rb b/backend/engines/api/spec/integration/spree/api/v3/store/payment_sessions_spec.rbnew file mode 100644index 0000000000..8100632dc8--- /dev/null+++ b/backend/engines/api/spec/integration/spree/api/v3/store/payment_sessions_spec.rb@@ -0,0 +1,193 @@+# frozen_string_literal: true++require 'swagger_helper'++RSpec.describe 'Payment Sessions API', type: :request, swagger_doc: 'api-reference/store.yaml' do+ include_context 'API v3 Store'++ let(:order) { create(:order_with_line_items, store: store, user: user, state: 'payment') }+ let(:order_id) { order.to_param }+ let(:payment_method) { create(:bogus_payment_method, stores: [store]) }+ let!(:payment_session) do+ create(:bogus_payment_session,+ order: order,+ payment_method: payment_method,+ amount: order.total,+ external_data: { 'client_secret' => 'secret_123' })+ end++ path '/api/v3/store/orders/{order_id}/payment_sessions' do+ post 'Create payment session' do+ tags 'Payment Sessions'+ consumes 'application/json'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description 'Creates a new payment session for the specified order. Delegates to the payment gateway to initialize a provider-specific session (e.g. Stripe PaymentIntent, Adyen session, PayPal order).'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: 'Authorization', in: :header, type: :string, required: false,+ description: 'Bearer token for authenticated customers'+ parameter name: :order_id, in: :path, type: :string, required: true,+ description: 'Order ID or number'+ parameter name: :order_token, in: :query, type: :string, required: false,+ description: 'Order token for guest access'+ parameter name: :body, in: :body, schema: {+ type: :object,+ properties: {+ payment_method_id: { type: :string, example: 'pm_abc123', description: 'Payment method ID' },+ amount: { type: :string, example: '99.99', description: 'Payment amount (defaults to order total minus store credits)' },+ external_data: { type: :object, description: 'Provider-specific data passed to the gateway' }+ },+ required: %w[payment_method_id]+ }++ response '201', 'payment session created' do+ let(:'x-spree-api-key') { api_key.token }+ let(:'Authorization') { "Bearer #{jwt_token}" }+ let(:body) { { payment_method_id: payment_method.prefixed_id } }++ schema '$ref' => '#/components/schemas/StorePaymentSession'++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['status']).to eq('pending')+ expect(data['payment_method_id']).to eq(payment_method.prefixed_id)+ end+ end++ response '404', 'order not found' do+ let(:'x-spree-api-key') { api_key.token }+ let(:'Authorization') { "Bearer #{jwt_token}" }+ let(:order_id) { 'invalid' }+ let(:body) { { payment_method_id: payment_method.prefixed_id } }++ schema '$ref' => '#/components/schemas/ErrorResponse'+ run_test!+ end+ end+ end++ path '/api/v3/store/orders/{order_id}/payment_sessions/{id}' do+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: 'Authorization', in: :header, type: :string, required: false,+ description: 'Bearer token for authenticated customers'+ parameter name: :order_id, in: :path, type: :string, required: true,+ description: 'Order ID or number'+ parameter name: :id, in: :path, type: :string, required: true,+ description: 'Payment session ID'+ parameter name: :order_token, in: :query, type: :string, required: false,+ description: 'Order token for guest access'++ get 'Get payment session' do+ tags 'Payment Sessions'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description 'Returns a single payment session with its current status and provider data.'++ response '200', 'payment session found' do+ let(:'x-spree-api-key') { api_key.token }+ let(:'Authorization') { "Bearer #{jwt_token}" }+ let(:id) { payment_session.to_param }++ schema '$ref' => '#/components/schemas/StorePaymentSession'++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['id']).to eq(payment_session.prefixed_id)+ expect(data['status']).to eq('pending')+ end+ end++ response '404', 'payment session not found' do+ let(:'x-spree-api-key') { api_key.token }+ let(:'Authorization') { "Bearer #{jwt_token}" }+ let(:id) { 'invalid' }++ schema '$ref' => '#/components/schemas/ErrorResponse'+ run_test!+ end+ end++ patch 'Update payment session' do+ tags 'Payment Sessions'+ consumes 'application/json'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description 'Updates a payment session. Delegates to the payment gateway to sync changes with the provider.'++ parameter name: :body, in: :body, schema: {+ type: :object,+ properties: {+ amount: { type: :string, example: '50.00', description: 'Updated payment amount' },+ external_data: { type: :object, description: 'Provider-specific data to update' }+ }+ }++ response '200', 'payment session updated' do+ let(:'x-spree-api-key') { api_key.token }+ let(:'Authorization') { "Bearer #{jwt_token}" }+ let(:id) { payment_session.to_param }+ let(:body) { { amount: '50.00' } }++ schema '$ref' => '#/components/schemas/StorePaymentSession'++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['id']).to eq(payment_session.prefixed_id)+ end+ end+ end+ end++ path '/api/v3/store/orders/{order_id}/payment_sessions/{id}/complete' do+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: 'Authorization', in: :header, type: :string, required: false,+ description: 'Bearer token for authenticated customers'+ parameter name: :order_id, in: :path, type: :string, required: true,+ description: 'Order ID or number'+ parameter name: :id, in: :path, type: :string, required: true,+ description: 'Payment session ID'+ parameter name: :order_token, in: :query, type: :string, required: false,+ description: 'Order token for guest access'++ patch 'Complete payment session' do+ tags 'Payment Sessions'+ consumes 'application/json'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description 'Completes a payment session by confirming the payment with the provider. This triggers payment capture/authorization and order completion.'++ parameter name: :body, in: :body, schema: {+ type: :object,+ properties: {+ session_result: { type: :string, description: 'Provider-specific session result token' },+ external_data: { type: :object, description: 'Provider-specific completion data' }+ }+ }++ response '200', 'payment session completed' do+ let(:'x-spree-api-key') { api_key.token }+ let(:'Authorization') { "Bearer #{jwt_token}" }+ let(:id) { payment_session.to_param }+ let(:body) { { session_result: 'success' } }++ schema '$ref' => '#/components/schemas/StorePaymentSession'++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['status']).to eq('completed')+ end+ end++ response '404', 'payment session not found' do+ let(:'x-spree-api-key') { api_key.token }+ let(:'Authorization') { "Bearer #{jwt_token}" }+ let(:id) { 'invalid' }+ let(:body) { { session_result: 'success' } }++ schema '$ref' => '#/components/schemas/ErrorResponse'+ run_test!+ end+ end+ end+enddiff --git a/backend/engines/api/spec/serializers/spree/api/v3/payment_session_serializer_spec.rb b/backend/engines/api/spec/serializers/spree/api/v3/payment_session_serializer_spec.rbnew file mode 100644index 0000000000..a5059d481a--- /dev/null+++ b/backend/engines/api/spec/serializers/spree/api/v3/payment_session_serializer_spec.rb@@ -0,0 +1,53 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::PaymentSessionSerializer do+ let(:store) { @default_store }+ let(:order) { create(:order, store: store) }+ let(:payment_method) { create(:bogus_payment_method, stores: [store]) }+ let(:payment_session) do+ create(:bogus_payment_session,+ order: order,+ payment_method: payment_method,+ amount: 99.99,+ currency: 'USD',+ external_data: { 'client_secret' => 'secret_123', 'channel' => 'Web' },+ expires_at: 24.hours.from_now,+ customer_external_id: 'cus_abc123')+ end+ let(:base_params) { { store: store, currency: 'USD' } }++ subject { described_class.new(payment_session, params: base_params).to_h }++ describe 'serialized attributes' do+ it 'includes standard attributes' do+ expect(subject).to include(+ 'id' => payment_session.prefixed_id,+ 'status' => 'pending',+ 'amount' => '99.99',+ 'currency' => 'USD',+ 'customer_external_id' => 'cus_abc123'+ )+ end++ it 'includes external_data' do+ expect(subject['external_data']).to eq({ 'client_secret' => 'secret_123', 'channel' => 'Web' })+ end++ it 'includes prefixed payment_method_id' do+ expect(subject['payment_method_id']).to eq(payment_method.prefixed_id)+ end++ it 'includes prefixed order_id' do+ expect(subject['order_id']).to eq(order.prefixed_id)+ end++ it 'includes timestamp attributes' do+ expect(subject).to have_key('created_at')+ expect(subject).to have_key('updated_at')+ end++ it 'includes expires_at' do+ expect(subject['expires_at']).to be_present+ end+ end+enddiff --git a/backend/engines/api/spec/swagger_helper.rb b/backend/engines/api/spec/swagger_helper.rbindex f5953454c0..e1af691384 100644--- a/backend/engines/api/spec/swagger_helper.rb+++ b/backend/engines/api/spec/swagger_helper.rb@@ -94,6 +94,7 @@ RSpec.configure do |config|{ name: 'Line Items', description: 'Cart item management' },{ name: 'Coupon Codes', description: 'Coupon code and gift card management' },{ name: 'Payments', description: 'Payment processing' },+ { name: 'Payment Sessions', description: 'Provider-agnostic payment session management' },{ name: 'Payment Methods', description: 'Available payment options' },{ name: 'Shipments', description: 'Shipping and delivery' },{ name: 'Customers', description: 'Customer account management' },@@ -105,7 +106,7 @@ RSpec.configure do |config|'x-tagGroups': [{ name: 'Store', tags: %w[Store Countries] },{ name: 'Catalog', tags: %w[Products Taxonomies Taxons] },- { name: 'Checkout', tags: ['Cart', 'Orders', 'Line Items', 'Coupon Codes', 'Payments', 'Payment Methods', 'Shipments'] },+ { name: 'Checkout', tags: ['Cart', 'Orders', 'Line Items', 'Coupon Codes', 'Payments', 'Payment Sessions', 'Payment Methods', 'Shipments'] },{ name: 'Customer', tags: ['Authentication', 'Customers', 'Addresses', 'Credit Cards', 'Wishlists', 'Digitals'] }],components: {diff --git a/backend/engines/core/app/models/spree/gateway/bogus.rb b/backend/engines/core/app/models/spree/gateway/bogus.rbindex 0b6de8749a..5fce1e9539 100644--- a/backend/engines/core/app/models/spree/gateway/bogus.rb+++ b/backend/engines/core/app/models/spree/gateway/bogus.rb@@ -84,6 +84,34 @@ module SpreeCreditCardend+ def payment_session_class+ PaymentSession::Bogus+ end++ def create_payment_session(order:, amount: nil, external_data: {})+ payment_session_class.create(+ order: order,+ payment_method: self,+ amount: amount.presence || order.total_minus_store_credits,+ currency: order.currency,+ status: 'pending',+ external_id: "bogus_#{SecureRandom.hex(12)}",+ external_data: external_data.merge('client_secret' => "bogus_secret_#{SecureRandom.hex(8)}"),+ customer: order.user+ )+ end++ def update_payment_session(payment_session:, amount: nil, external_data: {})+ attrs = {}+ attrs[:amount] = amount if amount.present?+ attrs[:external_data] = payment_session.external_data.merge(external_data) if external_data.present?+ payment_session.update(attrs)+ end++ def complete_payment_session(payment_session:, params: {})+ payment_session.complete+ end+def actions%w(capture void credit)enddiff --git a/backend/engines/core/app/models/spree/order.rb b/backend/engines/core/app/models/spree/order.rbindex 0298f4ec0b..15f4ec72c5 100644--- a/backend/engines/core/app/models/spree/order.rb+++ b/backend/engines/core/app/models/spree/order.rb@@ -122,6 +122,7 @@ module Spreehas_many :state_changes, as: :stateful, class_name: 'Spree::StateChange'has_many :line_items, -> { order(:created_at) }, inverse_of: :order, class_name: 'Spree::LineItem'has_many :payments, class_name: 'Spree::Payment'+ has_many :payment_sessions, inverse_of: :order, class_name: 'Spree::PaymentSession'has_many :return_authorizations, inverse_of: :order, class_name: 'Spree::ReturnAuthorization'has_many :adjustments, -> { order(:created_at) }, as: :adjustable, class_name: 'Spree::Adjustment'enddiff --git a/backend/engines/core/app/models/spree/payment.rb b/backend/engines/core/app/models/spree/payment.rbindex 139f60d15a..1c742db595 100644--- a/backend/engines/core/app/models/spree/payment.rb+++ b/backend/engines/core/app/models/spree/payment.rb@@ -36,6 +36,10 @@ module Spreehas_many :capture_events, class_name: 'Spree::PaymentCaptureEvent'has_many :refunds, inverse_of: :payment+ has_one :payment_session, class_name: 'Spree::PaymentSession',+ foreign_key: :external_id,+ primary_key: :response_code+validates :payment_method, presence: truevalidates :source, presence: true, if: :source_required?validate :payment_method_available_for_order, on: :creatediff --git a/backend/engines/core/app/models/spree/payment_method.rb b/backend/engines/core/app/models/spree/payment_method.rbindex 610c21c7fe..57ffc6a613 100644--- a/backend/engines/core/app/models/spree/payment_method.rb+++ b/backend/engines/core/app/models/spree/payment_method.rb@@ -47,6 +47,32 @@ module Spreeraise ::NotImplementedError, 'You must implement payment_source_class method for this gateway.'end+ # The class used for payment sessions with this payment method.+ # Override in gateway subclasses to provide a provider-specific session class+ # that inherits from Spree::PaymentSession (STI).+ # nil means the payment method doesn't support payment sessions.+ def payment_session_class+ nil+ end++ # Creates a payment session via the provider.+ # Override in gateway subclasses to implement provider-specific session creation.+ def create_payment_session(order:, amount: nil, external_data: {})+ raise ::NotImplementedError, 'You must implement create_payment_session method for this gateway.'+ end++ # Updates an existing payment session via the provider.+ # Override in gateway subclasses to implement provider-specific session updates.+ def update_payment_session(payment_session:, amount: nil, external_data: {})+ raise ::NotImplementedError, 'You must implement update_payment_session method for this gateway.'+ end++ # Completes a payment session via the provider.+ # Override in gateway subclasses to implement provider-specific session completion.+ def complete_payment_session(payment_session:, params: {})+ raise ::NotImplementedError, 'You must implement complete_payment_session method for this gateway.'+ end+def method_typetype.demodulize.downcaseenddiff --git a/backend/engines/core/app/models/spree/payment_session.rb b/backend/engines/core/app/models/spree/payment_session.rbnew file mode 100644index 0000000000..b7f1f89161--- /dev/null+++ b/backend/engines/core/app/models/spree/payment_session.rb@@ -0,0 +1,79 @@+module Spree+ class PaymentSession < Spree.base_class+ has_prefix_id :ps++ acts_as_paranoid++ include Spree::Metafields++ belongs_to :order, class_name: 'Spree::Order'+ belongs_to :payment_method, class_name: 'Spree::PaymentMethod'+ belongs_to :customer, class_name: Spree.user_class.to_s, optional: true++ has_one :payment, class_name: 'Spree::Payment',+ foreign_key: :response_code,+ primary_key: :external_id++ validates :order, :payment_method, :external_id, :status, :currency, presence: true+ validates :external_id, uniqueness: { scope: [:order_id, :payment_method_id] }+ validates :amount, presence: true, numericality: { greater_than: 0 }++ state_machine :status, initial: :pending do+ state :pending+ state :processing+ state :completed+ state :failed+ state :canceled+ state :expired++ event :process do+ transition pending: :processing+ end++ event :complete do+ transition [:pending, :processing] => :completed+ end++ event :fail do+ transition [:pending, :processing] => :failed+ end++ event :cancel do+ transition [:pending, :processing] => :canceled+ end++ event :expire do+ transition [:pending, :processing] => :expired+ end+ end++ scope :not_expired, -> { where('expires_at IS NULL OR expires_at > ?', Time.current) }+ scope :active, -> { not_expired.where(status: %w[pending processing]) }++ before_validation :set_defaults_from_order, on: :create++ delegate :store, to: :order++ def amount_in_cents+ money.cents+ end++ def money+ @money ||= Spree::Money.new(amount, currency: currency)+ end++ def expired?+ expires_at.present? && expires_at <= Time.current+ end++ private++ def set_defaults_from_order+ return unless order++ self.amount ||= order.total_minus_store_credits if amount.blank? || amount.zero?+ self.currency ||= order.currency+ self.customer ||= order.user+ end+ end+enddiff --git a/backend/engines/core/app/models/spree/payment_session/bogus.rb b/backend/engines/core/app/models/spree/payment_session/bogus.rbnew file mode 100644index 0000000000..716e63f3e2--- /dev/null+++ b/backend/engines/core/app/models/spree/payment_session/bogus.rb@@ -0,0 +1,4 @@+module Spree+ class PaymentSession::Bogus < PaymentSession+ end+enddiff --git a/backend/engines/core/db/migrate/20260213000000_create_spree_payment_sessions.rb b/backend/engines/core/db/migrate/20260213000000_create_spree_payment_sessions.rbnew file mode 100644index 0000000000..8b6dce810b--- /dev/null+++ b/backend/engines/core/db/migrate/20260213000000_create_spree_payment_sessions.rb@@ -0,0 +1,27 @@+class CreateSpreePaymentSessions < ActiveRecord::Migration[7.2]+ def change+ create_table :spree_payment_sessions do |t|+ t.string :type, null: false, index: true+ t.references :order, null: false, index: true+ t.references :payment_method, null: false, index: true+ t.references :customer, index: true+ t.decimal :amount, precision: 10, scale: 2, null: false+ t.string :currency, null: false+ t.string :status, null: false, index: true+ t.string :external_id, null: false+ if t.respond_to? :jsonb+ t.jsonb :external_data, default: {}+ else+ t.json :external_data, default: {}+ end+ t.datetime :expires_at, index: true+ t.string :customer_external_id+ t.datetime :deleted_at, index: true+ t.timestamps+ end++ add_index :spree_payment_sessions, [:order_id, :payment_method_id, :external_id],+ unique: true, name: 'idx_payment_sessions_order_method_external'+ add_index :spree_payment_sessions, :external_id+ end+enddiff --git a/backend/engines/core/lib/spree/permitted_attributes.rb b/backend/engines/core/lib/spree/permitted_attributes.rbindex 4aceb4264f..7d93621516 100644--- a/backend/engines/core/lib/spree/permitted_attributes.rb+++ b/backend/engines/core/lib/spree/permitted_attributes.rb@@ -35,6 +35,7 @@ module Spree:page_section_attributes,:payment_attributes,:payment_method_attributes,+ :payment_session_attributes,:policy_attributes,:post_attributes,:post_category_attributes,@@ -165,6 +166,8 @@ module Spree@@payment_method_attributes = [:name, :type, :description, :active, :display_on, :auto_capture, :position]+ @@payment_session_attributes = [:amount, :payment_method_id, { external_data: {} }]+@@policy_attributes = [:name, :slug, :body]@@post_attributes = [:title, :meta_title, :meta_description, :slug, :author_id, :post_category_id, :published_at, :content, :excerpt, :image, tag_list: []]diff --git a/backend/engines/core/lib/spree/testing_support/factories/payment_method_factory.rb b/backend/engines/core/lib/spree/testing_support/factories/payment_method_factory.rbindex 1cb986083d..759fa8fa6f 100644--- a/backend/engines/core/lib/spree/testing_support/factories/payment_method_factory.rb+++ b/backend/engines/core/lib/spree/testing_support/factories/payment_method_factory.rb@@ -42,4 +42,6 @@ FactoryBot.define dotype { 'Spree::Gateway::CustomPaymentSourceMethod' }name { 'Custom' }end++ factory :bogus_payment_method, parent: :credit_card_payment_methodenddiff --git a/backend/engines/core/lib/spree/testing_support/factories/payment_session_factory.rb b/backend/engines/core/lib/spree/testing_support/factories/payment_session_factory.rbnew file mode 100644index 0000000000..eac689e577--- /dev/null+++ b/backend/engines/core/lib/spree/testing_support/factories/payment_session_factory.rb@@ -0,0 +1,47 @@+FactoryBot.define do+ factory :payment_session, class: 'Spree::PaymentSession' do+ order+ payment_method { create(:credit_card_payment_method, stores: [order.store]) }+ amount { order.total }+ currency { order.currency }+ status { 'pending' }+ external_id { "ps_test_#{SecureRandom.hex(12)}" }+ external_data { {} }++ trait :processing do+ status { 'processing' }+ end++ trait :completed do+ status { 'completed' }+ end++ trait :failed do+ status { 'failed' }+ end++ trait :canceled do+ status { 'canceled' }+ end++ trait :expired do+ status { 'expired' }+ expires_at { 1.hour.ago }+ end++ trait :with_expiration do+ expires_at { 24.hours.from_now }+ end++ trait :with_customer do+ customer { order.user || create(:user) }+ end++ factory :bogus_payment_session, class: 'Spree::PaymentSession::Bogus' do+ type { 'Spree::PaymentSession::Bogus' }+ payment_method { create(:bogus_payment_method, stores: [order.store]) }+ external_id { "bogus_#{SecureRandom.hex(12)}" }+ external_data { { 'client_secret' => "bogus_secret_#{SecureRandom.hex(8)}" } }+ end+ end+enddiff --git a/packages/sdk/src/types/generated/StorePaymentSession.ts b/packages/sdk/src/types/generated/StorePaymentSession.tsnew file mode 100644index 0000000000..f87d74e663--- /dev/null+++ b/packages/sdk/src/types/generated/StorePaymentSession.ts@@ -0,0 +1,23 @@+// Typelizer digest placeholder+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.+import type {StorePaymentMethod, StorePayment} from '@/types'++type StorePaymentSession = {+ id: string;+ status: string;+ amount: string;+ currency: string;+ external_id: string;+ external_data: Record<string, unknown>;+ expires_at: string | null;+ customer_external_id: string | null;+ payment_method_id: string;+ order_id: string;+ created_at: string;+ updated_at: string;+ payment_method: StorePaymentMethod;+ payment: StorePayment;+}++export default StorePaymentSession;diff --git a/packages/sdk/src/types/generated/index.ts b/packages/sdk/src/types/generated/index.tsindex cbd0254677..0d7d07b73f 100644--- a/packages/sdk/src/types/generated/index.ts+++ b/packages/sdk/src/types/generated/index.ts@@ -25,6 +25,7 @@ export type { default as StoreOrderPromotion } from './StoreOrderPromotion'export type { default as StoreOrder } from './StoreOrder'export type { default as StorePaymentMethod } from './StorePaymentMethod'export type { default as StorePayment } from './StorePayment'+export type { default as StorePaymentSession } from './StorePaymentSession'export type { default as StorePrice } from './StorePrice'export type { default as StoreProduct } from './StoreProduct'export type { default as StoreShipment } from './StoreShipment'