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.

Add Payment Sessions to SDK and Next.js packages

Damian Legawiec7d659eab6c08
diff --git a/packages/next/.changeset/add-payment-sessions.md b/packages/next/.changeset/add-payment-sessions.md
new file mode 100644
index 0000000000..edc1032b42
--- /dev/null
+++ b/packages/next/.changeset/add-payment-sessions.md
@@ -0,0 +1,5 @@
+---
+"@spree/next": minor
+---
+
+Add Payment Sessions server actions: `createPaymentSession`, `getPaymentSession`, `updatePaymentSession`, and `completePaymentSession`. Re-export `StorePaymentSession` and related param types from `@spree/sdk`.
diff --git a/packages/next/README.md b/packages/next/README.md
index fcb343631d..cf26759bdf 100644
--- a/packages/next/README.md
+++ b/packages/next/README.md
@@ -198,6 +198,32 @@ const orders = await listOrders();
const order = await getOrder(orderId);
```
+### Payment Sessions
+
+```typescript
+import {
+ createPaymentSession,
+ getPaymentSession,
+ updatePaymentSession,
+ completePaymentSession,
+} from '@spree/next';
+
+// Create a payment session (initializes provider-specific session)
+const session = await createPaymentSession(orderId, { payment_method_id: 'pm_123' });
+
+// Access provider data (e.g., Stripe client secret)
+const clientSecret = session.external_data.client_secret;
+
+// Get a payment session
+const session = await getPaymentSession(orderId, sessionId);
+
+// Update a payment session
+await updatePaymentSession(orderId, sessionId, { amount: '50.00' });
+
+// Complete a payment session (confirms payment with provider)
+await completePaymentSession(orderId, sessionId, { session_result: 'success' });
+```
+
### Credit Cards & Gift Cards
```typescript
@@ -229,6 +255,7 @@ import type {
StoreProduct,
StoreOrder,
StoreLineItem,
+ StorePaymentSession,
StoreTaxon,
PaginatedResponse,
SpreeError,
diff --git a/packages/next/src/actions/payment-sessions.ts b/packages/next/src/actions/payment-sessions.ts
new file mode 100644
index 0000000000..ccfcf89bf0
--- /dev/null
+++ b/packages/next/src/actions/payment-sessions.ts
@@ -0,0 +1,72 @@
+'use server';
+
+import { revalidateTag } from 'next/cache';
+import type {
+ StorePaymentSession,
+ CreatePaymentSessionParams,
+ UpdatePaymentSessionParams,
+ CompletePaymentSessionParams,
+} from '@spree/sdk';
+import { getClient } from '../config';
+import { getCartToken, getAccessToken } from '../cookies';
+
+async function getCheckoutOptions() {
+ const orderToken = await getCartToken();
+ const token = await getAccessToken();
+ return { orderToken, token };
+}
+
+/**
+ * Create a payment session for an order.
+ * Delegates to the payment gateway to initialize a provider-specific session.
+ */
+export async function createPaymentSession(
+ orderId: string,
+ params: CreatePaymentSessionParams
+): Promise<StorePaymentSession> {
+ const options = await getCheckoutOptions();
+ const result = await getClient().store.orders.paymentSessions.create(orderId, params, options);
+ revalidateTag('checkout');
+ return result;
+}
+
+/**
+ * Get a payment session by ID.
+ */
+export async function getPaymentSession(
+ orderId: string,
+ sessionId: string
+): Promise<StorePaymentSession> {
+ const options = await getCheckoutOptions();
+ return getClient().store.orders.paymentSessions.get(orderId, sessionId, options);
+}
+
+/**
+ * Update a payment session.
+ * Delegates to the payment gateway to sync changes with the provider.
+ */
+export async function updatePaymentSession(
+ orderId: string,
+ sessionId: string,
+ params: UpdatePaymentSessionParams
+): Promise<StorePaymentSession> {
+ const options = await getCheckoutOptions();
+ const result = await getClient().store.orders.paymentSessions.update(orderId, sessionId, params, options);
+ revalidateTag('checkout');
+ return result;
+}
+
+/**
+ * Complete a payment session.
+ * Confirms the payment with the provider, triggering capture/authorization.
+ */
+export async function completePaymentSession(
+ orderId: string,
+ sessionId: string,
+ params?: CompletePaymentSessionParams
+): Promise<StorePaymentSession> {
+ const options = await getCheckoutOptions();
+ const result = await getClient().store.orders.paymentSessions.complete(orderId, sessionId, params, options);
+ revalidateTag('checkout');
+ return result;
+}
diff --git a/packages/next/src/index.ts b/packages/next/src/index.ts
index 1acf5cf47e..ff694e0c8c 100644
--- a/packages/next/src/index.ts
+++ b/packages/next/src/index.ts
@@ -52,6 +52,13 @@ export { listOrders, getOrder } from './actions/orders';
export { listCreditCards, deleteCreditCard } from './actions/credit-cards';
export { listGiftCards, getGiftCard } from './actions/gift-cards';
+export {
+ createPaymentSession,
+ getPaymentSession,
+ updatePaymentSession,
+ completePaymentSession,
+} from './actions/payment-sessions';
+
// Re-export commonly used SDK types for convenience
export type {
StoreProduct,
@@ -70,6 +77,7 @@ export type {
StoreShippingRate,
StorePayment,
StorePaymentMethod,
+ StorePaymentSession,
StoreImage,
StoreOptionType,
StoreOptionValue,
@@ -78,5 +86,8 @@ export type {
PaginatedResponse,
AddressParams,
ProductFiltersResponse,
+ CreatePaymentSessionParams,
+ UpdatePaymentSessionParams,
+ CompletePaymentSessionParams,
SpreeError,
} from '@spree/sdk';
diff --git a/packages/next/tests/actions/payment-sessions.test.ts b/packages/next/tests/actions/payment-sessions.test.ts
new file mode 100644
index 0000000000..e511b1eec9
--- /dev/null
+++ b/packages/next/tests/actions/payment-sessions.test.ts
@@ -0,0 +1,118 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { mockCookieStore } from '../setup';
+import { initSpreeNext, resetClient } from '../../src/config';
+
+const mockClient = {
+ store: {
+ orders: {
+ paymentSessions: {
+ create: vi.fn(),
+ get: vi.fn(),
+ update: vi.fn(),
+ complete: vi.fn(),
+ },
+ },
+ },
+};
+
+vi.mock('@spree/sdk', () => ({
+ createSpreeClient: vi.fn(() => mockClient),
+}));
+
+import {
+ createPaymentSession,
+ getPaymentSession,
+ updatePaymentSession,
+ completePaymentSession,
+} from '../../src/actions/payment-sessions';
+import { revalidateTag } from 'next/cache';
+
+describe('payment session actions', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetClient();
+ initSpreeNext({ baseUrl: 'https://api.test.com', publishableKey: 'pk_test' });
+ mockCookieStore.get
+ .mockReturnValueOnce({ value: 'order_token_123' })
+ .mockReturnValueOnce({ value: 'jwt_token_abc' });
+ });
+
+ describe('createPaymentSession', () => {
+ it('creates a payment session and revalidates checkout', async () => {
+ const mockSession = { id: 'ps_1', status: 'pending', payment_method_id: 'pm_1' };
+ mockClient.store.orders.paymentSessions.create.mockResolvedValue(mockSession);
+
+ const result = await createPaymentSession('order_1', { payment_method_id: 'pm_1' });
+ expect(result).toEqual(mockSession);
+ expect(mockClient.store.orders.paymentSessions.create).toHaveBeenCalledWith(
+ 'order_1',
+ { payment_method_id: 'pm_1' },
+ { orderToken: 'order_token_123', token: 'jwt_token_abc' }
+ );
+ expect(revalidateTag).toHaveBeenCalledWith('checkout');
+ });
+ });
+
+ describe('getPaymentSession', () => {
+ it('returns a payment session by ID', async () => {
+ const mockSession = { id: 'ps_1', status: 'pending', amount: '99.99' };
+ mockClient.store.orders.paymentSessions.get.mockResolvedValue(mockSession);
+
+ const result = await getPaymentSession('order_1', 'ps_1');
+ expect(result).toEqual(mockSession);
+ expect(mockClient.store.orders.paymentSessions.get).toHaveBeenCalledWith(
+ 'order_1',
+ 'ps_1',
+ { orderToken: 'order_token_123', token: 'jwt_token_abc' }
+ );
+ });
+ });
+
+ describe('updatePaymentSession', () => {
+ it('updates a payment session and revalidates checkout', async () => {
+ const mockSession = { id: 'ps_1', status: 'pending', amount: '50.00' };
+ mockClient.store.orders.paymentSessions.update.mockResolvedValue(mockSession);
+
+ const result = await updatePaymentSession('order_1', 'ps_1', { amount: '50.00' });
+ expect(result).toEqual(mockSession);
+ expect(mockClient.store.orders.paymentSessions.update).toHaveBeenCalledWith(
+ 'order_1',
+ 'ps_1',
+ { amount: '50.00' },
+ { orderToken: 'order_token_123', token: 'jwt_token_abc' }
+ );
+ expect(revalidateTag).toHaveBeenCalledWith('checkout');
+ });
+ });
+
+ describe('completePaymentSession', () => {
+ it('completes a payment session and revalidates checkout', async () => {
+ const mockSession = { id: 'ps_1', status: 'completed' };
+ mockClient.store.orders.paymentSessions.complete.mockResolvedValue(mockSession);
+
+ const result = await completePaymentSession('order_1', 'ps_1', { session_result: 'success' });
+ expect(result).toEqual(mockSession);
+ expect(mockClient.store.orders.paymentSessions.complete).toHaveBeenCalledWith(
+ 'order_1',
+ 'ps_1',
+ { session_result: 'success' },
+ { orderToken: 'order_token_123', token: 'jwt_token_abc' }
+ );
+ expect(revalidateTag).toHaveBeenCalledWith('checkout');
+ });
+
+ it('completes without params', async () => {
+ const mockSession = { id: 'ps_1', status: 'completed' };
+ mockClient.store.orders.paymentSessions.complete.mockResolvedValue(mockSession);
+
+ const result = await completePaymentSession('order_1', 'ps_1');
+ expect(result).toEqual(mockSession);
+ expect(mockClient.store.orders.paymentSessions.complete).toHaveBeenCalledWith(
+ 'order_1',
+ 'ps_1',
+ undefined,
+ { orderToken: 'order_token_123', token: 'jwt_token_abc' }
+ );
+ });
+ });
+});
diff --git a/packages/sdk/.changeset/add-payment-sessions.md b/packages/sdk/.changeset/add-payment-sessions.md
new file mode 100644
index 0000000000..9b0eb74fe5
--- /dev/null
+++ b/packages/sdk/.changeset/add-payment-sessions.md
@@ -0,0 +1,5 @@
+---
+"@spree/sdk": minor
+---
+
+Add Payment Sessions support: `client.store.orders.paymentSessions` with `create`, `get`, `update`, and `complete` methods. Add `session_required` field to `StorePaymentMethod` type. Add `CreatePaymentSessionParams`, `UpdatePaymentSessionParams`, and `CompletePaymentSessionParams` types.
diff --git a/packages/sdk/README.md b/packages/sdk/README.md
index 9eb39b5c5e..adfb914616 100644
--- a/packages/sdk/README.md
+++ b/packages/sdk/README.md
@@ -325,6 +325,44 @@ const payments = await client.store.orders.payments.list(cart.id, options);
const payment = await client.store.orders.payments.get(cart.id, paymentId, options);
```
+### Payment Sessions
+
+Payment sessions provide a unified, provider-agnostic interface for payment processing. They work with any payment gateway (Stripe, Adyen, PayPal, etc.) through a single API.
+
+```typescript
+const options = { orderToken: cart.token };
+
+// Create a payment session (initializes a session with the payment gateway)
+const session = await client.store.orders.paymentSessions.create(cart.id, {
+ payment_method_id: 'pm_xxx',
+ amount: '99.99', // Optional, defaults to order total
+ external_data: { // Optional, provider-specific data
+ return_url: 'https://mystore.com/checkout/complete',
+ },
+}, options);
+
+// The session contains provider-specific data (e.g., Stripe client_secret)
+console.log(session.external_data.client_secret);
+
+// Get a payment session
+const existing = await client.store.orders.paymentSessions.get(
+ cart.id, session.id, options
+);
+
+// Update a payment session (e.g., after order total changes)
+await client.store.orders.paymentSessions.update(cart.id, session.id, {
+ amount: '149.99',
+}, options);
+
+// Complete the payment session (after customer confirms payment on the frontend)
+const completed = await client.store.orders.paymentSessions.complete(
+ cart.id, session.id,
+ { session_result: 'success' },
+ options
+);
+console.log(completed.status); // 'completed'
+```
+
### Geography
```typescript
@@ -456,6 +494,7 @@ The SDK uses a resource builder pattern for nested resources:
| `store.orders` | `lineItems` | `create`, `update`, `delete` |
| `store.orders` | `payments` | `list`, `get` |
| `store.orders` | `paymentMethods` | `list` |
+| `store.orders` | `paymentSessions` | `create`, `get`, `update`, `complete` |
| `store.orders` | `shipments` | `list`, `update` |
| `store.orders` | `couponCodes` | `apply`, `remove` |
| `store.customer` | `addresses` | `list`, `get`, `create`, `update`, `delete`, `markAsDefault` |
@@ -554,6 +593,7 @@ The SDK exports all Store API types:
### Commerce Types
- `StorePayment` - Payment record
- `StorePaymentMethod` - Payment method
+- `StorePaymentSession` - Provider-agnostic payment session
- `StoreShipment` - Shipment record
- `StoreShippingRate` - Shipping rate option
- `StoreShippingMethod` - Shipping method
@@ -583,6 +623,9 @@ The SDK exports all Store API types:
- `PaginatedResponse<T>` - Paginated API response
- `AuthTokens` - JWT tokens from login
- `AddressParams` - Address input parameters
+- `CreatePaymentSessionParams` - Payment session creation parameters
+- `UpdatePaymentSessionParams` - Payment session update parameters
+- `CompletePaymentSessionParams` - Payment session completion parameters
- `ProductFiltersResponse` - Product filters response
## Custom Fetch
diff --git a/packages/sdk/src/store-client.ts b/packages/sdk/src/store-client.ts
index b1ca286114..b36b6d0e2a 100644
--- a/packages/sdk/src/store-client.ts
+++ b/packages/sdk/src/store-client.ts
@@ -14,6 +14,9 @@ import type {
UpdateLineItemParams,
UpdateOrderParams,
AddressParams,
+ CreatePaymentSessionParams,
+ UpdatePaymentSessionParams,
+ CompletePaymentSessionParams,
StoreCreditCard,
StoreGiftCard,
StoreProduct,
@@ -24,6 +27,7 @@ import type {
StoreTaxon,
StorePayment,
StorePaymentMethod,
+ StorePaymentSession,
StoreShipment,
StoreStore,
StoreWishlist,
@@ -433,6 +437,72 @@ export class StoreClient {
),
},
+ /**
+ * Nested resource: Payment sessions
+ */
+ paymentSessions: {
+ /**
+ * Create a payment session for an order
+ * Delegates to the payment gateway to initialize a provider-specific session
+ */
+ create: (
+ orderId: string,
+ params: CreatePaymentSessionParams,
+ options?: RequestOptions
+ ): Promise<StorePaymentSession> =>
+ this.request<StorePaymentSession>(
+ 'POST',
+ `/orders/${orderId}/payment_sessions`,
+ { ...options, body: params }
+ ),
+
+ /**
+ * Get a payment session by ID
+ */
+ get: (
+ orderId: string,
+ sessionId: string,
+ options?: RequestOptions
+ ): Promise<StorePaymentSession> =>
+ this.request<StorePaymentSession>(
+ 'GET',
+ `/orders/${orderId}/payment_sessions/${sessionId}`,
+ options
+ ),
+
+ /**
+ * Update a payment session
+ * Delegates to the payment gateway to sync changes with the provider
+ */
+ update: (
+ orderId: string,
+ sessionId: string,
+ params: UpdatePaymentSessionParams,
+ options?: RequestOptions
+ ): Promise<StorePaymentSession> =>
+ this.request<StorePaymentSession>(
+ 'PATCH',
+ `/orders/${orderId}/payment_sessions/${sessionId}`,
+ { ...options, body: params }
+ ),
+
+ /**
+ * Complete a payment session
+ * Confirms the payment with the provider, triggering capture/authorization
+ */
+ complete: (
+ orderId: string,
+ sessionId: string,
+ params?: CompletePaymentSessionParams,
+ options?: RequestOptions
+ ): Promise<StorePaymentSession> =>
+ this.request<StorePaymentSession>(
+ 'PATCH',
+ `/orders/${orderId}/payment_sessions/${sessionId}/complete`,
+ { ...options, body: params }
+ ),
+ },
+
/**
* Nested resource: Coupon codes
*/
diff --git a/packages/sdk/src/types/index.ts b/packages/sdk/src/types/index.ts
index d83f6d6545..3fa7c2361d 100644
--- a/packages/sdk/src/types/index.ts
+++ b/packages/sdk/src/types/index.ts
@@ -115,6 +115,23 @@ export interface UpdateOrderParams {
ship_address?: AddressParams;
}
+// Payment Sessions
+export interface CreatePaymentSessionParams {
+ payment_method_id: string;
+ amount?: string;
+ external_data?: Record<string, unknown>;
+}
+
+export interface UpdatePaymentSessionParams {
+ amount?: string;
+ external_data?: Record<string, unknown>;
+}
+
+export interface CompletePaymentSessionParams {
+ session_result?: string;
+ external_data?: Record<string, unknown>;
+}
+
// Product Filters types
export interface FilterOption {
id: string;
diff --git a/packages/sdk/tests/mocks/handlers.ts b/packages/sdk/tests/mocks/handlers.ts
index 1b1b237638..a906a9c0d2 100644
--- a/packages/sdk/tests/mocks/handlers.ts
+++ b/packages/sdk/tests/mocks/handlers.ts
@@ -217,6 +217,79 @@ export const handlers = [
HttpResponse.json({ data: [], meta: paginationMeta })
),
+ // Payment Sessions
+ http.post(`${API_PREFIX}/orders/:orderId/payment_sessions`, () =>
+ HttpResponse.json({
+ id: 'ps_1',
+ status: 'pending',
+ amount: '99.99',
+ currency: 'USD',
+ external_id: 'bogus_abc123',
+ external_data: { client_secret: 'bogus_secret_xyz' },
+ expires_at: null,
+ customer_external_id: null,
+ payment_method_id: 'pm_1',
+ order_id: 'order_1',
+ created_at: '2026-02-13T00:00:00.000Z',
+ updated_at: '2026-02-13T00:00:00.000Z',
+ payment_method: { id: 'pm_1', name: 'Credit Card', description: null, type: 'Spree::Gateway::Bogus' },
+ }, { status: 201 })
+ ),
+
+ http.get(`${API_PREFIX}/orders/:orderId/payment_sessions/:id`, () =>
+ HttpResponse.json({
+ id: 'ps_1',
+ status: 'pending',
+ amount: '99.99',
+ currency: 'USD',
+ external_id: 'bogus_abc123',
+ external_data: { client_secret: 'bogus_secret_xyz' },
+ expires_at: null,
+ customer_external_id: null,
+ payment_method_id: 'pm_1',
+ order_id: 'order_1',
+ created_at: '2026-02-13T00:00:00.000Z',
+ updated_at: '2026-02-13T00:00:00.000Z',
+ payment_method: { id: 'pm_1', name: 'Credit Card', description: null, type: 'Spree::Gateway::Bogus' },
+ })
+ ),
+
+ http.patch(`${API_PREFIX}/orders/:orderId/payment_sessions/:id/complete`, () =>
+ HttpResponse.json({
+ id: 'ps_1',
+ status: 'completed',
+ amount: '99.99',
+ currency: 'USD',
+ external_id: 'bogus_abc123',
+ external_data: { client_secret: 'bogus_secret_xyz' },
+ expires_at: null,
+ customer_external_id: null,
+ payment_method_id: 'pm_1',
+ order_id: 'order_1',
+ created_at: '2026-02-13T00:00:00.000Z',
+ updated_at: '2026-02-13T00:00:00.000Z',
+ payment_method: { id: 'pm_1', name: 'Credit Card', description: null, type: 'Spree::Gateway::Bogus' },
+ })
+ ),
+
+ http.patch(`${API_PREFIX}/orders/:orderId/payment_sessions/:id`, () =>
+ HttpResponse.json({
+ id: 'ps_1',
+ status: 'pending',
+ amount: '50.00',
+ currency: 'USD',
+ external_id: 'bogus_abc123',
+ external_data: { client_secret: 'bogus_secret_xyz' },
+ expires_at: null,
+ customer_external_id: null,
+ payment_method_id: 'pm_1',
+ order_id: 'order_1',
+ created_at: '2026-02-13T00:00:00.000Z',
+ updated_at: '2026-02-13T00:00:00.000Z',
+ payment_method: { id: 'pm_1', name: 'Credit Card', description: null, type: 'Spree::Gateway::Bogus' },
+ })
+ ),
+
// Coupon Codes
http.post(`${API_PREFIX}/orders/:orderId/coupon_codes`, () =>
HttpResponse.json(fixtures.order)
diff --git a/packages/sdk/tests/payment-sessions.test.ts b/packages/sdk/tests/payment-sessions.test.ts
new file mode 100644
index 0000000000..f7de28e4c2
--- /dev/null
+++ b/packages/sdk/tests/payment-sessions.test.ts
@@ -0,0 +1,84 @@
+import { describe, it, expect, beforeAll } from 'vitest';
+import { createTestClient } from './helpers';
+import type { SpreeClient } from '../src';
+
+describe('paymentSessions', () => {
+ let client: SpreeClient;
+ beforeAll(() => { client = createTestClient(); });
+ const opts = { token: 'user-jwt' };
+
+ describe('create', () => {
+ it('creates a payment session', async () => {
+ const result = await client.store.orders.paymentSessions.create(
+ 'order_1',
+ { payment_method_id: 'pm_1' },
+ opts
+ );
+ expect(result.id).toBe('ps_1');
+ expect(result.status).toBe('pending');
+ expect(result.payment_method_id).toBe('pm_1');
+ expect(result.order_id).toBe('order_1');
+ expect(result.external_data).toHaveProperty('client_secret');
+ });
+
+ it('accepts optional amount and external_data', async () => {
+ const result = await client.store.orders.paymentSessions.create(
+ 'order_1',
+ { payment_method_id: 'pm_1', amount: '50.00', external_data: { channel: 'Web' } },
+ opts
+ );
+ expect(result.id).toBe('ps_1');
+ });
+ });
+
+ describe('get', () => {
+ it('returns a payment session by ID', async () => {
+ const result = await client.store.orders.paymentSessions.get(
+ 'order_1',
+ 'ps_1',
+ opts
+ );
+ expect(result.id).toBe('ps_1');
+ expect(result.status).toBe('pending');
+ expect(result.amount).toBe('99.99');
+ expect(result.currency).toBe('USD');
+ expect(result.external_id).toBe('bogus_abc123');
+ });
+ });
+
+ describe('update', () => {
+ it('updates a payment session', async () => {
+ const result = await client.store.orders.paymentSessions.update(
+ 'order_1',
+ 'ps_1',
+ { amount: '50.00' },
+ opts
+ );
+ expect(result.id).toBe('ps_1');
+ expect(result.amount).toBe('50.00');
+ });
+ });
+
+ describe('complete', () => {
+ it('completes a payment session', async () => {
+ const result = await client.store.orders.paymentSessions.complete(
+ 'order_1',
+ 'ps_1',
+ { session_result: 'success' },
+ opts
+ );
+ expect(result.id).toBe('ps_1');
+ expect(result.status).toBe('completed');
+ });
+
+ it('completes without params', async () => {
+ const result = await client.store.orders.paymentSessions.complete(
+ 'order_1',
+ 'ps_1',
+ undefined,
+ opts
+ );
+ expect(result.status).toBe('completed');
+ });
+ });
+});