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.

Unified Carts API (#13770)

Damian Legawiec98a72be6c18b
diff --git a/CLAUDE.md b/CLAUDE.md
index 611617ba26..39b3ec0b53 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -270,9 +270,9 @@ We use [typelizer](https://github.com/skryukov/typelizer) to generate TypeScript
### API Authentication
- **Publishable API keys** (`spree_pk_xxx`) — used for Store API, passed via `Authorization: Bearer` header
-- **Secret API keys** (`spree_sk_xxx`) — used for Admin API, passed via `Authorization: Bearer` header
+- **Secret API keys** (`sk_xxx`) — used for Admin API, passed via `Authorization: Bearer` header
- **User authentication** — JWT tokens, passed via `Authorization: Bearer <token>` header
-- **Guest cart tokens** — passed via `X-Spree-Order-Token` header for guest checkout
+- **Guest cart tokens** — passed via `X-Spree-Token` header for guest checkout
```ruby
# Creating API keys
diff --git a/docs/api-reference/store-api/authentication.mdx b/docs/api-reference/store-api/authentication.mdx
index 43047ab2da..b9a27166c3 100644
--- a/docs/api-reference/store-api/authentication.mdx
+++ b/docs/api-reference/store-api/authentication.mdx
@@ -138,19 +138,19 @@ curl -X POST 'http://localhost:3000/api/v3/store/auth/refresh' \
For guest checkout flows, use the **order token** returned when creating a cart. This allows unauthenticated users to manage their cart and complete checkout.
-Pass the token via the `X-Spree-Order-Token` header or `order_token` query parameter:
+Pass the token via the `x-spree-token` header:
<CodeGroup>
```typescript SDK
// Create a cart (guest)
-const cart = await client.cart.create()
+const cart = await client.carts.create()
-// Use orderToken for all cart operations
-const options = { orderToken: cart.token }
+// Use spreeToken for all guest cart operations
+const options = { spreeToken: cart.token }
// Add items
-await client.orders.lineItems.create(cart.id, {
+await client.carts.items.create(cart.id, {
variant_id: 'variant_abc123',
quantity: 1,
}, options)
@@ -158,13 +158,13 @@ await client.orders.lineItems.create(cart.id, {
```bash cURL
# Create a cart
-curl -X POST 'http://localhost:3000/api/v3/store/cart' \
+curl -X POST 'http://localhost:3000/api/v3/store/carts' \
-H 'X-Spree-Api-Key: spree_pk_xxx'
# Use the returned token for cart operations
-curl -X POST 'http://localhost:3000/api/v3/store/orders/or_xxx/line_items' \
+curl -X POST 'http://localhost:3000/api/v3/store/carts/cart_xxx/items' \
-H 'X-Spree-Api-Key: spree_pk_xxx' \
- -H 'X-Spree-Order-Token: <order_token>' \
+ -H 'X-Spree-Token: <order_token>' \
-H 'Content-Type: application/json' \
-d '{"variant_id": "variant_abc123", "quantity": 1}'
```
@@ -178,17 +178,17 @@ After a guest user logs in, you can associate their guest cart with their accoun
<CodeGroup>
```typescript SDK
-await client.cart.associate({
+await client.carts.associate(cart.id, {
token: jwtToken,
- orderToken: cart.token,
+ spreeToken: cart.token,
})
```
```bash cURL
-curl -X PATCH 'http://localhost:3000/api/v3/store/cart/associate' \
+curl -X PATCH 'http://localhost:3000/api/v3/store/carts/cart_xxx/associate' \
-H 'X-Spree-Api-Key: spree_pk_xxx' \
-H 'Authorization: Bearer <jwt_token>' \
- -H 'X-Spree-Order-Token: <order_token>'
+ -H 'X-Spree-Token: <order_token>'
```
</CodeGroup>
@@ -199,4 +199,4 @@ curl -X PATCH 'http://localhost:3000/api/v3/store/cart/associate' \
|--------|--------|----------|
| API Key | `X-Spree-Api-Key: spree_pk_xxx` | All requests (required) |
| JWT Token | `Authorization: Bearer <token>` | Authenticated customer actions |
-| Order Token | `X-Spree-Order-Token: <token>` | Guest cart and checkout |
+| Order Token | `X-Spree-Token: <token>` | Guest cart and checkout |
diff --git a/docs/api-reference/store-api/errors.mdx b/docs/api-reference/store-api/errors.mdx
index f6fff0e2de..aaf5bcff58 100644
--- a/docs/api-reference/store-api/errors.mdx
+++ b/docs/api-reference/store-api/errors.mdx
@@ -80,15 +80,22 @@ Validation errors include an additional `details` field with per-field error mes
| `parameter_missing` | 400 | A required parameter is missing |
| `parameter_invalid` | 400 | A parameter has an invalid value |
+### Cart Errors
+
+| Code | Status | Description |
+|------|--------|-------------|
+| `cart_not_found` | 404 | Cart doesn't exist or doesn't belong to the current user/guest |
+| `cart_already_completed` | 422 | Cannot modify a cart that has already been completed |
+| `cart_cannot_transition` | 422 | Internal state machine transition failed (e.g., completing a cart that isn't ready) |
+| `cart_empty` | 422 | Cart has no line items |
+| `cart_invalid_state` | 422 | Cart is in an invalid state for this operation |
+| `cart_already_updated` | 409 | Cart was modified by another request (optimistic locking conflict) |
+
### Order Errors
| Code | Status | Description |
|------|--------|-------------|
-| `order_not_found` | 404 | Order doesn't exist or doesn't belong to the current user/guest |
-| `order_already_completed` | 422 | Cannot modify an order that has already been completed |
-| `order_cannot_transition` | 422 | Order can't move to the requested state (e.g., advancing without an address) |
-| `order_empty` | 422 | Order has no line items |
-| `order_invalid_state` | 422 | Order is in an invalid state for this operation |
+| `order_not_found` | 404 | Completed order doesn't exist or doesn't belong to the current user/guest |
### Line Item & Stock Errors
@@ -177,9 +184,9 @@ curl -X POST https://api.mystore.com/api/v3/store/account/addresses \
### Insufficient Stock
```bash
-curl -X POST https://api.mystore.com/api/v3/store/cart/line_items \
+curl -X POST https://api.mystore.com/api/v3/store/carts/cart_xxx/items \
-H "Authorization: Bearer spree_pk_xxx" \
- -H "X-Spree-Order-Token: abc123" \
+ -H "X-Spree-Token: abc123" \
-H "Content-Type: application/json" \
-d '{"variant_id": "var_xxx", "quantity": 999}'
```
@@ -196,16 +203,15 @@ curl -X POST https://api.mystore.com/api/v3/store/cart/line_items \
### Invalid State Transition
```bash
-curl -X PATCH https://api.mystore.com/api/v3/store/orders/or_xxx/advance \
- -H "Authorization: Bearer spree_pk_xxx" \
- -H "X-Spree-Order-Token: abc123"
+curl -X POST https://api.mystore.com/api/v3/store/carts/cart_xxx/complete \
+ -H "Authorization: Bearer spree_pk_xxx"
```
```json 422
{
"error": {
- "code": "order_cannot_transition",
- "message": "Cannot transition state via :next from :cart"
+ "code": "cart_cannot_transition",
+ "message": "Cannot transition cart to complete — ensure address, shipping, and payment are set"
}
}
```
@@ -235,7 +241,7 @@ Handle specific error codes:
```typescript
try {
- await client.orders.lineItems.create(orderId, {
+ await client.carts.items.create(cartId, {
variant_id: variantId,
quantity: 1,
});
@@ -248,7 +254,7 @@ try {
case 'variant_not_found':
showNotification('This product is no longer available');
break;
- case 'order_already_completed':
+ case 'cart_already_completed':
// Cart was already checked out — create a new one
await createNewCart();
break;
diff --git a/docs/api-reference/store-api/idempotency.mdx b/docs/api-reference/store-api/idempotency.mdx
index be5875087d..4bf49bafc7 100644
--- a/docs/api-reference/store-api/idempotency.mdx
+++ b/docs/api-reference/store-api/idempotency.mdx
@@ -15,9 +15,9 @@ Include an `Idempotency-Key` header with a unique value (e.g., a UUID) on any su
3. **Key reuse with different parameters** — return a `422` error to prevent misuse
```bash
-curl -X POST https://api.mystore.com/api/v3/store/orders/or_xxx/line_items \
+curl -X POST https://api.mystore.com/api/v3/store/carts/cart_xxx/items \
-H "Authorization: Bearer spree_pk_xxx" \
- -H "X-Spree-Order-Token: abc123" \
+ -H "X-Spree-Token: abc123" \
-H "Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000" \
-H "Content-Type: application/json" \
-d '{"variant_id": "variant_xxx", "quantity": 1}'
@@ -29,16 +29,14 @@ If the client retries this exact request with the same idempotency key, the API
| Endpoint | Actions |
|----------|---------|
-| `POST /cart` | Cart creation |
-| `PATCH /orders/:id` | Order updates |
-| `PATCH /orders/:id/next` | Checkout state transition |
-| `PATCH /orders/:id/advance` | Checkout advancement |
-| `PATCH /orders/:id/complete` | Order completion |
-| `POST /orders/:id/line_items` | Adding items to cart |
-| `POST /orders/:id/payment_sessions` | Payment session creation |
-| `PATCH /orders/:id/payment_sessions/:id/complete` | Payment completion |
-| `POST /orders/:id/coupon_codes` | Applying coupon codes |
-| `POST /orders/:id/store_credits` | Applying store credits |
+| `POST /carts` | Cart creation |
+| `PATCH /carts/:id` | Cart updates |
+| `POST /carts/:id/complete` | Order completion |
+| `POST /carts/:id/items` | Adding items to cart |
+| `POST /carts/:id/payment_sessions` | Payment session creation |
+| `PATCH /carts/:id/payment_sessions/:id/complete` | Payment completion |
+| `POST /carts/:id/coupon_codes` | Applying coupon codes |
+| `POST /carts/:id/store_credits` | Applying store credits |
Idempotency keys are ignored on `GET`, `DELETE`, and other non-supported actions.
@@ -104,7 +102,7 @@ const client = createClient({
})
// Add item to cart with idempotency key
-await client.orders.lineItems.create(orderId, {
+await client.carts.items.create(cartId, {
variant_id: 'variant_xxx',
quantity: 1,
}, {
diff --git a/docs/api-reference/store-api/metadata.mdx b/docs/api-reference/store-api/metadata.mdx
index d2bf531e5b..dad830be01 100644
--- a/docs/api-reference/store-api/metadata.mdx
+++ b/docs/api-reference/store-api/metadata.mdx
@@ -17,7 +17,7 @@ You can attach metadata when creating a cart:
<CodeGroup>
```typescript SDK
-const cart = await client.cart.create({
+const cart = await client.carts.create({
metadata: {
utm_source: 'google',
utm_campaign: 'summer_sale',
@@ -27,7 +27,7 @@ const cart = await client.cart.create({
```
```bash cURL
-curl -X POST 'http://localhost:3000/api/v3/store/cart' \
+curl -X POST 'http://localhost:3000/api/v3/store/carts' \
-H 'X-Spree-Api-Key: spree_pk_xxx' \
-H 'Content-Type: application/json' \
-d '{
@@ -41,25 +41,25 @@ curl -X POST 'http://localhost:3000/api/v3/store/cart' \
</CodeGroup>
-## Order Metadata
+## Cart Metadata (Update)
-Update metadata on an existing order:
+Update metadata on an existing cart:
<CodeGroup>
```typescript SDK
-await client.orders.update(cart.id, {
+await client.carts.update(cart.id, {
metadata: {
gift_message: 'Happy Birthday!',
preferred_delivery: 'morning',
},
-}, { orderToken: cart.token })
+}, { spreeToken: cart.token })
```
```bash cURL
-curl -X PATCH 'http://localhost:3000/api/v3/store/orders/or_xxx' \
+curl -X PATCH 'http://localhost:3000/api/v3/store/carts/cart_xxx' \
-H 'X-Spree-Api-Key: spree_pk_xxx' \
- -H 'X-Spree-Order-Token: <order_token>' \
+ -H 'X-Spree-Token: <order_token>' \
-H 'Content-Type: application/json' \
-d '{
"metadata": {
@@ -71,29 +71,29 @@ curl -X PATCH 'http://localhost:3000/api/v3/store/orders/or_xxx' \
</CodeGroup>
-## Line Item Metadata
+## Item Metadata
-Attach metadata to individual line items when adding or updating them:
+Attach metadata to individual items when adding or updating them:
### When Adding an Item
<CodeGroup>
```typescript SDK
-await client.orders.lineItems.create(cart.id, {
+await client.carts.items.create(cart.id, {
variant_id: 'variant_abc123',
quantity: 1,
metadata: {
personalization: 'John',
gift_wrap: true,
},
-}, { orderToken: cart.token })
+}, { spreeToken: cart.token })
```
```bash cURL
-curl -X POST 'http://localhost:3000/api/v3/store/orders/or_xxx/line_items' \
+curl -X POST 'http://localhost:3000/api/v3/store/carts/cart_xxx/items' \
-H 'X-Spree-Api-Key: spree_pk_xxx' \
- -H 'X-Spree-Order-Token: <order_token>' \
+ -H 'X-Spree-Token: <order_token>' \
-H 'Content-Type: application/json' \
-d '{
"variant_id": "variant_abc123",
@@ -114,18 +114,18 @@ Updating metadata **merges** with existing values rather than replacing them:
<CodeGroup>
```typescript SDK
-await client.orders.lineItems.update(cart.id, 'li_xyz789', {
+await client.carts.items.update(cart.id, 'li_xyz789', {
metadata: {
personalization: 'Jane', // Updates existing key
engraving: 'With Love', // Adds new key
},
-}, { orderToken: cart.token })
+}, { spreeToken: cart.token })
```
```bash cURL
-curl -X PATCH 'http://localhost:3000/api/v3/store/orders/or_xxx/line_items/li_xyz789' \
+curl -X PATCH 'http://localhost:3000/api/v3/store/carts/cart_xxx/items/li_xyz789' \
-H 'X-Spree-Api-Key: spree_pk_xxx' \
- -H 'X-Spree-Order-Token: <order_token>' \
+ -H 'X-Spree-Token: <order_token>' \
-H 'Content-Type: application/json' \
-d '{
"metadata": {
diff --git a/docs/api-reference/store.yaml b/docs/api-reference/store.yaml
index a017e38323..216adca1a4 100644
--- a/docs/api-reference/store.yaml
+++ b/docs/api-reference/store.yaml
@@ -661,16 +661,16 @@ paths:
content:
application/json:
example:
- token: eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX3R5cGUiOiJjdXN0b21lciIsImp0aSI6IjlhYTI3NmNkLTYyYmYtNDM5ZC1hNGNlLWZkOWEzZmMzOWM0YiIsImlzcyI6InNwcmVlIiwiYXVkIjoic3RvcmVfYXBpIiwiZXhwIjoxNzczMzE2OTcyfQ.-jiv9QqxaOAkIm9of9pt3IXMtBBDnCHX3vr48XjHgBw
+ token: eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX3R5cGUiOiJjdXN0b21lciIsImp0aSI6Ijc5MjE2MDdmLTJiMzYtNGFhZi04MzM2LTBhMDExNDNhNDExNCIsImlzcyI6InNwcmVlIiwiYXVkIjoic3RvcmVfYXBpIiwiZXhwIjoxNzczNDAyODAxfQ.24eRQQE9XB_xMaY6aCQ5z6Dz95vMV6oOSLmed8bz2Ww
user:
id: cus_UkLWZg9DAJ
- first_name: Reginald
- last_name: Wyman
+ first_name: Cindie
+ last_name: Lockman
phone:
accepts_email_marketing: false
- created_at: '2026-03-12T11:02:52.408Z'
- updated_at: '2026-03-12T11:02:52.408Z'
+ created_at: '2026-03-13T10:53:21.357Z'
+ updated_at: '2026-03-13T10:53:21.357Z'
addresses: []
default_billing_address:
default_shipping_address:
@@ -747,16 +747,16 @@ paths:
content:
application/json:
example:
- token: eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX3R5cGUiOiJjdXN0b21lciIsImp0aSI6ImM1YTI1NGQyLTNiNjEtNDA1ZS1hZWI5LTlmM2Y4YTgzOWExOSIsImlzcyI6InNwcmVlIiwiYXVkIjoic3RvcmVfYXBpIiwiZXhwIjoxNzczMzE2OTczfQ.pjMVxf_SHTDS2WL7eAhMQoAyGFV9TetQpFL0FweZENw
+ token: eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX3R5cGUiOiJjdXN0b21lciIsImp0aSI6IjBkMDllNThhLThmNGItNGE2ZC05MDY1LTVmMmNjNDhjYmIyNSIsImlzcyI6InNwcmVlIiwiYXVkIjoic3RvcmVfYXBpIiwiZXhwIjoxNzczNDAyODAyfQ.XfI6XfHYLtAKqqvOCV8Ig0CqhxoF-jm-l1Bb_pxCl-s
user:
id: cus_UkLWZg9DAJ
- first_name: Kena
- last_name: Marks
+ first_name: Gerardo
+ last_name: Lind
phone:
accepts_email_marketing: false
- created_at: '2026-03-12T11:02:53.836Z'
- updated_at: '2026-03-12T11:02:53.836Z'
+ created_at: '2026-03-13T10:53:22.724Z'
+ updated_at: '2026-03-13T10:53:22.724Z'
addresses: []
default_billing_address:
default_shipping_address:
@@ -772,182 +772,15 @@ paths:
message: Authentication required
schema:
"$ref": "#/components/schemas/ErrorResponse"
- "/api/v3/store/cart":
- post:
- summary: Create a new cart
- tags:
- - Cart
- security:
- - api_key: []
- description: |
- Creates a new shopping cart. Can be created by guests or authenticated customers.
- Returns a `token` that must be used for guest access to the cart.
- x-codeSamples:
- - lang: javascript
- label: Spree SDK
- source: |-
- import { createClient } from '@spree/sdk'
-
- const client = createClient({
- baseUrl: 'https://your-store.com',
- publishableKey: '<api-key>',
- })
-
- // Create an empty cart
- const cart = await client.cart.create()
-
- // Create a cart with line items
- const cartWithItems = await client.cart.create({
- line_items: [
- { variant_id: 'variant_abc123', quantity: 2 },
- ],
- })
- parameters:
- - name: x-spree-api-key
- in: header
- required: true
- schema:
- type: string
- - name: Authorization
- in: header
- required: false
- description: Bearer JWT token (optional - for authenticated customers)
- schema:
- type: string
- - name: Idempotency-Key
- in: header
- required: false
- description: Unique key for request idempotency. Duplicate requests with the
- same key return the cached response.
- schema:
- type: string
- responses:
- '201':
- description: cart created with metadata
- content:
- application/json:
- example:
- id: cart_UkLWZg9DAJ
- number: R444676807
- token: 2IQsRMgRO83n2G7YHQxwew1773313374623
- email:
- special_instructions:
- currency: USD
- locale: en
- item_count: 0
- item_total: '0.0'
- display_item_total: "$0.00"
- ship_total: '0.0'
- display_ship_total: "$0.00"
- adjustment_total: '0.0'
- display_adjustment_total: "$0.00"
- promo_total: '0.0'
- display_promo_total: "$0.00"
- tax_total: '0.0'
- display_tax_total: "$0.00"
- included_tax_total: '0.0'
- display_included_tax_total: "$0.00"
- additional_tax_total: '0.0'
- display_additional_tax_total: "$0.00"
- total: '0.0'
- display_total: "$0.00"
- created_at: '2026-03-12T11:02:54.625Z'
- updated_at: '2026-03-12T11:02:54.625Z'
- current_step: address
- completed_steps: []
- requirements:
- - step: cart
- field: line_items
- message: Add at least one item to your cart
- - step: address
- field: email
- message: Email address is required
- - step: address
- field: ship_address
- message: Shipping address is required
- - step: delivery
- field: shipping_method
- message: Select a shipping method for all shipments
- promotions: []
- items: []
- shipments: []
- payments: []
- bill_address:
- ship_address:
- payment_methods: []
- schema:
- "$ref": "#/components/schemas/Cart"
- '401':
- description: unauthorized - invalid API key
- content:
- application/json:
- example:
- error:
- code: invalid_token
- message: Valid API key required
- schema:
- "$ref": "#/components/schemas/ErrorResponse"
- '400':
- description: idempotency key too long
- content:
- application/json:
- example:
- error:
- code: invalid_request
- message: Idempotency-Key must be 255 characters or less.
- schema:
- "$ref": "#/components/schemas/ErrorResponse"
- '422':
- description: idempotency key reused with different parameters
- content:
- application/json:
- example:
- error:
- code: idempotency_key_reused
- message: This Idempotency-Key has already been used with different
- request parameters.
- schema:
- "$ref": "#/components/schemas/ErrorResponse"
- requestBody:
- content:
- application/json:
- schema:
- type: object
- properties:
- metadata:
- type: object
- description: Write-only key-value metadata (Stripe-style). Not returned
- in responses.
- line_items:
- type: array
- description: Line items to add to the cart on creation
- items:
- type: object
- properties:
- variant_id:
- type: string
- example: variant_abc123
- description: Prefixed variant ID
- quantity:
- type: integer
- example: 2
- description: Quantity (defaults to 1)
- metadata:
- type: object
- additionalProperties: true
- description: Arbitrary key-value metadata
- required:
- - variant_id
+ "/api/v3/store/carts":
get:
- summary: Get current cart
+ summary: List active carts
tags:
- - Cart
+ - Carts
security:
- api_key: []
bearer_auth: []
- description: |
- Returns the current shopping cart (incomplete order).
- Authenticate via JWT token for logged-in users or via x-spree-token header for guests.
+ description: Returns all active (incomplete) carts for the authenticated user.
x-codeSamples:
- lang: javascript
label: Spree SDK
@@ -959,15 +792,9 @@ paths:
publishableKey: '<api-key>',
})
- // Authenticated customer
- const cart = await client.cart.get({
+ const carts = await client.carts.list({
bearerToken: '<token>',
})
-
- // Guest with order token
- const guestCart = await client.cart.get({
- orderToken: 'ORDER_TOKEN',
- })
parameters:
- name: x-spree-api-key
in: header
@@ -976,474 +803,28 @@ paths:
type: string
- name: Authorization
in: header
- required: false
- description: Bearer JWT token for authenticated customers
- schema:
- type: string
- - name: x-spree-token
- in: header
- required: false
- description: Order token for guest checkout
+ required: true
schema:
type: string
responses:
'200':
- description: cart found (authenticated)
+ description: carts listed
content:
application/json:
example:
- id: cart_UkLWZg9DAJ
- number: R815446004
- token: frUZtW2DD2R64CF2ed1XC69uUNo9C7Us8LV
- special_instructions:
- currency: USD
- locale: en
- item_count: 1
- item_total: '10.0'
- display_item_total: "$10.00"
- ship_total: '100.0'
- display_ship_total: "$100.00"
- adjustment_total: '0.0'
- display_adjustment_total: "$0.00"
- promo_total: '0.0'
- display_promo_total: "$0.00"
- tax_total: '0.0'
- display_tax_total: "$0.00"
- included_tax_total: '0.0'
- display_included_tax_total: "$0.00"
- additional_tax_total: '0.0'
- display_additional_tax_total: "$0.00"
- total: '110.0'
- display_total: "$110.00"
- created_at: '2026-03-12T11:02:55.627Z'
- updated_at: '2026-03-12T11:02:55.687Z'
- current_step: address
- completed_steps: []
- requirements:
- - step: payment
- field: payment
- message: Add a payment method
- promotions: []
- items:
- - id: li_UkLWZg9DAJ
- variant_id: variant_UkLWZg9DAJ
- quantity: 1
+ data:
+ - id: cart_gbHJdmfrXB
+ number: R225562932
+ token: GSFPkqUTWbf5b8qjoxsXRXAi6EDphCV4LQX
+ special_instructions:
currency: USD
- name: Product 34547
- slug: product-34547
- options_text: ''
- price: '10.0'
- display_price: "$10.00"
- total: '10.0'
- display_total: "$10.00"
- adjustment_total: '0.0'
- display_adjustment_total: "$0.00"
- additional_tax_total: '0.0'
- display_additional_tax_total: "$0.00"
- included_tax_total: '0.0'
- display_included_tax_total: "$0.00"
- promo_total: '0.0'
- display_promo_total: "$0.00"
- pre_tax_amount: '10.0'
- display_pre_tax_amount: "$10.00"
- discounted_amount: '10.0'
- display_discounted_amount: "$10.00"
- display_compare_at_amount: "$0.00"
- created_at: '2026-03-12T11:02:55.662Z'
- updated_at: '2026-03-12T11:02:55.662Z'
- compare_at_amount:
- thumbnail_url:
- option_values: []
- digital_links: []
- shipments:
- - id: ship_UkLWZg9DAJ
- number: H26905428503
- state: pending
- tracking: U10000
- tracking_url:
- cost: '100.0'
- display_cost: "$100.00"
- shipped_at:
- created_at: '2026-03-12T11:02:55.668Z'
- updated_at: '2026-03-12T11:02:55.685Z'
- shipping_method:
- id: shpm_UkLWZg9DAJ
- name: UPS Ground
- code: UPS_GROUND
- stock_location:
- id: sloc_UkLWZg9DAJ
- state_abbr: STATE_ABBR_42
- name: Irina Kuhn
- address1: 1600 Pennsylvania Ave NW
- city: Washington
- zipcode: '20500'
- country_iso: US
- country_name: United States of America
- state_text: STATE_ABBR_42
- shipping_rates:
- - id: shpr_UkLWZg9DAJ
- shipping_method_id: shpm_UkLWZg9DAJ
- name: UPS Ground
- selected: true
- cost: '100.0'
- display_cost: "$100.00"
- shipping_method:
- id: shpm_UkLWZg9DAJ
- name: UPS Ground
- code: UPS_GROUND
- payments: []
- bill_address:
- id: addr_EfhxLZ9ck8
- firstname: John
- lastname: Doe
- full_name: John Doe
- address1: 43 Lovely Street
- address2: Northwest
- city: Herndon
- zipcode: '35005'
- phone: 555-555-0199
- company: Company
- country_name: United States of America
- country_iso: US
- state_text: STATE_ABBR_44
- state_abbr: STATE_ABBR_44
- quick_checkout: false
- state_name: STATE_NAME_44
- ship_address:
- id: addr_VqXmZF31wY
- firstname: John
- lastname: Doe
- full_name: John Doe
- address1: 44 Lovely Street
- address2: Northwest
- city: Herndon
- zipcode: '35005'
- phone: 555-555-0199
- company: Company
- country_name: United States of America
- country_iso: US
- state_text: STATE_ABBR_45
- state_abbr: STATE_ABBR_45
- quick_checkout: false
- state_name: STATE_NAME_45
- payment_methods: []
- schema:
- "$ref": "#/components/schemas/Cart"
- '404':
- description: no cart found
- content:
- application/json:
- example:
- error:
- code: order_not_found
- message: Order not found
- schema:
- "$ref": "#/components/schemas/ErrorResponse"
- delete:
- summary: Delete current cart
- tags:
- - Cart
- security:
- - api_key: []
- bearer_auth: []
- description: Deletes/abandons the current shopping cart.
- x-codeSamples:
- - lang: javascript
- label: Spree SDK
- source: |-
- import { createClient } from '@spree/sdk'
-
- const client = createClient({
- baseUrl: 'https://your-store.com',
- publishableKey: '<api-key>',
- })
-
- await client.cart.delete({
- orderToken: 'ORDER_TOKEN',
- })
- parameters:
- - name: x-spree-api-key
- in: header
- required: true
- schema:
- type: string
- - name: Authorization
- in: header
- required: false
- schema:
- type: string
- - name: x-spree-token
- in: header
- required: false
- schema:
- type: string
- responses:
- '204':
- description: cart deleted
- "/api/v3/store/cart/associate":
- patch:
- summary: Associate guest cart with authenticated user
- tags:
- - Cart
- security:
- - api_key: []
- bearer_auth: []
- description: |
- Associates a guest cart with the currently authenticated user.
- Requires both JWT authentication and an order token.
- The order must not be completed and must not belong to another user.
- x-codeSamples:
- - lang: javascript
- label: Spree SDK
- source: |-
- import { createClient } from '@spree/sdk'
-
- const client = createClient({
- baseUrl: 'https://your-store.com',
- publishableKey: '<api-key>',
- })
-
- const cart = await client.cart.associate({
- bearerToken: '<token>',
- orderToken: 'GUEST_ORDER_TOKEN',
- })
- parameters:
- - name: x-spree-api-key
- in: header
- required: true
- schema:
- type: string
- - name: Authorization
- in: header
- required: true
- description: Bearer JWT token (required)
- schema:
- type: string
- - name: x-spree-token
- in: header
- required: true
- description: Order token for identifying the guest cart
- schema:
- type: string
- responses:
- '200':
- description: cart associated successfully
- content:
- application/json:
- example:
- id: cart_UkLWZg9DAJ
- number: R859728395
- token: 9J3r7QQfHRG3n8aLbVjNSwF3N6c2uhB2U6u
- special_instructions:
- currency: USD
- locale: en
- item_count: 1
- item_total: '10.0'
- display_item_total: "$10.00"
- ship_total: '100.0'
- display_ship_total: "$100.00"
- adjustment_total: '0.0'
- display_adjustment_total: "$0.00"
- promo_total: '0.0'
- display_promo_total: "$0.00"
- tax_total: '0.0'
- display_tax_total: "$0.00"
- included_tax_total: '0.0'
- display_included_tax_total: "$0.00"
- additional_tax_total: '0.0'
- display_additional_tax_total: "$0.00"
- total: '110.0'
- display_total: "$110.00"
- created_at: '2026-03-12T11:02:56.912Z'
- updated_at: '2026-03-12T11:02:56.960Z'
- current_step: address
- completed_steps: []
- requirements:
- - step: payment
- field: payment
- message: Add a payment method
- promotions: []
- items:
- - id: li_UkLWZg9DAJ
- variant_id: variant_UkLWZg9DAJ
- quantity: 1
- currency: USD
- name: Product 54840
- slug: product-54840
- options_text: ''
- price: '10.0'
- display_price: "$10.00"
- total: '10.0'
- display_total: "$10.00"
- adjustment_total: '0.0'
- display_adjustment_total: "$0.00"
- additional_tax_total: '0.0'
- display_additional_tax_total: "$0.00"
- included_tax_total: '0.0'
- display_included_tax_total: "$0.00"
- promo_total: '0.0'
- display_promo_total: "$0.00"
- pre_tax_amount: '10.0'
- display_pre_tax_amount: "$10.00"
- discounted_amount: '10.0'
- display_discounted_amount: "$10.00"
- display_compare_at_amount: "$0.00"
- created_at: '2026-03-12T11:02:56.940Z'
- updated_at: '2026-03-12T11:02:56.940Z'
- compare_at_amount:
- thumbnail_url:
- option_values: []
- digital_links: []
- shipments:
- - id: ship_UkLWZg9DAJ
- number: H14918773498
- state: pending
- tracking: U10000
- tracking_url:
- cost: '100.0'
- display_cost: "$100.00"
- shipped_at:
- created_at: '2026-03-12T11:02:56.945Z'
- updated_at: '2026-03-12T11:02:56.958Z'
- shipping_method:
- id: shpm_UkLWZg9DAJ
- name: UPS Ground
- code: UPS_GROUND
- stock_location:
- id: sloc_UkLWZg9DAJ
- state_abbr: STATE_ABBR_50
- name: Alison Boyer
- address1: 1600 Pennsylvania Ave NW
- city: Washington
- zipcode: '20500'
- country_iso: US
- country_name: United States of America
- state_text: STATE_ABBR_50
- shipping_rates:
- - id: shpr_UkLWZg9DAJ
- shipping_method_id: shpm_UkLWZg9DAJ
- name: UPS Ground
- selected: true
- cost: '100.0'
- display_cost: "$100.00"
- shipping_method:
- id: shpm_UkLWZg9DAJ
- name: UPS Ground
- code: UPS_GROUND
- payments: []
- bill_address:
- id: addr_EfhxLZ9ck8
- firstname: John
- lastname: Doe
- full_name: John Doe
- address1: 51 Lovely Street
- address2: Northwest
- city: Herndon
- zipcode: '35005'
- phone: 555-555-0199
- company: Company
- country_name: United States of America
- country_iso: US
- state_text: STATE_ABBR_52
- state_abbr: STATE_ABBR_52
- quick_checkout: false
- state_name: STATE_NAME_52
- ship_address:
- id: addr_VqXmZF31wY
- firstname: John
- lastname: Doe
- full_name: John Doe
- address1: 52 Lovely Street
- address2: Northwest
- city: Herndon
- zipcode: '35005'
- phone: 555-555-0199
- company: Company
- country_name: United States of America
- country_iso: US
- state_text: STATE_ABBR_53
- state_abbr: STATE_ABBR_53
- quick_checkout: false
- state_name: STATE_NAME_53
- payment_methods: []
- schema:
- "$ref": "#/components/schemas/Cart"
- '401':
- description: unauthorized - JWT required
- content:
- application/json:
- example:
- error:
- code: authentication_required
- message: Authentication required
- schema:
- "$ref": "#/components/schemas/ErrorResponse"
- '404':
- description: cart already completed
- content:
- application/json:
- example:
- error:
- code: order_not_found
- message: Order not found
- schema:
- "$ref": "#/components/schemas/ErrorResponse"
- "/api/v3/store/carts":
- get:
- summary: List active carts
- tags:
- - Cart
- security:
- - api_key: []
- bearer_auth: []
- description: Returns all active (incomplete) carts for the authenticated user.
- Useful for users who may have multiple carts.
- x-codeSamples:
- - lang: javascript
- label: Spree SDK
- source: |-
- import { createClient } from '@spree/sdk'
-
- const client = createClient({
- baseUrl: 'https://your-store.com',
- publishableKey: '<api-key>',
- })
-
- const carts = await client.carts.list({
- bearerToken: '<token>',
- })
- parameters:
- - name: x-spree-api-key
- in: header
- required: true
- schema:
- type: string
- - name: Authorization
- in: header
- required: true
- schema:
- type: string
- responses:
- '200':
- description: carts listed
- content:
- application/json:
- example:
- data:
- - id: cart_gbHJdmfrXB
- number: R814368838
- token: 2VCTJwra1PHZDVLgNoatuq7QBf756Tti68e
- special_instructions:
- currency: USD
- locale: en
- item_count: 1
- item_total: '10.0'
- display_item_total: "$10.00"
- ship_total: '100.0'
- display_ship_total: "$100.00"
+ locale: en
+ item_count: 1
+ item_total: '10.0'
+ display_item_total: "$10.00"
+ ship_total: '100.0'
+ display_ship_total: "$100.00"
adjustment_total: '0.0'
display_adjustment_total: "$0.00"
promo_total: '0.0'
@@ -1456,8 +837,8 @@ paths:
display_additional_tax_total: "$0.00"
total: '110.0'
display_total: "$110.00"
- created_at: '2026-03-12T11:02:59.696Z'
- updated_at: '2026-03-12T11:02:59.744Z'
+ created_at: '2026-03-13T10:53:23.458Z'
+ updated_at: '2026-03-13T10:53:23.511Z'
current_step: address
completed_steps: []
requirements:
@@ -1470,8 +851,8 @@ paths:
variant_id: variant_gbHJdmfrXB
quantity: 1
currency: USD
- name: Product 107531
- slug: product-107531
+ name: Product 28768
+ slug: product-28768
options_text: ''
price: '10.0'
display_price: "$10.00"
@@ -1490,37 +871,37 @@ paths:
discounted_amount: '10.0'
display_discounted_amount: "$10.00"
display_compare_at_amount: "$0.00"
- created_at: '2026-03-12T11:02:59.722Z'
- updated_at: '2026-03-12T11:02:59.722Z'
+ created_at: '2026-03-13T10:53:23.489Z'
+ updated_at: '2026-03-13T10:53:23.489Z'
compare_at_amount:
thumbnail_url:
option_values: []
digital_links: []
shipments:
- id: ship_gbHJdmfrXB
- number: H05290586723
+ number: H00671914240
state: pending
tracking: U10000
tracking_url:
cost: '100.0'
display_cost: "$100.00"
shipped_at:
- created_at: '2026-03-12T11:02:59.731Z'
- updated_at: '2026-03-12T11:02:59.742Z'
+ created_at: '2026-03-13T10:53:23.497Z'
+ updated_at: '2026-03-13T10:53:23.508Z'
shipping_method:
id: shpm_gbHJdmfrXB
name: UPS Ground
code: UPS_GROUND
stock_location:
id: sloc_UkLWZg9DAJ
- state_abbr: STATE_ABBR_66
- name: Isaias Hessel
+ state_abbr: STATE_ABBR_37
+ name: Tonisha Buckridge
address1: 1600 Pennsylvania Ave NW
city: Washington
zipcode: '20500'
country_iso: US
country_name: United States of America
- state_text: STATE_ABBR_66
+ state_text: STATE_ABBR_37
shipping_rates:
- id: shpr_gbHJdmfrXB
shipping_method_id: shpm_gbHJdmfrXB
@@ -1538,7 +919,7 @@ paths:
firstname: John
lastname: Doe
full_name: John Doe
- address1: 69 Lovely Street
+ address1: 41 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -1546,16 +927,16 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_70
- state_abbr: STATE_ABBR_70
+ state_text: STATE_ABBR_41
+ state_abbr: STATE_ABBR_41
quick_checkout: false
- state_name: STATE_NAME_70
+ state_name: STATE_NAME_41
ship_address:
id: addr_OIJLhNcSbf
firstname: John
lastname: Doe
full_name: John Doe
- address1: 70 Lovely Street
+ address1: 42 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -1563,15 +944,15 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_71
- state_abbr: STATE_ABBR_71
+ state_text: STATE_ABBR_42
+ state_abbr: STATE_ABBR_42
quick_checkout: false
- state_name: STATE_NAME_71
+ state_name: STATE_NAME_42
payment_methods: []
- id: cart_UkLWZg9DAJ
- number: R892264243
- token: RYpjSFuiKYNrJ9rtmtauESMByXb41GN5ih2
+ number: R729014327
+ token: 7B3ktRBFwv9vxim3gcvp3GKr6ZAJquptw6d
special_instructions:
currency: USD
locale: en
@@ -1592,8 +973,8 @@ paths:
display_additional_tax_total: "$0.00"
total: '110.0'
display_total: "$110.00"
- created_at: '2026-03-12T11:02:59.632Z'
- updated_at: '2026-03-12T11:02:59.690Z'
+ created_at: '2026-03-13T10:53:23.311Z'
+ updated_at: '2026-03-13T10:53:23.451Z'
current_step: address
completed_steps: []
requirements:
@@ -1606,8 +987,8 @@ paths:
variant_id: variant_UkLWZg9DAJ
quantity: 1
currency: USD
- name: Product 93378
- slug: product-93378
+ name: Product 12324
+ slug: product-12324
options_text: ''
price: '10.0'
display_price: "$10.00"
@@ -1626,37 +1007,37 @@ paths:
discounted_amount: '10.0'
display_discounted_amount: "$10.00"
display_compare_at_amount: "$0.00"
- created_at: '2026-03-12T11:02:59.667Z'
- updated_at: '2026-03-12T11:02:59.667Z'
+ created_at: '2026-03-13T10:53:23.380Z'
+ updated_at: '2026-03-13T10:53:23.380Z'
compare_at_amount:
thumbnail_url:
option_values: []
digital_links: []
shipments:
- id: ship_UkLWZg9DAJ
- number: H98177595730
+ number: H94118725017
state: pending
tracking: U10000
tracking_url:
cost: '100.0'
display_cost: "$100.00"
shipped_at:
- created_at: '2026-03-12T11:02:59.673Z'
- updated_at: '2026-03-12T11:02:59.688Z'
+ created_at: '2026-03-13T10:53:23.395Z'
+ updated_at: '2026-03-13T10:53:23.446Z'
shipping_method:
id: shpm_UkLWZg9DAJ
name: UPS Ground
code: UPS_GROUND
stock_location:
id: sloc_UkLWZg9DAJ
- state_abbr: STATE_ABBR_66
- name: Isaias Hessel
+ state_abbr: STATE_ABBR_37
+ name: Tonisha Buckridge
address1: 1600 Pennsylvania Ave NW
city: Washington
zipcode: '20500'
country_iso: US
country_name: United States of America
- state_text: STATE_ABBR_66
+ state_text: STATE_ABBR_37
shipping_rates:
- id: shpr_UkLWZg9DAJ
shipping_method_id: shpm_UkLWZg9DAJ
@@ -1674,7 +1055,7 @@ paths:
firstname: John
lastname: Doe
full_name: John Doe
- address1: 67 Lovely Street
+ address1: 39 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -1682,16 +1063,16 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_68
- state_abbr: STATE_ABBR_68
+ state_text: STATE_ABBR_39
+ state_abbr: STATE_ABBR_39
quick_checkout: false
- state_name: STATE_NAME_68
+ state_name: STATE_NAME_39
ship_address:
id: addr_VqXmZF31wY
firstname: John
lastname: Doe
full_name: John Doe
- address1: 68 Lovely Street
+ address1: 40 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -1699,10 +1080,10 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_69
- state_abbr: STATE_ABBR_69
+ state_text: STATE_ABBR_40
+ state_abbr: STATE_ABBR_40
quick_checkout: false
- state_name: STATE_NAME_69
+ state_name: STATE_NAME_40
payment_methods: []
meta:
page: 1
@@ -1724,14 +1105,148 @@ paths:
message: Authentication required
schema:
"$ref": "#/components/schemas/ErrorResponse"
- "/api/v3/store/categories":
+ post:
+ summary: Create a new cart
+ tags:
+ - Carts
+ security:
+ - api_key: []
+ description: |
+ Creates a new shopping cart. Can be created by guests or authenticated customers.
+ Returns a `token` that must be used for guest access to the cart.
+ x-codeSamples:
+ - lang: javascript
+ label: Spree SDK
+ source: |-
+ import { createClient } from '@spree/sdk'
+
+ const client = createClient({
+ baseUrl: 'https://your-store.com',
+ publishableKey: '<api-key>',
+ })
+
+ // Create an empty cart
+ const cart = await client.carts.create()
+
+ // Create a cart with items
+ const cartWithItems = await client.carts.create({
+ items: [
+ { variant_id: 'variant_abc123', quantity: 2 },
+ ],
+ })
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: false
+ description: Bearer JWT token (optional - for authenticated customers)
+ schema:
+ type: string
+ - name: Idempotency-Key
+ in: header
+ required: false
+ description: Unique key for request idempotency.
+ schema:
+ type: string
+ responses:
+ '201':
+ description: cart created
+ content:
+ application/json:
+ example:
+ id: cart_UkLWZg9DAJ
+ number: R663575791
+ token: kt8wusHEzcm2h6uhvRweV6Qc7xSsRN5sAcY
+ email:
+ special_instructions:
+ currency: USD
+ locale: en
+ item_count: 0
+ item_total: '0.0'
+ display_item_total: "$0.00"
+ ship_total: '0.0'
+ display_ship_total: "$0.00"
+ adjustment_total: '0.0'
+ display_adjustment_total: "$0.00"
+ promo_total: '0.0'
+ display_promo_total: "$0.00"
+ tax_total: '0.0'
+ display_tax_total: "$0.00"
+ included_tax_total: '0.0'
+ display_included_tax_total: "$0.00"
+ additional_tax_total: '0.0'
+ display_additional_tax_total: "$0.00"
+ total: '0.0'
+ display_total: "$0.00"
+ created_at: '2026-03-13T10:53:23.970Z'
+ updated_at: '2026-03-13T10:53:23.970Z'
+ current_step: address
+ completed_steps: []
+ requirements:
+ - step: cart
+ field: line_items
+ message: Add at least one item to your cart
+ - step: address
+ field: email
+ message: Email address is required
+ - step: address
+ field: ship_address
+ message: Shipping address is required
+ - step: delivery
+ field: shipping_method
+ message: Select a shipping method for all shipments
+ promotions: []
+ items: []
+ shipments: []
+ payments: []
+ bill_address:
+ ship_address:
+ payment_methods: []
+ schema:
+ "$ref": "#/components/schemas/Cart"
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ metadata:
+ type: object
+ description: Write-only key-value metadata (Stripe-style).
+ items:
+ type: array
+ description: Items to add to the cart on creation
+ items:
+ type: object
+ properties:
+ variant_id:
+ type: string
+ example: variant_abc123
+ description: Prefixed variant ID
+ quantity:
+ type: integer
+ example: 2
+ description: Quantity (defaults to 1)
+ metadata:
+ type: object
+ additionalProperties: true
+ required:
+ - variant_id
+ "/api/v3/store/carts/{id}":
get:
- summary: List categories
+ summary: Get a cart
tags:
- - Product Catalog
+ - Carts
security:
- api_key: []
- description: Returns a paginated list of categories for the current store
+ bearer_auth: []
+ description: |
+ Returns a shopping cart by prefixed ID.
+ Authorize via x-spree-token header (guest) or JWT Bearer token (authenticated user).
x-codeSamples:
- lang: javascript
label: Spree SDK
@@ -1743,9 +1258,8 @@ paths:
publishableKey: '<api-key>',
})
- const categories = await client.categories.list({
- page: 1,
- limit: 25,
+ const cart = await client.carts.get('cart_abc123', {
+ bearerToken: '<token>',
})
parameters:
- name: x-spree-api-key
@@ -1753,130 +1267,186 @@ paths:
required: true
schema:
type: string
- - name: page
- in: query
- required: false
- schema:
- type: integer
- - name: limit
- in: query
+ - name: Authorization
+ in: header
required: false
schema:
- type: integer
- - name: q[name_cont]
- in: query
+ type: string
+ - name: x-spree-token
+ in: header
required: false
- description: Filter by name
schema:
type: string
- - name: fields
- in: query
- required: false
- description: Comma-separated list of fields to include (e.g., name,slug,price).
- id is always included.
+ - name: id
+ in: path
+ required: true
+ description: Cart prefixed ID (e.g., cart_abc123)
schema:
type: string
responses:
'200':
- description: categories found
+ description: cart found
content:
application/json:
example:
- data:
- - id: ctg_UkLWZg9DAJ
- name: taxonomy_1
- permalink: taxonomy-1
- position: 0
- depth: 0
- meta_title:
- meta_description:
- meta_keywords:
- children_count: 1
- created_at: '2026-03-12T11:03:00.192Z'
- updated_at: '2026-03-12T11:03:00.239Z'
- parent_id:
- description: ''
- description_html: ''
- image_url:
- square_image_url:
- is_root: true
- is_child: false
- is_leaf: false
- - id: ctg_gbHJdmfrXB
- name: taxon_1
- permalink: taxonomy-1/taxon-1
- position: 0
- depth: 1
- meta_title:
- meta_description:
- meta_keywords:
- children_count: 1
- created_at: '2026-03-12T11:03:00.200Z'
- updated_at: '2026-03-12T11:03:00.239Z'
- parent_id: ctg_UkLWZg9DAJ
- description: ''
- description_html: ''
- image_url:
- square_image_url:
- is_root: false
- is_child: true
- is_leaf: false
- - id: ctg_EfhxLZ9ck8
- name: taxon_2
- permalink: taxonomy-1/taxon-1/taxon-2
- position: 0
- depth: 2
- meta_title:
- meta_description:
- meta_keywords:
- children_count: 0
- created_at: '2026-03-12T11:03:00.208Z'
- updated_at: '2026-03-12T11:03:00.213Z'
- parent_id: ctg_gbHJdmfrXB
- description: ''
- description_html: ''
- image_url:
- square_image_url:
- is_root: false
- is_child: true
- is_leaf: true
- meta:
- page: 1
- limit: 25
- count: 3
- pages: 1
- from: 1
- to: 3
- in: 3
- previous:
- next:
+ id: cart_UkLWZg9DAJ
+ number: R653795125
+ token: rhmmHTrYL6tNkhbmFZqm3BNwtLF4fL7UeTr
+ special_instructions:
+ currency: USD
+ locale: en
+ item_count: 1
+ item_total: '10.0'
+ display_item_total: "$10.00"
+ ship_total: '100.0'
+ display_ship_total: "$100.00"
+ adjustment_total: '0.0'
+ display_adjustment_total: "$0.00"
+ promo_total: '0.0'
+ display_promo_total: "$0.00"
+ tax_total: '0.0'
+ display_tax_total: "$0.00"
+ included_tax_total: '0.0'
+ display_included_tax_total: "$0.00"
+ additional_tax_total: '0.0'
+ display_additional_tax_total: "$0.00"
+ total: '110.0'
+ display_total: "$110.00"
+ created_at: '2026-03-13T10:53:24.249Z'
+ updated_at: '2026-03-13T10:53:24.305Z'
+ current_step: address
+ completed_steps: []
+ requirements:
+ - step: payment
+ field: payment
+ message: Add a payment method
+ promotions: []
+ items:
+ - id: li_UkLWZg9DAJ
+ variant_id: variant_UkLWZg9DAJ
+ quantity: 1
+ currency: USD
+ name: Product 52397
+ slug: product-52397
+ options_text: ''
+ price: '10.0'
+ display_price: "$10.00"
+ total: '10.0'
+ display_total: "$10.00"
+ adjustment_total: '0.0'
+ display_adjustment_total: "$0.00"
+ additional_tax_total: '0.0'
+ display_additional_tax_total: "$0.00"
+ included_tax_total: '0.0'
+ display_included_tax_total: "$0.00"
+ promo_total: '0.0'
+ display_promo_total: "$0.00"
+ pre_tax_amount: '10.0'
+ display_pre_tax_amount: "$10.00"
+ discounted_amount: '10.0'
+ display_discounted_amount: "$10.00"
+ display_compare_at_amount: "$0.00"
+ created_at: '2026-03-13T10:53:24.281Z'
+ updated_at: '2026-03-13T10:53:24.281Z'
+ compare_at_amount:
+ thumbnail_url:
+ option_values: []
+ digital_links: []
+ shipments:
+ - id: ship_UkLWZg9DAJ
+ number: H01911063812
+ state: pending
+ tracking: U10000
+ tracking_url:
+ cost: '100.0'
+ display_cost: "$100.00"
+ shipped_at:
+ created_at: '2026-03-13T10:53:24.287Z'
+ updated_at: '2026-03-13T10:53:24.302Z'
+ shipping_method:
+ id: shpm_UkLWZg9DAJ
+ name: UPS Ground
+ code: UPS_GROUND
+ stock_location:
+ id: sloc_UkLWZg9DAJ
+ state_abbr: STATE_ABBR_47
+ name: Mattie Goldner
+ address1: 1600 Pennsylvania Ave NW
+ city: Washington
+ zipcode: '20500'
+ country_iso: US
+ country_name: United States of America
+ state_text: STATE_ABBR_47
+ shipping_rates:
+ - id: shpr_UkLWZg9DAJ
+ shipping_method_id: shpm_UkLWZg9DAJ
+ name: UPS Ground
+ selected: true
+ cost: '100.0'
+ display_cost: "$100.00"
+ shipping_method:
+ id: shpm_UkLWZg9DAJ
+ name: UPS Ground
+ code: UPS_GROUND
+ payments: []
+ bill_address:
+ id: addr_UkLWZg9DAJ
+ firstname: John
+ lastname: Doe
+ full_name: John Doe
+ address1: 47 Lovely Street
+ address2: Northwest
+ city: Herndon
+ zipcode: '35005'
+ phone: 555-555-0199
+ company: Company
+ country_name: United States of America
+ country_iso: US
+ state_text: STATE_ABBR_47
+ state_abbr: STATE_ABBR_47
+ quick_checkout: false
+ state_name: STATE_NAME_47
+ ship_address:
+ id: addr_gbHJdmfrXB
+ firstname: John
+ lastname: Doe
+ full_name: John Doe
+ address1: 48 Lovely Street
+ address2: Northwest
+ city: Herndon
+ zipcode: '35005'
+ phone: 555-555-0199
+ company: Company
+ country_name: United States of America
+ country_iso: US
+ state_text: STATE_ABBR_48
+ state_abbr: STATE_ABBR_48
+ quick_checkout: false
+ state_name: STATE_NAME_48
+ payment_methods: []
schema:
- type: object
- properties:
- data:
- type: array
- items:
- "$ref": "#/components/schemas/Category"
- meta:
- "$ref": "#/components/schemas/PaginationMeta"
- '401':
- description: unauthorized
+ "$ref": "#/components/schemas/Cart"
+ '404':
+ description: cart not found
content:
application/json:
example:
error:
- code: invalid_token
- message: Valid API key required
+ code: cart_not_found
+ message: Cart not found
schema:
"$ref": "#/components/schemas/ErrorResponse"
- "/api/v3/store/categories/{id}":
- get:
- summary: Get a category
+ patch:
+ summary: Update a cart
tags:
- - Product Catalog
+ - Carts
security:
- api_key: []
- description: Returns a single category by permalink or prefix ID
+ bearer_auth: []
+ description: Updates cart info (email, addresses, special instructions). When
+ addresses change, the order state is reverted to address to ensure shipments
+ are recalculated.
x-codeSamples:
- lang: javascript
label: Spree SDK
@@ -1888,8 +1458,19 @@ paths:
publishableKey: '<api-key>',
})
- const category = await client.categories.get('categories/clothing/shirts', {
- expand: 'children',
+ const cart = await client.carts.update('cart_abc123', {
+ email: '[email protected]',
+ ship_address: {
+ firstname: 'John',
+ lastname: 'Doe',
+ address1: '123 Main St',
+ city: 'New York',
+ zipcode: '10001',
+ country_iso: 'US',
+ state_abbr: 'NY',
+ },
+ }, {
+ bearerToken: '<token>',
})
parameters:
- name: x-spree-api-key
@@ -1897,82 +1478,251 @@ paths:
required: true
schema:
type: string
- - name: id
- in: path
- required: true
- description: Category permalink (e.g., clothing/shirts) or prefix ID (e.g.,
- ctg_abc123)
+ - name: Authorization
+ in: header
+ required: false
schema:
type: string
- - name: expand
- in: query
+ - name: x-spree-token
+ in: header
required: false
- description: Expand associations (children, parent, ancestors, metafields)
schema:
type: string
- - name: fields
- in: query
+ - name: Idempotency-Key
+ in: header
required: false
- description: Comma-separated list of fields to include (e.g., name,slug,price).
- id is always included.
+ schema:
+ type: string
+ - name: id
+ in: path
+ required: true
+ description: Cart prefixed ID
schema:
type: string
responses:
'200':
- description: category found by prefix ID
- content:
- application/json:
- example:
- id: ctg_gbHJdmfrXB
- name: taxon_10
- permalink: taxonomy-7/taxon-10
- position: 0
- depth: 1
- meta_title:
- meta_description:
- meta_keywords:
- children_count: 1
- created_at: '2026-03-12T11:03:00.643Z'
- updated_at: '2026-03-12T11:03:00.679Z'
- parent_id: ctg_UkLWZg9DAJ
- description: ''
- description_html: ''
- image_url:
- square_image_url:
- is_root: false
- is_child: true
- is_leaf: false
- schema:
- "$ref": "#/components/schemas/Category"
- '404':
- description: category from other store not accessible
- content:
- application/json:
- example:
- error:
- code: record_not_found
- message: Category not found
- schema:
- "$ref": "#/components/schemas/ErrorResponse"
- '401':
- description: unauthorized
+ description: cart updated
content:
application/json:
example:
- error:
- code: invalid_token
- message: Valid API key required
+ id: cart_UkLWZg9DAJ
+ number: R649255363
+ token: aMmhj5bJ8KU9u6tqre7iTPUGuNoUXXDXxwd
+ special_instructions: Leave at door
+ currency: USD
+ locale: en
+ item_count: 1
+ item_total: '19.99'
+ display_item_total: "$19.99"
+ ship_total: '10.0'
+ display_ship_total: "$10.00"
+ adjustment_total: '0.0'
+ display_adjustment_total: "$0.00"
+ promo_total: '0.0'
+ display_promo_total: "$0.00"
+ tax_total: '0.0'
+ display_tax_total: "$0.00"
+ included_tax_total: '0.0'
+ display_included_tax_total: "$0.00"
+ additional_tax_total: '0.0'
+ display_additional_tax_total: "$0.00"
+ total: '29.99'
+ display_total: "$29.99"
+ created_at: '2026-03-13T10:53:24.887Z'
+ updated_at: '2026-03-13T10:53:25.037Z'
+ current_step: payment
+ completed_steps:
+ - address
+ - delivery
+ requirements:
+ - step: payment
+ field: payment
+ message: Add a payment method
+ promotions: []
+ items:
+ - id: li_UkLWZg9DAJ
+ variant_id: variant_UkLWZg9DAJ
+ quantity: 1
+ currency: USD
+ name: Product 69203
+ slug: product-69203
+ options_text: ''
+ price: '19.99'
+ display_price: "$19.99"
+ total: '19.99'
+ display_total: "$19.99"
+ adjustment_total: '0.0'
+ display_adjustment_total: "$0.00"
+ additional_tax_total: '0.0'
+ display_additional_tax_total: "$0.00"
+ included_tax_total: '0.0'
+ display_included_tax_total: "$0.00"
+ promo_total: '0.0'
+ display_promo_total: "$0.00"
+ pre_tax_amount: '19.99'
+ display_pre_tax_amount: "$19.99"
+ discounted_amount: '19.99'
+ display_discounted_amount: "$19.99"
+ display_compare_at_amount: "$0.00"
+ created_at: '2026-03-13T10:53:24.914Z'
+ updated_at: '2026-03-13T10:53:24.984Z'
+ compare_at_amount:
+ thumbnail_url:
+ option_values: []
+ digital_links: []
+ shipments:
+ - id: ship_gbHJdmfrXB
+ number: H66584744530
+ state: pending
+ tracking:
+ tracking_url:
+ cost: '10.0'
+ display_cost: "$10.00"
+ shipped_at:
+ created_at: '2026-03-13T10:53:25.005Z'
+ updated_at: '2026-03-13T10:53:25.020Z'
+ shipping_method:
+ id: shpm_UkLWZg9DAJ
+ name: UPS Ground
+ code: UPS_GROUND
+ stock_location:
+ id: sloc_UkLWZg9DAJ
+ state_abbr: STATE_ABBR_49
+ name: Charline Corkery
+ address1: 1600 Pennsylvania Ave NW
+ city: Washington
+ zipcode: '20500'
+ country_iso: US
+ country_name: United States of America
+ state_text: STATE_ABBR_49
+ shipping_rates:
+ - id: shpr_gbHJdmfrXB
+ shipping_method_id: shpm_UkLWZg9DAJ
+ name: UPS Ground
+ selected: true
+ cost: '10.0'
+ display_cost: "$10.00"
+ shipping_method:
+ id: shpm_UkLWZg9DAJ
+ name: UPS Ground
+ code: UPS_GROUND
+ payments: []
+ bill_address:
+ id: addr_EfhxLZ9ck8
+ firstname: John
+ lastname: Doe
+ full_name: John Doe
+ address1: 51 Lovely Street
+ address2: Northwest
+ city: Herndon
+ zipcode: '35005'
+ phone: 555-555-0199
+ company: Company
+ country_name: United States of America
+ country_iso: US
+ state_text: STATE_ABBR_51
+ state_abbr: STATE_ABBR_51
+ quick_checkout: false
+ state_name: STATE_NAME_51
+ ship_address:
+ id: addr_VqXmZF31wY
+ firstname: John
+ lastname: Doe
+ full_name: John Doe
+ address1: 52 Lovely Street
+ address2: Northwest
+ city: Herndon
+ zipcode: '35005'
+ phone: 555-555-0199
+ company: Company
+ country_name: United States of America
+ country_iso: US
+ state_text: STATE_ABBR_52
+ state_abbr: STATE_ABBR_52
+ quick_checkout: false
+ state_name: STATE_NAME_52
+ payment_methods: []
schema:
- "$ref": "#/components/schemas/ErrorResponse"
- "/api/v3/store/categories/{category_id}/products":
- get:
- summary: List products in a category
+ "$ref": "#/components/schemas/Cart"
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ email:
+ type: string
+ format: email
+ special_instructions:
+ type: string
+ example: Leave at door
+ metadata:
+ type: object
+ additionalProperties: true
+ ship_address_id:
+ type: string
+ description: Existing address ID to use as shipping address
+ example: addr_abc123
+ bill_address_id:
+ type: string
+ description: Existing address ID to use as billing address
+ example: addr_def456
+ bill_address:
+ type: object
+ properties:
+ firstname:
+ type: string
+ lastname:
+ type: string
+ address1:
+ type: string
+ address2:
+ type: string
+ city:
+ type: string
+ zipcode:
+ type: string
+ phone:
+ type: string
+ company:
+ type: string
+ country_iso:
+ type: string
+ state_abbr:
+ type: string
+ ship_address:
+ type: object
+ properties:
+ firstname:
+ type: string
+ lastname:
+ type: string
+ address1:
+ type: string
+ address2:
+ type: string
+ city:
+ type: string
+ zipcode:
+ type: string
+ phone:
+ type: string
+ company:
+ type: string
+ country_iso:
+ type: string
+ state_abbr:
+ type: string
+ delete:
+ summary: Delete a cart
tags:
- - Product Catalog
+ - Carts
security:
- api_key: []
- description: Returns a paginated list of products belonging to the specified
- category
+ bearer_auth: []
+ description: Deletes/abandons the cart.
x-codeSamples:
- lang: javascript
label: Spree SDK
@@ -1984,11 +1734,8 @@ paths:
publishableKey: '<api-key>',
})
- const products = await client.categories.products.list('categories/clothing', {
- page: 1,
- limit: 25,
- sort: 'price',
- with_option_value_ids: ['optval_abc'],
+ await client.carts.delete('cart_abc123', {
+ bearerToken: '<token>',
})
parameters:
- name: x-spree-api-key
@@ -1996,149 +1743,231 @@ paths:
required: true
schema:
type: string
- - name: category_id
- in: path
- required: true
- description: Category permalink or prefix ID
- schema:
- type: string
- - name: page
- in: query
- required: false
- description: 'Page number (default: 1)'
- schema:
- type: integer
- - name: limit
- in: query
- required: false
- description: 'Number of items per page (default: 25, max: 100)'
- schema:
- type: integer
- - name: sort
- in: query
+ - name: Authorization
+ in: header
required: false
- description: 'Sort order. Prefix with - for descending. Values: price, -price,
- best_selling, name, -name, -available_on, available_on'
schema:
type: string
- - name: q[price_gte]
- in: query
+ - name: x-spree-token
+ in: header
required: false
- description: Filter by minimum price
schema:
- type: number
- - name: q[price_lte]
- in: query
- required: false
- description: Filter by maximum price
+ type: string
+ - name: id
+ in: path
+ required: true
+ description: Cart prefixed ID
schema:
- type: number
- - name: q[with_option_value_ids][]
- in: query
- required: false
- description: Filter by option value prefix IDs
+ type: string
+ responses:
+ '204':
+ description: cart deleted
+ "/api/v3/store/carts/{id}/associate":
+ patch:
+ summary: Associate guest cart with authenticated user
+ tags:
+ - Carts
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: |
+ Associates a guest cart with the currently authenticated user.
+ Requires JWT authentication. The cart must not belong to another user.
+ x-codeSamples:
+ - lang: javascript
+ label: Spree SDK
+ source: |-
+ import { createClient } from '@spree/sdk'
+
+ const client = createClient({
+ baseUrl: 'https://your-store.com',
+ publishableKey: '<api-key>',
+ })
+
+ const cart = await client.carts.associate('cart_abc123', {
+ bearerToken: '<token>',
+ })
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
schema:
type: string
- - name: q[in_stock]
- in: query
- required: false
- description: Filter to only in-stock products
+ - name: Authorization
+ in: header
+ required: true
schema:
- type: boolean
- - name: fields
- in: query
- required: false
- description: Comma-separated list of fields to include (e.g., name,slug,price).
- id is always included.
+ type: string
+ - name: id
+ in: path
+ required: true
+ description: Cart prefixed ID
schema:
type: string
responses:
'200':
- description: products found
+ description: cart associated successfully
content:
application/json:
example:
- data:
- - id: prod_UkLWZg9DAJ
- name: Product 207555
- description: |-
- Eaque est a odio at ut. Tenetur assumenda quos accusantium a autem. Pariatur hic nobis quae amet voluptas.
- Suscipit sequi alias velit nobis sapiente ipsam. Quam perferendis beatae autem praesentium et. Tempora dolores quia blanditiis ut assumenda. Mollitia enim dolor necessitatibus a.
- slug: product-207555
- meta_description:
- meta_keywords:
- variant_count: 0
- available_on: '2025-03-12T11:03:01.155Z'
- created_at: '2026-03-12T11:03:01.168Z'
- updated_at: '2026-03-12T11:03:01.180Z'
- purchasable: true
- in_stock: false
- backorderable: true
- available: true
- default_variant_id: variant_UkLWZg9DAJ
+ id: cart_UkLWZg9DAJ
+ number: R380993870
+ token: QePbYFDKav4JpkUPNqwz6eMvmMkgQhyQiZX
+ special_instructions:
+ currency: USD
+ locale: en
+ item_count: 1
+ item_total: '10.0'
+ display_item_total: "$10.00"
+ ship_total: '100.0'
+ display_ship_total: "$100.00"
+ adjustment_total: '0.0'
+ display_adjustment_total: "$0.00"
+ promo_total: '0.0'
+ display_promo_total: "$0.00"
+ tax_total: '0.0'
+ display_tax_total: "$0.00"
+ included_tax_total: '0.0'
+ display_included_tax_total: "$0.00"
+ additional_tax_total: '0.0'
+ display_additional_tax_total: "$0.00"
+ total: '110.0'
+ display_total: "$110.00"
+ created_at: '2026-03-13T10:53:25.692Z'
+ updated_at: '2026-03-13T10:53:25.750Z'
+ current_step: address
+ completed_steps: []
+ requirements:
+ - step: payment
+ field: payment
+ message: Add a payment method
+ promotions: []
+ items:
+ - id: li_UkLWZg9DAJ
+ variant_id: variant_UkLWZg9DAJ
+ quantity: 1
+ currency: USD
+ name: Product 85068
+ slug: product-85068
+ options_text: ''
+ price: '10.0'
+ display_price: "$10.00"
+ total: '10.0'
+ display_total: "$10.00"
+ adjustment_total: '0.0'
+ display_adjustment_total: "$0.00"
+ additional_tax_total: '0.0'
+ display_additional_tax_total: "$0.00"
+ included_tax_total: '0.0'
+ display_included_tax_total: "$0.00"
+ promo_total: '0.0'
+ display_promo_total: "$0.00"
+ pre_tax_amount: '10.0'
+ display_pre_tax_amount: "$10.00"
+ discounted_amount: '10.0'
+ display_discounted_amount: "$10.00"
+ display_compare_at_amount: "$0.00"
+ created_at: '2026-03-13T10:53:25.722Z'
+ updated_at: '2026-03-13T10:53:25.722Z'
+ compare_at_amount:
thumbnail_url:
- tags: []
- price:
- id: price_UkLWZg9DAJ
- amount: '19.99'
- amount_in_cents: 1999
- compare_at_amount:
- compare_at_amount_in_cents:
- currency: USD
- display_amount: "$19.99"
- display_compare_at_amount:
- price_list_id:
- original_price:
- meta:
- page: 1
- limit: 25
- count: 1
- pages: 1
- from: 1
- to: 1
- in: 1
- previous:
- next:
- schema:
- type: object
- properties:
- data:
- type: array
- items:
- "$ref": "#/components/schemas/Product"
- meta:
- "$ref": "#/components/schemas/PaginationMeta"
- '404':
- description: category not found
- content:
- application/json:
- example:
- error:
- code: record_not_found
- message: Category not found
+ option_values: []
+ digital_links: []
+ shipments:
+ - id: ship_UkLWZg9DAJ
+ number: H27925173096
+ state: pending
+ tracking: U10000
+ tracking_url:
+ cost: '100.0'
+ display_cost: "$100.00"
+ shipped_at:
+ created_at: '2026-03-13T10:53:25.727Z'
+ updated_at: '2026-03-13T10:53:25.745Z'
+ shipping_method:
+ id: shpm_UkLWZg9DAJ
+ name: UPS Ground
+ code: UPS_GROUND
+ stock_location:
+ id: sloc_UkLWZg9DAJ
+ state_abbr: STATE_ABBR_57
+ name: Cristy Deckow
+ address1: 1600 Pennsylvania Ave NW
+ city: Washington
+ zipcode: '20500'
+ country_iso: US
+ country_name: United States of America
+ state_text: STATE_ABBR_57
+ shipping_rates:
+ - id: shpr_UkLWZg9DAJ
+ shipping_method_id: shpm_UkLWZg9DAJ
+ name: UPS Ground
+ selected: true
+ cost: '100.0'
+ display_cost: "$100.00"
+ shipping_method:
+ id: shpm_UkLWZg9DAJ
+ name: UPS Ground
+ code: UPS_GROUND
+ payments: []
+ bill_address:
+ id: addr_UkLWZg9DAJ
+ firstname: John
+ lastname: Doe
+ full_name: John Doe
+ address1: 57 Lovely Street
+ address2: Northwest
+ city: Herndon
+ zipcode: '35005'
+ phone: 555-555-0199
+ company: Company
+ country_name: United States of America
+ country_iso: US
+ state_text: STATE_ABBR_57
+ state_abbr: STATE_ABBR_57
+ quick_checkout: false
+ state_name: STATE_NAME_57
+ ship_address:
+ id: addr_gbHJdmfrXB
+ firstname: John
+ lastname: Doe
+ full_name: John Doe
+ address1: 58 Lovely Street
+ address2: Northwest
+ city: Herndon
+ zipcode: '35005'
+ phone: 555-555-0199
+ company: Company
+ country_name: United States of America
+ country_iso: US
+ state_text: STATE_ABBR_58
+ state_abbr: STATE_ABBR_58
+ quick_checkout: false
+ state_name: STATE_NAME_58
+ payment_methods: []
schema:
- "$ref": "#/components/schemas/ErrorResponse"
+ "$ref": "#/components/schemas/Cart"
'401':
- description: unauthorized
+ description: unauthorized - JWT required
content:
application/json:
example:
error:
- code: invalid_token
- message: Valid API key required
+ code: authentication_required
+ message: Authentication required
schema:
"$ref": "#/components/schemas/ErrorResponse"
- "/api/v3/store/checkout":
- patch:
- summary: Update checkout
+ "/api/v3/store/carts/{id}/complete":
+ post:
+ summary: Complete cart
tags:
- - Checkout
+ - Carts
security:
- api_key: []
bearer_auth: []
- description: Updates checkout info (email, addresses, special instructions).
- When addresses change, the order state is reverted to address to ensure shipments
- are recalculated.
+ description: Completes the cart and finalizes the purchase. Returns an Order
+ (not Cart).
x-codeSamples:
- lang: javascript
label: Spree SDK
@@ -2150,18 +1979,7 @@ paths:
publishableKey: '<api-key>',
})
- const cart = await client.checkout.update({
- email: '[email protected]',
- ship_address: {
- firstname: 'John',
- lastname: 'Doe',
- address1: '123 Main St',
- city: 'New York',
- zipcode: '10001',
- country_iso: 'US',
- state_abbr: 'NY',
- },
- }, {
+ const order = await client.carts.complete('cart_abc123', {
bearerToken: '<token>',
})
parameters:
@@ -2180,30 +1998,31 @@ paths:
required: false
schema:
type: string
- - name: Idempotency-Key
- in: header
- required: false
- description: Unique key for request idempotency.
+ - name: id
+ in: path
+ required: true
+ description: Cart prefixed ID
schema:
type: string
responses:
'200':
- description: checkout updated
+ description: cart completed
content:
application/json:
example:
- id: cart_UkLWZg9DAJ
- number: R124919587
- token: CcPjjKoNocxpAkTCuuras5KqfDEabpmxHsA
- special_instructions: Leave at door
+ id: or_UkLWZg9DAJ
+ number: R549828527
+ special_instructions:
currency: USD
locale: en
item_count: 1
- item_total: '10.0'
- display_item_total: "$10.00"
- ship_total: '100.0'
- display_ship_total: "$100.00"
+ shipment_state: backorder
+ payment_state: paid
+ item_total: '19.99'
+ display_item_total: "$19.99"
+ ship_total: '10.0'
+ display_ship_total: "$10.00"
adjustment_total: '0.0'
display_adjustment_total: "$0.00"
promo_total: '0.0'
@@ -2214,29 +2033,24 @@ paths:
display_included_tax_total: "$0.00"
additional_tax_total: '0.0'
display_additional_tax_total: "$0.00"
- total: '110.0'
- display_total: "$110.00"
- created_at: '2026-03-12T11:03:02.103Z'
- updated_at: '2026-03-12T11:03:02.169Z'
- current_step: address
- completed_steps: []
- requirements:
- - step: payment
- field: payment
- message: Add a payment method
+ total: '29.99'
+ display_total: "$29.99"
+ completed_at: '2026-03-13T10:53:27.193Z'
+ created_at: '2026-03-13T10:53:26.982Z'
+ updated_at: '2026-03-13T10:53:27.193Z'
promotions: []
items:
- id: li_UkLWZg9DAJ
variant_id: variant_UkLWZg9DAJ
quantity: 1
currency: USD
- name: Product 232670
- slug: product-232670
+ name: Product 104377
+ slug: product-104377
options_text: ''
- price: '10.0'
- display_price: "$10.00"
- total: '10.0'
- display_total: "$10.00"
+ price: '19.99'
+ display_price: "$19.99"
+ total: '19.99'
+ display_total: "$19.99"
adjustment_total: '0.0'
display_adjustment_total: "$0.00"
additional_tax_total: '0.0'
@@ -2245,60 +2059,86 @@ paths:
display_included_tax_total: "$0.00"
promo_total: '0.0'
display_promo_total: "$0.00"
- pre_tax_amount: '10.0'
- display_pre_tax_amount: "$10.00"
- discounted_amount: '10.0'
- display_discounted_amount: "$10.00"
+ pre_tax_amount: '19.99'
+ display_pre_tax_amount: "$19.99"
+ discounted_amount: '19.99'
+ display_discounted_amount: "$19.99"
display_compare_at_amount: "$0.00"
- created_at: '2026-03-12T11:03:02.131Z'
- updated_at: '2026-03-12T11:03:02.131Z'
+ created_at: '2026-03-13T10:53:27.014Z'
+ updated_at: '2026-03-13T10:53:27.064Z'
compare_at_amount:
thumbnail_url:
option_values: []
digital_links: []
shipments:
- - id: ship_UkLWZg9DAJ
- number: H83568061706
+ - id: ship_gbHJdmfrXB
+ number: H93700831239
state: pending
- tracking: U10000
+ tracking:
tracking_url:
- cost: '100.0'
- display_cost: "$100.00"
+ cost: '10.0'
+ display_cost: "$10.00"
shipped_at:
- created_at: '2026-03-12T11:03:02.136Z'
- updated_at: '2026-03-12T11:03:02.149Z'
+ created_at: '2026-03-13T10:53:27.077Z'
+ updated_at: '2026-03-13T10:53:27.187Z'
shipping_method:
id: shpm_UkLWZg9DAJ
name: UPS Ground
code: UPS_GROUND
stock_location:
id: sloc_UkLWZg9DAJ
- state_abbr: STATE_ABBR_86
- name: See Kirlin
+ state_abbr: STATE_ABBR_63
+ name: Sommer Hilll
address1: 1600 Pennsylvania Ave NW
city: Washington
zipcode: '20500'
country_iso: US
country_name: United States of America
- state_text: STATE_ABBR_86
+ state_text: STATE_ABBR_63
shipping_rates:
- - id: shpr_UkLWZg9DAJ
+ - id: shpr_gbHJdmfrXB
shipping_method_id: shpm_UkLWZg9DAJ
name: UPS Ground
selected: true
- cost: '100.0'
- display_cost: "$100.00"
+ cost: '10.0'
+ display_cost: "$10.00"
shipping_method:
id: shpm_UkLWZg9DAJ
name: UPS Ground
code: UPS_GROUND
- payments: []
+ payments:
+ - id: py_UkLWZg9DAJ
+ payment_method_id: pm_UkLWZg9DAJ
+ state: completed
+ response_code: '12345'
+ number: PCTKFQCI
+ amount: '29.99'
+ display_amount: "$29.99"
+ created_at: '2026-03-13T10:53:27.147Z'
+ updated_at: '2026-03-13T10:53:27.174Z'
+ source_type: credit_card
+ source_id: card_UkLWZg9DAJ
+ source:
+ id: card_UkLWZg9DAJ
+ cc_type: visa
+ last_digits: '1111'
+ month: 12
+ year: 2027
+ name: Spree Commerce
+ default: false
+ gateway_payment_profile_id:
+ payment_method:
+ id: pm_UkLWZg9DAJ
+ name: Check
+ description:
+ type: Spree::PaymentMethod::Check
+ session_required: false
bill_address:
id: addr_EfhxLZ9ck8
firstname: John
lastname: Doe
full_name: John Doe
- address1: 77 Lovely Street
+ address1: 65 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -2306,16 +2146,16 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_88
- state_abbr: STATE_ABBR_88
+ state_text: STATE_ABBR_65
+ state_abbr: STATE_ABBR_65
quick_checkout: false
- state_name: STATE_NAME_88
+ state_name: STATE_NAME_65
ship_address:
id: addr_VqXmZF31wY
firstname: John
lastname: Doe
full_name: John Doe
- address1: 78 Lovely Street
+ address1: 66 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -2323,85 +2163,175 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_89
- state_abbr: STATE_ABBR_89
+ state_text: STATE_ABBR_66
+ state_abbr: STATE_ABBR_66
quick_checkout: false
- state_name: STATE_NAME_89
- payment_methods: []
+ state_name: STATE_NAME_66
+ schema:
+ "$ref": "#/components/schemas/Order"
+ '422':
+ description: cannot complete
+ content:
+ application/json:
+ example:
+ error:
+ code: cart_already_completed
+ message: No payment found
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ "/api/v3/store/categories":
+ get:
+ summary: List categories
+ tags:
+ - Product Catalog
+ security:
+ - api_key: []
+ description: Returns a paginated list of categories for the current store
+ x-codeSamples:
+ - lang: javascript
+ label: Spree SDK
+ source: |-
+ import { createClient } from '@spree/sdk'
+
+ const client = createClient({
+ baseUrl: 'https://your-store.com',
+ publishableKey: '<api-key>',
+ })
+
+ const categories = await client.categories.list({
+ page: 1,
+ limit: 25,
+ })
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: page
+ in: query
+ required: false
+ schema:
+ type: integer
+ - name: limit
+ in: query
+ required: false
+ schema:
+ type: integer
+ - name: q[name_cont]
+ in: query
+ required: false
+ description: Filter by name
+ schema:
+ type: string
+ - name: fields
+ in: query
+ required: false
+ description: Comma-separated list of fields to include (e.g., name,slug,price).
+ id is always included.
+ schema:
+ type: string
+ responses:
+ '200':
+ description: categories found
+ content:
+ application/json:
+ example:
+ data:
+ - id: ctg_UkLWZg9DAJ
+ name: taxonomy_1
+ permalink: taxonomy-1
+ position: 0
+ depth: 0
+ meta_title:
+ meta_description:
+ meta_keywords:
+ children_count: 1
+ created_at: '2026-03-13T10:53:27.924Z'
+ updated_at: '2026-03-13T10:53:27.976Z'
+ parent_id:
+ description: ''
+ description_html: ''
+ image_url:
+ square_image_url:
+ is_root: true
+ is_child: false
+ is_leaf: false
+ - id: ctg_gbHJdmfrXB
+ name: taxon_1
+ permalink: taxonomy-1/taxon-1
+ position: 0
+ depth: 1
+ meta_title:
+ meta_description:
+ meta_keywords:
+ children_count: 1
+ created_at: '2026-03-13T10:53:27.931Z'
+ updated_at: '2026-03-13T10:53:27.975Z'
+ parent_id: ctg_UkLWZg9DAJ
+ description: ''
+ description_html: ''
+ image_url:
+ square_image_url:
+ is_root: false
+ is_child: true
+ is_leaf: false
+ - id: ctg_EfhxLZ9ck8
+ name: taxon_2
+ permalink: taxonomy-1/taxon-1/taxon-2
+ position: 0
+ depth: 2
+ meta_title:
+ meta_description:
+ meta_keywords:
+ children_count: 0
+ created_at: '2026-03-13T10:53:27.941Z'
+ updated_at: '2026-03-13T10:53:27.948Z'
+ parent_id: ctg_gbHJdmfrXB
+ description: ''
+ description_html: ''
+ image_url:
+ square_image_url:
+ is_root: false
+ is_child: true
+ is_leaf: true
+ meta:
+ page: 1
+ limit: 25
+ count: 3
+ pages: 1
+ from: 1
+ to: 3
+ in: 3
+ previous:
+ next:
schema:
- "$ref": "#/components/schemas/Cart"
- requestBody:
- content:
- application/json:
- schema:
- type: object
- properties:
- email:
- type: string
- format: email
- special_instructions:
- type: string
- example: Leave at door
- metadata:
- type: object
- additionalProperties: true
- bill_address:
- type: object
- properties:
- firstname:
- type: string
- lastname:
- type: string
- address1:
- type: string
- address2:
- type: string
- city:
- type: string
- zipcode:
- type: string
- phone:
- type: string
- company:
- type: string
- country_iso:
- type: string
- state_abbr:
- type: string
- ship_address:
- type: object
- properties:
- firstname:
- type: string
- lastname:
- type: string
- address1:
- type: string
- address2:
- type: string
- city:
- type: string
- zipcode:
- type: string
- phone:
- type: string
- company:
- type: string
- country_iso:
- type: string
- state_abbr:
- type: string
- "/api/v3/store/checkout/complete":
- post:
- summary: Complete checkout
+ type: object
+ properties:
+ data:
+ type: array
+ items:
+ "$ref": "#/components/schemas/Category"
+ meta:
+ "$ref": "#/components/schemas/PaginationMeta"
+ '401':
+ description: unauthorized
+ content:
+ application/json:
+ example:
+ error:
+ code: invalid_token
+ message: Valid API key required
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ "/api/v3/store/categories/{id}":
+ get:
+ summary: Get a category
tags:
- - Checkout
+ - Product Catalog
security:
- api_key: []
- bearer_auth: []
- description: Completes the checkout and finalizes the purchase. Returns an Order
- (not Cart).
+ description: Returns a single category by permalink or prefix ID
x-codeSamples:
- lang: javascript
label: Spree SDK
@@ -2413,8 +2343,8 @@ paths:
publishableKey: '<api-key>',
})
- const order = await client.checkout.complete({
- bearerToken: '<token>',
+ const category = await client.categories.get('categories/clothing/shirts', {
+ expand: 'children',
})
parameters:
- name: x-spree-api-key
@@ -2422,204 +2352,235 @@ paths:
required: true
schema:
type: string
- - name: Authorization
- in: header
+ - name: id
+ in: path
+ required: true
+ description: Category permalink (e.g., clothing/shirts) or prefix ID (e.g.,
+ ctg_abc123)
+ schema:
+ type: string
+ - name: expand
+ in: query
required: false
+ description: Expand associations (children, parent, ancestors, metafields)
schema:
type: string
- - name: x-spree-token
- in: header
+ - name: fields
+ in: query
required: false
+ description: Comma-separated list of fields to include (e.g., name,slug,price).
+ id is always included.
schema:
type: string
- - name: Idempotency-Key
+ responses:
+ '200':
+ description: category found by prefix ID
+ content:
+ application/json:
+ example:
+ id: ctg_gbHJdmfrXB
+ name: taxon_10
+ permalink: taxonomy-7/taxon-10
+ position: 0
+ depth: 1
+ meta_title:
+ meta_description:
+ meta_keywords:
+ children_count: 1
+ created_at: '2026-03-13T10:53:28.311Z'
+ updated_at: '2026-03-13T10:53:28.347Z'
+ parent_id: ctg_UkLWZg9DAJ
+ description: ''
+ description_html: ''
+ image_url:
+ square_image_url:
+ is_root: false
+ is_child: true
+ is_leaf: false
+ schema:
+ "$ref": "#/components/schemas/Category"
+ '404':
+ description: category from other store not accessible
+ content:
+ application/json:
+ example:
+ error:
+ code: record_not_found
+ message: Category not found
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '401':
+ description: unauthorized
+ content:
+ application/json:
+ example:
+ error:
+ code: invalid_token
+ message: Valid API key required
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ "/api/v3/store/categories/{category_id}/products":
+ get:
+ summary: List products in a category
+ tags:
+ - Product Catalog
+ security:
+ - api_key: []
+ description: Returns a paginated list of products belonging to the specified
+ category
+ x-codeSamples:
+ - lang: javascript
+ label: Spree SDK
+ source: |-
+ import { createClient } from '@spree/sdk'
+
+ const client = createClient({
+ baseUrl: 'https://your-store.com',
+ publishableKey: '<api-key>',
+ })
+
+ const products = await client.categories.products.list('categories/clothing', {
+ page: 1,
+ limit: 25,
+ sort: 'price',
+ with_option_value_ids: ['optval_abc'],
+ })
+ parameters:
+ - name: x-spree-api-key
in: header
+ required: true
+ schema:
+ type: string
+ - name: category_id
+ in: path
+ required: true
+ description: Category permalink or prefix ID
+ schema:
+ type: string
+ - name: page
+ in: query
+ required: false
+ description: 'Page number (default: 1)'
+ schema:
+ type: integer
+ - name: limit
+ in: query
+ required: false
+ description: 'Number of items per page (default: 25, max: 100)'
+ schema:
+ type: integer
+ - name: sort
+ in: query
+ required: false
+ description: 'Sort order. Prefix with - for descending. Values: price, -price,
+ best_selling, name, -name, -available_on, available_on'
+ schema:
+ type: string
+ - name: q[price_gte]
+ in: query
+ required: false
+ description: Filter by minimum price
+ schema:
+ type: number
+ - name: q[price_lte]
+ in: query
+ required: false
+ description: Filter by maximum price
+ schema:
+ type: number
+ - name: q[with_option_value_ids][]
+ in: query
+ required: false
+ description: Filter by option value prefix IDs
+ schema:
+ type: string
+ - name: q[in_stock]
+ in: query
required: false
+ description: Filter to only in-stock products
+ schema:
+ type: boolean
+ - name: fields
+ in: query
+ required: false
+ description: Comma-separated list of fields to include (e.g., name,slug,price).
+ id is always included.
schema:
type: string
responses:
'200':
- description: checkout completed
+ description: products found
+ content:
+ application/json:
+ example:
+ data:
+ - id: prod_UkLWZg9DAJ
+ name: Product 194794
+ description: |-
+ Rem dolor laboriosam vel repellendus cupiditate impedit. Corporis velit aspernatur temporibus ex. Dolores dicta deserunt beatae repellendus atque. Omnis debitis blanditiis cumque autem inventore distinctio. Ipsa earum sunt qui similique.
+ Sint fuga iusto dicta non molestias repellat odit. Quia repellat quis veniam est fugit nihil. Quam nemo voluptates nostrum molestiae.
+ slug: product-194794
+ meta_description:
+ meta_keywords:
+ variant_count: 0
+ available_on: '2025-03-13T10:53:28.786Z'
+ created_at: '2026-03-13T10:53:28.800Z'
+ updated_at: '2026-03-13T10:53:28.815Z'
+ purchasable: true
+ in_stock: false
+ backorderable: true
+ available: true
+ default_variant_id: variant_UkLWZg9DAJ
+ thumbnail_url:
+ tags: []
+ price:
+ id: price_UkLWZg9DAJ
+ amount: '19.99'
+ amount_in_cents: 1999
+ compare_at_amount:
+ compare_at_amount_in_cents:
+ currency: USD
+ display_amount: "$19.99"
+ display_compare_at_amount:
+ price_list_id:
+ original_price:
+ meta:
+ page: 1
+ limit: 25
+ count: 1
+ pages: 1
+ from: 1
+ to: 1
+ in: 1
+ previous:
+ next:
+ schema:
+ type: object
+ properties:
+ data:
+ type: array
+ items:
+ "$ref": "#/components/schemas/Product"
+ meta:
+ "$ref": "#/components/schemas/PaginationMeta"
+ '404':
+ description: category not found
content:
application/json:
example:
- id: or_gbHJdmfrXB
- number: R100780089
- special_instructions:
- currency: USD
- locale: en
- item_count: 1
- shipment_state: backorder
- payment_state: paid
- item_total: '19.99'
- display_item_total: "$19.99"
- ship_total: '10.0'
- display_ship_total: "$10.00"
- adjustment_total: '0.0'
- display_adjustment_total: "$0.00"
- promo_total: '0.0'
- display_promo_total: "$0.00"
- tax_total: '0.0'
- display_tax_total: "$0.00"
- included_tax_total: '0.0'
- display_included_tax_total: "$0.00"
- additional_tax_total: '0.0'
- display_additional_tax_total: "$0.00"
- total: '29.99'
- display_total: "$29.99"
- completed_at: '2026-03-12T11:03:02.983Z'
- created_at: '2026-03-12T11:03:02.773Z'
- updated_at: '2026-03-12T11:03:02.983Z'
- promotions: []
- items:
- - id: li_gbHJdmfrXB
- variant_id: variant_gbHJdmfrXB
- quantity: 1
- currency: USD
- name: Product 251301
- slug: product-251301
- options_text: ''
- price: '19.99'
- display_price: "$19.99"
- total: '19.99'
- display_total: "$19.99"
- adjustment_total: '0.0'
- display_adjustment_total: "$0.00"
- additional_tax_total: '0.0'
- display_additional_tax_total: "$0.00"
- included_tax_total: '0.0'
- display_included_tax_total: "$0.00"
- promo_total: '0.0'
- display_promo_total: "$0.00"
- pre_tax_amount: '19.99'
- display_pre_tax_amount: "$19.99"
- discounted_amount: '19.99'
- display_discounted_amount: "$19.99"
- display_compare_at_amount: "$0.00"
- created_at: '2026-03-12T11:03:02.799Z'
- updated_at: '2026-03-12T11:03:02.844Z'
- compare_at_amount:
- thumbnail_url:
- option_values: []
- digital_links: []
- shipments:
- - id: ship_EfhxLZ9ck8
- number: H33943132790
- state: pending
- tracking:
- tracking_url:
- cost: '10.0'
- display_cost: "$10.00"
- shipped_at:
- created_at: '2026-03-12T11:03:02.862Z'
- updated_at: '2026-03-12T11:03:02.976Z'
- shipping_method:
- id: shpm_UkLWZg9DAJ
- name: UPS Ground
- code: UPS_GROUND
- stock_location:
- id: sloc_UkLWZg9DAJ
- state_abbr: STATE_ABBR_90
- name: Beryl Cronin
- address1: 1600 Pennsylvania Ave NW
- city: Washington
- zipcode: '20500'
- country_iso: US
- country_name: United States of America
- state_text: STATE_ABBR_90
- shipping_rates:
- - id: shpr_EfhxLZ9ck8
- shipping_method_id: shpm_UkLWZg9DAJ
- name: UPS Ground
- selected: true
- cost: '10.0'
- display_cost: "$10.00"
- shipping_method:
- id: shpm_UkLWZg9DAJ
- name: UPS Ground
- code: UPS_GROUND
- - id: shpr_VqXmZF31wY
- shipping_method_id: shpm_gbHJdmfrXB
- name: UPS Ground
- selected: false
- cost: '10.0'
- display_cost: "$10.00"
- shipping_method:
- id: shpm_gbHJdmfrXB
- name: UPS Ground
- code: UPS_GROUND
- payments:
- - id: py_UkLWZg9DAJ
- payment_method_id: pm_UkLWZg9DAJ
- state: completed
- response_code: '12345'
- number: PYQ1LRYR
- amount: '29.99'
- display_amount: "$29.99"
- created_at: '2026-03-12T11:03:02.938Z'
- updated_at: '2026-03-12T11:03:02.963Z'
- source_type: credit_card
- source_id: card_UkLWZg9DAJ
- source:
- id: card_UkLWZg9DAJ
- cc_type: visa
- last_digits: '1111'
- month: 12
- year: 2027
- name: Spree Commerce
- default: false
- gateway_payment_profile_id:
- payment_method:
- id: pm_UkLWZg9DAJ
- name: Check
- description:
- type: Spree::PaymentMethod::Check
- session_required: false
- bill_address:
- id: addr_uw2YK1rnl0
- firstname: John
- lastname: Doe
- full_name: John Doe
- address1: 83 Lovely Street
- address2: Northwest
- city: Herndon
- zipcode: '35005'
- phone: 555-555-0199
- company: Company
- country_name: United States of America
- country_iso: US
- state_text: STATE_ABBR_94
- state_abbr: STATE_ABBR_94
- quick_checkout: false
- state_name: STATE_NAME_94
- ship_address:
- id: addr_OIJLhNcSbf
- firstname: John
- lastname: Doe
- full_name: John Doe
- address1: 84 Lovely Street
- address2: Northwest
- city: Herndon
- zipcode: '35005'
- phone: 555-555-0199
- company: Company
- country_name: United States of America
- country_iso: US
- state_text: STATE_ABBR_95
- state_abbr: STATE_ABBR_95
- quick_checkout: false
- state_name: STATE_NAME_95
+ error:
+ code: record_not_found
+ message: Category not found
schema:
- "$ref": "#/components/schemas/Order"
- '422':
- description: cannot complete
+ "$ref": "#/components/schemas/ErrorResponse"
+ '401':
+ description: unauthorized
content:
application/json:
example:
error:
- code: order_already_completed
- message: No payment found
+ code: invalid_token
+ message: Valid API key required
schema:
"$ref": "#/components/schemas/ErrorResponse"
"/api/v3/store/countries":
@@ -2664,7 +2625,7 @@ paths:
example:
data:
- iso: DE
- iso3: IS24
+ iso3: IS21
name: Germany
states_required: false
zipcode_required: true
@@ -2772,11 +2733,11 @@ paths:
message: Country not found
schema:
"$ref": "#/components/schemas/ErrorResponse"
- "/api/v3/store/cart/coupon_codes":
+ "/api/v3/store/carts/{cart_id}/coupon_codes":
post:
summary: Apply coupon code
tags:
- - Cart
+ - Carts
security:
- api_key: []
bearer_auth: []
@@ -2794,7 +2755,7 @@ paths:
publishableKey: '<api-key>',
})
- const cart = await client.cart.couponCodes.apply('SAVE10', {
+ const cart = await client.carts.couponCodes.apply('cart_abc123', 'SAVE10', {
bearerToken: '<token>',
})
parameters:
@@ -2815,6 +2776,12 @@ paths:
description: Order token for guest access
schema:
type: string
+ - name: cart_id
+ in: path
+ required: true
+ description: Cart prefixed ID (e.g., cart_abc123)
+ schema:
+ type: string
- name: Idempotency-Key
in: header
required: false
@@ -2828,9 +2795,9 @@ paths:
application/json:
example:
id: cart_UkLWZg9DAJ
- number: R335281823
- token: Rz7WFUsVFaJZyJ5nN6quMc22YPebxccFCuR
+ number: R473422016
+ token: f7SSah883rNjSyij3HF6JrGPBx4FuD5Gtid
special_instructions:
currency: USD
locale: en
@@ -2851,8 +2818,8 @@ paths:
display_additional_tax_total: "$0.00"
total: '110.0'
display_total: "$110.00"
- created_at: '2026-03-12T11:03:05.129Z'
- updated_at: '2026-03-12T11:03:05.228Z'
+ created_at: '2026-03-13T10:53:30.644Z'
+ updated_at: '2026-03-13T10:53:30.749Z'
current_step: address
completed_steps: []
requirements: []
@@ -2862,8 +2829,8 @@ paths:
variant_id: variant_UkLWZg9DAJ
quantity: 1
currency: USD
- name: Product 289663
- slug: product-289663
+ name: Product 239969
+ slug: product-239969
options_text: ''
price: '10.0'
display_price: "$10.00"
@@ -2882,37 +2849,37 @@ paths:
discounted_amount: '10.0'
display_discounted_amount: "$10.00"
display_compare_at_amount: "$0.00"
- created_at: '2026-03-12T11:03:05.155Z'
- updated_at: '2026-03-12T11:03:05.155Z'
+ created_at: '2026-03-13T10:53:30.670Z'
+ updated_at: '2026-03-13T10:53:30.670Z'
compare_at_amount:
thumbnail_url:
option_values: []
digital_links: []
shipments:
- id: ship_UkLWZg9DAJ
- number: H16772496724
+ number: H43709142175
state: pending
tracking: U10000
tracking_url:
cost: '100.0'
display_cost: "$100.00"
shipped_at:
- created_at: '2026-03-12T11:03:05.161Z'
- updated_at: '2026-03-12T11:03:05.174Z'
+ created_at: '2026-03-13T10:53:30.675Z'
+ updated_at: '2026-03-13T10:53:30.688Z'
shipping_method:
id: shpm_UkLWZg9DAJ
name: UPS Ground
code: UPS_GROUND
stock_location:
id: sloc_UkLWZg9DAJ
- state_abbr: STATE_ABBR_104
- name: Wenona Bins
+ state_abbr: STATE_ABBR_85
+ name: Mikel Cassin
address1: 1600 Pennsylvania Ave NW
city: Washington
zipcode: '20500'
country_iso: US
country_name: United States of America
- state_text: STATE_ABBR_104
+ state_text: STATE_ABBR_85
shipping_rates:
- id: shpr_UkLWZg9DAJ
shipping_method_id: shpm_UkLWZg9DAJ
@@ -2928,12 +2895,12 @@ paths:
- id: py_UkLWZg9DAJ
payment_method_id: pm_UkLWZg9DAJ
state: checkout
- response_code: 1-SC-20260312110305221962
- number: P2QKMSSD
+ response_code: 1-SC-20260313105330740941
+ number: PCRIEH05
amount: '50.0'
display_amount: "$50.00"
- created_at: '2026-03-12T11:03:05.223Z'
- updated_at: '2026-03-12T11:03:05.223Z'
+ created_at: '2026-03-13T10:53:30.743Z'
+ updated_at: '2026-03-13T10:53:30.743Z'
source_type: store_credit
source_id: credit_UkLWZg9DAJ
source:
@@ -2956,7 +2923,7 @@ paths:
firstname: John
lastname: Doe
full_name: John Doe
- address1: 95 Lovely Street
+ address1: 77 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -2964,16 +2931,16 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_106
- state_abbr: STATE_ABBR_106
+ state_text: STATE_ABBR_87
+ state_abbr: STATE_ABBR_87
quick_checkout: false
- state_name: STATE_NAME_106
+ state_name: STATE_NAME_87
ship_address:
id: addr_VqXmZF31wY
firstname: John
lastname: Doe
full_name: John Doe
- address1: 96 Lovely Street
+ address1: 78 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -2981,10 +2948,10 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_107
- state_abbr: STATE_ABBR_107
+ state_text: STATE_ABBR_88
+ state_abbr: STATE_ABBR_88
quick_checkout: false
- state_name: STATE_NAME_107
+ state_name: STATE_NAME_88
payment_methods:
- id: pm_UkLWZg9DAJ
name: Store Credit
@@ -3015,11 +2982,11 @@ paths:
description: Coupon code or gift card code to apply
required:
- code
- "/api/v3/store/cart/coupon_codes/{id}":
+ "/api/v3/store/carts/{cart_id}/coupon_codes/{id}":
delete:
summary: Remove coupon code
tags:
- - Cart
+ - Carts
security:
- api_key: []
bearer_auth: []
@@ -3036,7 +3003,7 @@ paths:
publishableKey: '<api-key>',
})
- const cart = await client.cart.couponCodes.remove('SAVE10', {
+ const cart = await client.carts.couponCodes.remove('cart_abc123', 'SAVE10', {
bearerToken: '<token>',
})
parameters:
@@ -3051,6 +3018,12 @@ paths:
description: Bearer token for authenticated customers
schema:
type: string
+ - name: cart_id
+ in: path
+ required: true
+ description: Cart prefixed ID
+ schema:
+ type: string
- name: id
in: path
required: true
@@ -3070,9 +3043,9 @@ paths:
application/json:
example:
id: cart_UkLWZg9DAJ
- number: R968960758
- token: WGRRA4PHnCcd9T1WakVGN3pYUR6g6Fv6A2Z
+ number: R152972004
+ token: Zom2xk6V5brXSLW3PuW6wouEqZPRngtaM3x
special_instructions:
currency: USD
locale: en
@@ -3093,8 +3066,8 @@ paths:
display_additional_tax_total: "$0.00"
total: '110.0'
display_total: "$110.00"
- created_at: '2026-03-12T11:03:06.388Z'
- updated_at: '2026-03-12T11:03:06.496Z'
+ created_at: '2026-03-13T10:53:31.922Z'
+ updated_at: '2026-03-13T10:53:32.029Z'
current_step: address
completed_steps: []
requirements:
@@ -3107,8 +3080,8 @@ paths:
variant_id: variant_UkLWZg9DAJ
quantity: 1
currency: USD
- name: Product 301309
- slug: product-301309
+ name: Product 257387
+ slug: product-257387
options_text: ''
price: '10.0'
display_price: "$10.00"
@@ -3127,37 +3100,37 @@ paths:
discounted_amount: '10.0'
display_discounted_amount: "$10.00"
display_compare_at_amount: "$0.00"
- created_at: '2026-03-12T11:03:06.416Z'
- updated_at: '2026-03-12T11:03:06.490Z'
+ created_at: '2026-03-13T10:53:31.951Z'
+ updated_at: '2026-03-13T10:53:32.023Z'
compare_at_amount:
thumbnail_url:
option_values: []
digital_links: []
shipments:
- id: ship_UkLWZg9DAJ
- number: H93628650111
+ number: H91587073653
state: pending
tracking: U10000
tracking_url:
cost: '100.0'
display_cost: "$100.00"
shipped_at:
- created_at: '2026-03-12T11:03:06.421Z'
- updated_at: '2026-03-12T11:03:06.433Z'
+ created_at: '2026-03-13T10:53:31.957Z'
+ updated_at: '2026-03-13T10:53:31.971Z'
shipping_method:
id: shpm_UkLWZg9DAJ
name: UPS Ground
code: UPS_GROUND
stock_location:
id: sloc_UkLWZg9DAJ
- state_abbr: STATE_ABBR_112
- name: Fanny Turcotte
+ state_abbr: STATE_ABBR_93
+ name: Evelyne Zulauf
address1: 1600 Pennsylvania Ave NW
city: Washington
zipcode: '20500'
country_iso: US
country_name: United States of America
- state_text: STATE_ABBR_112
+ state_text: STATE_ABBR_93
shipping_rates:
- id: shpr_UkLWZg9DAJ
shipping_method_id: shpm_UkLWZg9DAJ
@@ -3175,7 +3148,7 @@ paths:
firstname: John
lastname: Doe
full_name: John Doe
- address1: 103 Lovely Street
+ address1: 85 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -3183,16 +3156,16 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_114
- state_abbr: STATE_ABBR_114
+ state_text: STATE_ABBR_95
+ state_abbr: STATE_ABBR_95
quick_checkout: false
- state_name: STATE_NAME_114
+ state_name: STATE_NAME_95
ship_address:
id: addr_VqXmZF31wY
firstname: John
lastname: Doe
full_name: John Doe
- address1: 104 Lovely Street
+ address1: 86 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -3200,10 +3173,10 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_115
- state_abbr: STATE_ABBR_115
+ state_text: STATE_ABBR_96
+ state_abbr: STATE_ABBR_96
quick_checkout: false
- state_name: STATE_NAME_115
+ state_name: STATE_NAME_96
payment_methods: []
schema:
"$ref": "#/components/schemas/Cart"
@@ -3543,8 +3516,8 @@ paths:
example:
data:
- id: or_UkLWZg9DAJ
- number: R430787068
+ number: R925925425
special_instructions:
currency: USD
locale: en
@@ -3567,17 +3540,17 @@ paths:
display_additional_tax_total: "$0.00"
total: '110.0'
display_total: "$110.00"
- completed_at: '2026-03-12T11:03:11.132Z'
- created_at: '2026-03-12T11:03:11.082Z'
- updated_at: '2026-03-12T11:03:11.132Z'
+ completed_at: '2026-03-13T10:53:36.696Z'
+ created_at: '2026-03-13T10:53:36.596Z'
+ updated_at: '2026-03-13T10:53:36.696Z'
promotions: []
items:
- id: li_UkLWZg9DAJ
variant_id: variant_UkLWZg9DAJ
quantity: 1
currency: USD
- name: Product 324126
- slug: product-324126
+ name: Product 2713
+ slug: product-2713
options_text: ''
price: '10.0'
display_price: "$10.00"
@@ -3596,37 +3569,37 @@ paths:
discounted_amount: '10.0'
display_discounted_amount: "$10.00"
display_compare_at_amount: "$0.00"
- created_at: '2026-03-12T11:03:11.113Z'
- updated_at: '2026-03-12T11:03:11.113Z'
+ created_at: '2026-03-13T10:53:36.653Z'
+ updated_at: '2026-03-13T10:53:36.653Z'
compare_at_amount:
thumbnail_url:
option_values: []
digital_links: []
shipments:
- id: ship_UkLWZg9DAJ
- number: H87399186637
+ number: H77126100403
state: pending
tracking: U10000
tracking_url:
cost: '100.0'
display_cost: "$100.00"
shipped_at:
- created_at: '2026-03-12T11:03:11.117Z'
- updated_at: '2026-03-12T11:03:11.130Z'
+ created_at: '2026-03-13T10:53:36.664Z'
+ updated_at: '2026-03-13T10:53:36.692Z'
shipping_method:
id: shpm_UkLWZg9DAJ
name: UPS Ground
code: UPS_GROUND
stock_location:
id: sloc_UkLWZg9DAJ
- state_abbr: STATE_ABBR_132
- name: Sherell Hammes
+ state_abbr: STATE_ABBR_113
+ name: Patti Langworth
address1: 1600 Pennsylvania Ave NW
city: Washington
zipcode: '20500'
country_iso: US
country_name: United States of America
- state_text: STATE_ABBR_132
+ state_text: STATE_ABBR_113
shipping_rates:
- id: shpr_gbHJdmfrXB
shipping_method_id: shpm_UkLWZg9DAJ
@@ -3644,7 +3617,7 @@ paths:
firstname: John
lastname: Doe
full_name: John Doe
- address1: 123 Lovely Street
+ address1: 105 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -3652,16 +3625,16 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_134
- state_abbr: STATE_ABBR_134
+ state_text: STATE_ABBR_115
+ state_abbr: STATE_ABBR_115
quick_checkout: false
- state_name: STATE_NAME_134
+ state_name: STATE_NAME_115
ship_address:
id: addr_VqXmZF31wY
firstname: John
lastname: Doe
full_name: John Doe
- address1: 124 Lovely Street
+ address1: 106 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -3669,10 +3642,10 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_135
- state_abbr: STATE_ABBR_135
+ state_text: STATE_ABBR_116
+ state_abbr: STATE_ABBR_116
quick_checkout: false
- state_name: STATE_NAME_135
+ state_name: STATE_NAME_116
meta:
page: 1
limit: 25
@@ -3740,8 +3713,8 @@ paths:
application/json:
example:
id: or_UkLWZg9DAJ
- number: R521038493
+ number: R085960061
special_instructions:
currency: USD
locale: en
@@ -3764,17 +3737,17 @@ paths:
display_additional_tax_total: "$0.00"
total: '110.0'
display_total: "$110.00"
- completed_at: '2026-03-12T11:03:11.810Z'
- created_at: '2026-03-12T11:03:11.757Z'
- updated_at: '2026-03-12T11:03:11.810Z'
+ completed_at: '2026-03-13T10:53:37.406Z'
+ created_at: '2026-03-13T10:53:37.355Z'
+ updated_at: '2026-03-13T10:53:37.406Z'
promotions: []
items:
- id: li_UkLWZg9DAJ
variant_id: variant_UkLWZg9DAJ
quantity: 1
currency: USD
- name: Product 341335
- slug: product-341335
+ name: Product 2943
+ slug: product-2943
options_text: ''
price: '10.0'
display_price: "$10.00"
@@ -3793,37 +3766,37 @@ paths:
discounted_amount: '10.0'
display_discounted_amount: "$10.00"
display_compare_at_amount: "$0.00"
- created_at: '2026-03-12T11:03:11.789Z'
- updated_at: '2026-03-12T11:03:11.789Z'
+ created_at: '2026-03-13T10:53:37.384Z'
+ updated_at: '2026-03-13T10:53:37.384Z'
compare_at_amount:
thumbnail_url:
option_values: []
digital_links: []
shipments:
- id: ship_UkLWZg9DAJ
- number: H80054789977
+ number: H57096957541
state: pending
tracking: U10000
tracking_url:
cost: '100.0'
display_cost: "$100.00"
shipped_at:
- created_at: '2026-03-12T11:03:11.795Z'
- updated_at: '2026-03-12T11:03:11.808Z'
+ created_at: '2026-03-13T10:53:37.389Z'
+ updated_at: '2026-03-13T10:53:37.404Z'
shipping_method:
id: shpm_UkLWZg9DAJ
name: UPS Ground
code: UPS_GROUND
stock_location:
id: sloc_UkLWZg9DAJ
- state_abbr: STATE_ABBR_138
- name: Zoraida Abshire
+ state_abbr: STATE_ABBR_119
+ name: Marvin Funk
address1: 1600 Pennsylvania Ave NW
city: Washington
zipcode: '20500'
country_iso: US
country_name: United States of America
- state_text: STATE_ABBR_138
+ state_text: STATE_ABBR_119
shipping_rates:
- id: shpr_gbHJdmfrXB
shipping_method_id: shpm_UkLWZg9DAJ
@@ -3841,7 +3814,7 @@ paths:
firstname: John
lastname: Doe
full_name: John Doe
- address1: 129 Lovely Street
+ address1: 111 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -3849,16 +3822,16 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_140
- state_abbr: STATE_ABBR_140
+ state_text: STATE_ABBR_121
+ state_abbr: STATE_ABBR_121
quick_checkout: false
- state_name: STATE_NAME_140
+ state_name: STATE_NAME_121
ship_address:
id: addr_VqXmZF31wY
firstname: John
lastname: Doe
full_name: John Doe
- address1: 130 Lovely Street
+ address1: 112 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -3866,10 +3839,10 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_141
- state_abbr: STATE_ABBR_141
+ state_text: STATE_ABBR_122
+ state_abbr: STATE_ABBR_122
quick_checkout: false
- state_name: STATE_NAME_141
+ state_name: STATE_NAME_122
schema:
"$ref": "#/components/schemas/Order"
'404':
@@ -3879,9 +3852,7 @@ paths:
example:
error:
code: order_not_found
- message: Couldn't find Spree::Order with 'id'=1 [WHERE "spree_orders"."user_id"
- = ? AND "spree_orders"."store_id" = ? AND "spree_orders"."completed_at"
- IS NOT NULL]
+ message: Order not found
schema:
"$ref": "#/components/schemas/ErrorResponse"
"/api/v3/store/customers":
@@ -3925,7 +3896,7 @@ paths:
content:
application/json:
example:
- token: eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX3R5cGUiOiJjdXN0b21lciIsImp0aSI6ImI4ZDdhYmFkLTg1ZTUtNGI4My1hMmUyLWQ4NTMxYTU1OGM4MyIsImlzcyI6InNwcmVlIiwiYXVkIjoic3RvcmVfYXBpIiwiZXhwIjoxNzczMzE2OTkzfQ.euOfxsfqQPaintG2O49t4gOuHuTPRcVROHNE27iwTmQ
+ token: eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX3R5cGUiOiJjdXN0b21lciIsImp0aSI6ImMwNTBkYWI4LWQxNGMtNGRjMi1hYzYyLWJjNTI5OTlmOTA1NyIsImlzcyI6InNwcmVlIiwiYXVkIjoic3RvcmVfYXBpIiwiZXhwIjoxNzczNDAyODE4fQ.La66qT4qQPNuswQDSRTfgVhpsJyBdO1gEHCd1pqM-n4
user:
id: cus_UkLWZg9DAJ
@@ -3933,8 +3904,8 @@ paths:
last_name: Doe
phone: "+1234567890"
accepts_email_marketing: true
- created_at: '2026-03-12T11:03:13.001Z'
- updated_at: '2026-03-12T11:03:13.001Z'
+ created_at: '2026-03-13T10:53:38.584Z'
+ updated_at: '2026-03-13T10:53:38.584Z'
addresses: []
default_billing_address:
default_shipping_address:
@@ -4038,19 +4009,19 @@ paths:
application/json:
example:
id: cus_UkLWZg9DAJ
- first_name: Bailey
- last_name: Moore
+ first_name: Albert
+ last_name: Lynch
phone: 555-555-0199
accepts_email_marketing: false
- created_at: '2026-03-12T11:03:13.554Z'
- updated_at: '2026-03-12T11:03:13.820Z'
+ created_at: '2026-03-13T10:53:39.128Z'
+ updated_at: '2026-03-13T10:53:39.396Z'
addresses:
- id: addr_gbHJdmfrXB
firstname: John
lastname: Doe
full_name: John Doe
- address1: 136 Lovely Street
+ address1: 118 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -4058,15 +4029,15 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_147
- state_abbr: STATE_ABBR_147
+ state_text: STATE_ABBR_128
+ state_abbr: STATE_ABBR_128
quick_checkout: false
- state_name: STATE_NAME_147
+ state_name: STATE_NAME_128
- id: addr_UkLWZg9DAJ
firstname: John
lastname: Doe
full_name: John Doe
- address1: 135 Lovely Street
+ address1: 117 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -4074,16 +4045,16 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_146
- state_abbr: STATE_ABBR_146
+ state_text: STATE_ABBR_127
+ state_abbr: STATE_ABBR_127
quick_checkout: false
- state_name: STATE_NAME_146
+ state_name: STATE_NAME_127
default_billing_address:
id: addr_gbHJdmfrXB
firstname: John
lastname: Doe
full_name: John Doe
- address1: 136 Lovely Street
+ address1: 118 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -4091,16 +4062,16 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_147
- state_abbr: STATE_ABBR_147
+ state_text: STATE_ABBR_128
+ state_abbr: STATE_ABBR_128
quick_checkout: false
- state_name: STATE_NAME_147
+ state_name: STATE_NAME_128
default_shipping_address:
id: addr_UkLWZg9DAJ
firstname: John
lastname: Doe
full_name: John Doe
- address1: 135 Lovely Street
+ address1: 117 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -4108,10 +4079,10 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_146
- state_abbr: STATE_ABBR_146
+ state_text: STATE_ABBR_127
+ state_abbr: STATE_ABBR_127
quick_checkout: false
- state_name: STATE_NAME_146
+ state_name: STATE_NAME_127
schema:
"$ref": "#/components/schemas/Customer"
'401':
@@ -4168,19 +4139,19 @@ paths:
application/json:
example:
id: cus_UkLWZg9DAJ
first_name: Updated
last_name: Name
phone: 555-555-0199
accepts_email_marketing: false
- created_at: '2026-03-12T11:03:14.111Z'
- updated_at: '2026-03-12T11:03:14.388Z'
+ created_at: '2026-03-13T10:53:39.690Z'
+ updated_at: '2026-03-13T10:53:39.972Z'
addresses:
- id: addr_gbHJdmfrXB
firstname: John
lastname: Doe
full_name: John Doe
- address1: 138 Lovely Street
+ address1: 120 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -4188,15 +4159,15 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_149
- state_abbr: STATE_ABBR_149
+ state_text: STATE_ABBR_130
+ state_abbr: STATE_ABBR_130
quick_checkout: false
- state_name: STATE_NAME_149
+ state_name: STATE_NAME_130
- id: addr_UkLWZg9DAJ
firstname: John
lastname: Doe
full_name: John Doe
- address1: 137 Lovely Street
+ address1: 119 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -4204,16 +4175,16 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_148
- state_abbr: STATE_ABBR_148
+ state_text: STATE_ABBR_129
+ state_abbr: STATE_ABBR_129
quick_checkout: false
- state_name: STATE_NAME_148
+ state_name: STATE_NAME_129
default_billing_address:
id: addr_gbHJdmfrXB
firstname: John
lastname: Doe
full_name: John Doe
- address1: 138 Lovely Street
+ address1: 120 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -4221,16 +4192,16 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_149
- state_abbr: STATE_ABBR_149
+ state_text: STATE_ABBR_130
+ state_abbr: STATE_ABBR_130
quick_checkout: false
- state_name: STATE_NAME_149
+ state_name: STATE_NAME_130
default_shipping_address:
id: addr_UkLWZg9DAJ
firstname: John
lastname: Doe
full_name: John Doe
- address1: 137 Lovely Street
+ address1: 119 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -4238,10 +4209,10 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_148
- state_abbr: STATE_ABBR_148
+ state_text: STATE_ABBR_129
+ state_abbr: STATE_ABBR_129
quick_checkout: false
- state_name: STATE_NAME_148
+ state_name: STATE_NAME_129
schema:
"$ref": "#/components/schemas/Customer"
'422':
@@ -4398,7 +4369,7 @@ paths:
example:
data:
- id: gc_UkLWZg9DAJ
- code: E27753D43EB9B7E2
+ code: 741011ADA83424F9
state: active
currency: USD
amount: '10.0'
@@ -4412,8 +4383,8 @@ paths:
redeemed_at:
expired: false
active: true
- created_at: '2026-03-12T11:03:17.415Z'
- updated_at: '2026-03-12T11:03:17.415Z'
+ created_at: '2026-03-13T10:53:43.044Z'
+ updated_at: '2026-03-13T10:53:43.044Z'
meta:
page: 1
limit: 25
@@ -4496,7 +4467,7 @@ paths:
application/json:
example:
id: gc_UkLWZg9DAJ
- code: '081CBB2948E5FF8C'
+ code: 27A26F8AF471EDB4
state: active
currency: USD
amount: '10.0'
@@ -4510,8 +4481,8 @@ paths:
redeemed_at:
expired: false
active: true
- created_at: '2026-03-12T11:03:18.499Z'
- updated_at: '2026-03-12T11:03:18.499Z'
+ created_at: '2026-03-13T10:53:44.126Z'
+ updated_at: '2026-03-13T10:53:44.126Z'
schema:
"$ref": "#/components/schemas/GiftCard"
'404':
@@ -4524,11 +4495,11 @@ paths:
message: Gift card not found
schema:
"$ref": "#/components/schemas/ErrorResponse"
- "/api/v3/store/cart/items":
+ "/api/v3/store/carts/{cart_id}/items":
post:
summary: Add item to cart
tags:
- - Cart
+ - Carts
security:
- api_key: []
bearer_auth: []
@@ -4545,7 +4516,7 @@ paths:
publishableKey: '<api-key>',
})
- const cart = await client.cart.items.add({
+ const cart = await client.carts.items.create('cart_abc123', {
variant_id: 'variant_abc123',
quantity: 2,
}, {
@@ -4569,6 +4540,12 @@ paths:
description: Order token for guest access
schema:
type: string
+ - name: cart_id
+ in: path
+ required: true
+ description: Cart prefixed ID (e.g., cart_abc123)
+ schema:
+ type: string
- name: Idempotency-Key
in: header
required: false
@@ -4582,9 +4559,9 @@ paths:
application/json:
example:
id: cart_UkLWZg9DAJ
- number: R812647036
- token: LrfNbFy45m7JE9oZWj2XD3MtWAXT1U6UJsD
+ number: R520651117
+ token: ictwbFtBrVp7cKXFFFaWzhAc7gT8PioXv2z
special_instructions:
currency: USD
locale: en
@@ -4605,8 +4582,8 @@ paths:
display_additional_tax_total: "$0.00"
total: '29.99'
display_total: "$29.99"
- created_at: '2026-03-12T11:03:20.231Z'
- updated_at: '2026-03-12T11:03:20.374Z'
+ created_at: '2026-03-13T10:53:45.870Z'
+ updated_at: '2026-03-13T10:53:45.985Z'
current_step: address
completed_steps: []
requirements:
@@ -4625,8 +4602,8 @@ paths:
variant_id: variant_UkLWZg9DAJ
quantity: 1
currency: USD
- name: Product 445365
- slug: product-445365
+ name: Product 391667
+ slug: product-391667
options_text: ''
price: '10.0'
display_price: "$10.00"
@@ -4645,8 +4622,8 @@ paths:
discounted_amount: '10.0'
display_discounted_amount: "$10.00"
display_compare_at_amount: "$0.00"
- created_at: '2026-03-12T11:03:20.269Z'
- updated_at: '2026-03-12T11:03:20.269Z'
+ created_at: '2026-03-13T10:53:45.910Z'
+ updated_at: '2026-03-13T10:53:45.910Z'
compare_at_amount:
thumbnail_url:
option_values: []
@@ -4655,8 +4632,8 @@ paths:
variant_id: variant_gbHJdmfrXB
quantity: 1
currency: USD
- name: Product 458064
- slug: product-458064
+ name: Product 409634
+ slug: product-409634
options_text: ''
price: '19.99'
display_price: "$19.99"
@@ -4675,8 +4652,8 @@ paths:
discounted_amount: '19.99'
display_discounted_amount: "$19.99"
display_compare_at_amount: "$0.00"
- created_at: '2026-03-12T11:03:20.319Z'
- updated_at: '2026-03-12T11:03:20.319Z'
+ created_at: '2026-03-13T10:53:45.959Z'
+ updated_at: '2026-03-13T10:53:45.959Z'
compare_at_amount:
thumbnail_url:
option_values: []
@@ -4688,7 +4665,7 @@ paths:
firstname: John
lastname: Doe
full_name: John Doe
- address1: 166 Lovely Street
+ address1: 148 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -4696,10 +4673,10 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_177
- state_abbr: STATE_ABBR_177
+ state_text: STATE_ABBR_158
+ state_abbr: STATE_ABBR_158
quick_checkout: false
- state_name: STATE_NAME_177
+ state_name: STATE_NAME_158
ship_address:
payment_methods: []
schema:
@@ -4736,11 +4713,11 @@ paths:
gift_message: Happy Birthday!
required:
- variant_id
- "/api/v3/store/cart/items/{id}":
+ "/api/v3/store/carts/{cart_id}/items/{id}":
patch:
summary: Update line item quantity
tags:
- - Cart
+ - Carts
security:
- api_key: []
bearer_auth: []
@@ -4756,7 +4733,7 @@ paths:
publishableKey: '<api-key>',
})
- const cart = await client.cart.items.update('li_abc123', {
+ const cart = await client.carts.items.update('cart_abc123', 'li_abc123', {
quantity: 5,
}, {
bearerToken: '<token>',
@@ -4772,6 +4749,12 @@ paths:
required: false
schema:
type: string
+ - name: cart_id
+ in: path
+ required: true
+ description: Cart prefixed ID
+ schema:
+ type: string
- name: id
in: path
required: true
@@ -4790,9 +4773,9 @@ paths:
application/json:
example:
id: cart_UkLWZg9DAJ
- number: R048104757
- token: HcCquBCDtvPmM7GiNr578fEsaU1o6q5tV2Q
+ number: R355187117
+ token: P96jb41bg7g6gRPrZ8wDntby1LKYEpNfznw
special_instructions:
currency: USD
locale: en
@@ -4813,8 +4796,8 @@ paths:
display_additional_tax_total: "$0.00"
total: '0.0'
display_total: "$0.00"
- created_at: '2026-03-12T11:03:22.117Z'
- updated_at: '2026-03-12T11:03:22.145Z'
+ created_at: '2026-03-13T10:53:47.764Z'
+ updated_at: '2026-03-13T10:53:47.798Z'
current_step: address
completed_steps: []
requirements:
@@ -4830,8 +4813,8 @@ paths:
variant_id: variant_UkLWZg9DAJ
quantity: 1
currency: USD
- name: Product 484149
- slug: product-484149
+ name: Product 433446
+ slug: product-433446
options_text: ''
price: '10.0'
display_price: "$10.00"
@@ -4850,8 +4833,8 @@ paths:
discounted_amount: '10.0'
display_discounted_amount: "$10.00"
display_compare_at_amount: "$0.00"
- created_at: '2026-03-12T11:03:22.145Z'
- updated_at: '2026-03-12T11:03:22.161Z'
+ created_at: '2026-03-13T10:53:47.797Z'
+ updated_at: '2026-03-13T10:53:47.815Z'
compare_at_amount:
thumbnail_url:
option_values: []
@@ -4863,7 +4846,7 @@ paths:
firstname: John
lastname: Doe
full_name: John Doe
- address1: 175 Lovely Street
+ address1: 157 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -4871,10 +4854,10 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_186
- state_abbr: STATE_ABBR_186
+ state_text: STATE_ABBR_167
+ state_abbr: STATE_ABBR_167
quick_checkout: false
- state_name: STATE_NAME_186
+ state_name: STATE_NAME_167
ship_address:
payment_methods: []
schema:
@@ -4898,7 +4881,7 @@ paths:
delete:
summary: Remove line item from cart
tags:
- - Cart
+ - Carts
security:
- api_key: []
bearer_auth: []
@@ -4914,7 +4897,7 @@ paths:
publishableKey: '<api-key>',
})
- const cart = await client.cart.items.remove('li_abc123', {
+ const cart = await client.carts.items.delete('cart_abc123', 'li_abc123', {
bearerToken: '<token>',
})
parameters:
@@ -4928,6 +4911,12 @@ paths:
required: false
schema:
type: string
+ - name: cart_id
+ in: path
+ required: true
+ description: Cart prefixed ID
+ schema:
+ type: string
- name: id
in: path
required: true
@@ -4945,9 +4934,9 @@ paths:
application/json:
example:
id: cart_UkLWZg9DAJ
- number: R610522316
- token: 3ptdcsZnLpYqCffEYFphF6geVxHGG2iXGqe
+ number: R214734034
+ token: RF2oMDC3BiH96UZyyQ6tGJpybkGN49AJBDS
special_instructions:
currency: USD
locale: en
@@ -4968,8 +4957,8 @@ paths:
display_additional_tax_total: "$0.00"
total: '0.0'
display_total: "$0.00"
- created_at: '2026-03-12T11:03:22.703Z'
- updated_at: '2026-03-12T11:03:22.751Z'
+ created_at: '2026-03-13T10:53:48.386Z'
+ updated_at: '2026-03-13T10:53:48.451Z'
current_step: address
completed_steps: []
requirements:
@@ -4991,7 +4980,7 @@ paths:
firstname: John
lastname: Doe
full_name: John Doe
- address1: 178 Lovely Street
+ address1: 160 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -4999,10 +4988,10 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_189
- state_abbr: STATE_ABBR_189
+ state_text: STATE_ABBR_170
+ state_abbr: STATE_ABBR_170
quick_checkout: false
- state_name: STATE_NAME_189
+ state_name: STATE_NAME_170
ship_address:
payment_methods: []
schema:
@@ -5148,12 +5137,12 @@ paths:
- fr
countries:
- iso: DE
- iso3: IS45
+ iso3: IS42
name: Germany
states_required: false
zipcode_required: true
- iso: FR
- iso3: IS46
+ iso3: IS43
name: France
states_required: false
zipcode_required: true
@@ -5232,12 +5221,12 @@ paths:
- fr
countries:
- iso: DE
- iso3: IS49
+ iso3: IS46
name: Germany
states_required: false
zipcode_required: true
- iso: FR
- iso3: IS50
+ iso3: IS47
name: France
states_required: false
zipcode_required: true
@@ -5250,9 +5239,7 @@ paths:
example:
error:
code: record_not_found
- message: Couldn't find Spree::Market with 'id'=245546638656678833
- [WHERE "spree_markets"."deleted_at" IS NULL AND "spree_markets"."store_id"
- = ?]
+ message: Market not found
schema:
"$ref": "#/components/schemas/ErrorResponse"
"/api/v3/store/markets/resolve":
@@ -5314,12 +5301,12 @@ paths:
- fr
countries:
- iso: DE
- iso3: IS53
+ iso3: IS50
name: Germany
states_required: false
zipcode_required: true
- iso: FR
- iso3: IS54
+ iso3: IS51
name: France
states_required: false
zipcode_required: true
@@ -5383,12 +5370,12 @@ paths:
example:
data:
- iso: FR
- iso3: IS58
+ iso3: IS55
name: France
states_required: false
zipcode_required: true
- iso: DE
- iso3: IS57
+ iso3: IS54
name: Germany
states_required: false
zipcode_required: true
@@ -5523,7 +5510,7 @@ paths:
application/json:
example:
id: or_UkLWZg9DAJ
- number: R902483276
+ number: R517298683
special_instructions:
currency: USD
@@ -5547,17 +5534,17 @@ paths:
display_additional_tax_total: "$0.00"
total: '110.0'
display_total: "$110.00"
- completed_at: '2026-03-12T11:03:24.589Z'
- created_at: '2026-03-12T11:03:24.544Z'
- updated_at: '2026-03-12T11:03:24.589Z'
+ completed_at: '2026-03-13T10:53:50.370Z'
+ created_at: '2026-03-13T10:53:50.309Z'
+ updated_at: '2026-03-13T10:53:50.370Z'
promotions: []
items:
- id: li_UkLWZg9DAJ
variant_id: variant_UkLWZg9DAJ
quantity: 1
currency: USD
- name: Product 528624
- slug: product-528624
+ name: Product 474977
+ slug: product-474977
options_text: ''
price: '10.0'
display_price: "$10.00"
@@ -5576,37 +5563,37 @@ paths:
discounted_amount: '10.0'
display_discounted_amount: "$10.00"
display_compare_at_amount: "$0.00"
- created_at: '2026-03-12T11:03:24.571Z'
- updated_at: '2026-03-12T11:03:24.571Z'
+ created_at: '2026-03-13T10:53:50.346Z'
+ updated_at: '2026-03-13T10:53:50.346Z'
compare_at_amount:
thumbnail_url:
option_values: []
digital_links: []
shipments:
- id: ship_UkLWZg9DAJ
- number: H75029097237
+ number: H22253242565
state: pending
tracking: U10000
tracking_url:
cost: '100.0'
display_cost: "$100.00"
shipped_at:
- created_at: '2026-03-12T11:03:24.575Z'
- updated_at: '2026-03-12T11:03:24.587Z'
+ created_at: '2026-03-13T10:53:50.352Z'
+ updated_at: '2026-03-13T10:53:50.368Z'
shipping_method:
id: shpm_UkLWZg9DAJ
name: UPS Ground
code: UPS_GROUND
stock_location:
id: sloc_UkLWZg9DAJ
- state_abbr: STATE_ABBR_197
- name: Jo Padberg
+ state_abbr: STATE_ABBR_178
+ name: Myesha Erdman
address1: 1600 Pennsylvania Ave NW
city: Washington
zipcode: '20500'
country_iso: US
country_name: United States of America
- state_text: STATE_ABBR_197
+ state_text: STATE_ABBR_178
shipping_rates:
- id: shpr_gbHJdmfrXB
shipping_method_id: shpm_UkLWZg9DAJ
@@ -5624,7 +5611,7 @@ paths:
firstname: John
lastname: Doe
full_name: John Doe
- address1: 186 Lovely Street
+ address1: 168 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -5632,16 +5619,16 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_197
- state_abbr: STATE_ABBR_197
+ state_text: STATE_ABBR_178
+ state_abbr: STATE_ABBR_178
quick_checkout: false
- state_name: STATE_NAME_197
+ state_name: STATE_NAME_178
ship_address:
id: addr_gbHJdmfrXB
firstname: John
lastname: Doe
full_name: John Doe
- address1: 187 Lovely Street
+ address1: 169 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -5649,10 +5636,10 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_198
- state_abbr: STATE_ABBR_198
+ state_text: STATE_ABBR_179
+ state_abbr: STATE_ABBR_179
quick_checkout: false
- state_name: STATE_NAME_198
+ state_name: STATE_NAME_179
schema:
"$ref": "#/components/schemas/Order"
'404':
@@ -5662,16 +5649,14 @@ paths:
example:
error:
code: order_not_found
- message: Couldn't find Spree::Order with 'id'=1 [WHERE "spree_orders"."store_id"
- = ? AND "spree_orders"."completed_at" IS NOT NULL AND "spree_orders"."user_id"
- = ?]
+ message: Order not found
schema:
"$ref": "#/components/schemas/ErrorResponse"
- "/api/v3/store/checkout/payment_methods":
+ "/api/v3/store/carts/{cart_id}/payment_methods":
get:
summary: List available payment methods
tags:
- - Checkout
+ - Carts
security:
- api_key: []
bearer_auth: []
@@ -5688,7 +5673,7 @@ paths:
publishableKey: '<api-key>',
})
- const methods = await client.checkout.paymentMethods.list({
+ const methods = await client.carts.paymentMethods.list('cart_abc123', {
bearerToken: '<token>',
})
parameters:
@@ -5703,6 +5688,12 @@ paths:
description: Bearer token for authenticated customers
schema:
type: string
+ - name: cart_id
+ in: path
+ required: true
+ description: Cart prefixed ID (e.g., cart_abc123)
+ schema:
+ type: string
- name: x-spree-token
in: header
required: false
@@ -5735,17 +5726,17 @@ paths:
properties:
count:
type: integer
- "/api/v3/store/checkout/payment_sessions":
+ "/api/v3/store/carts/{cart_id}/payment_sessions":
post:
summary: Create payment session
tags:
- - Checkout
+ - Carts
security:
- api_key: []
bearer_auth: []
- description: Creates a new payment session for the current cart. Delegates to
- the payment gateway to initialize a provider-specific session (e.g. Stripe
- PaymentIntent, Adyen session, PayPal order).
+ description: Creates a new payment session for the cart. Delegates to the payment
+ gateway to initialize a provider-specific session (e.g. Stripe PaymentIntent,
+ Adyen session, PayPal order).
x-codeSamples:
- lang: javascript
label: Spree SDK
@@ -5757,7 +5748,7 @@ paths:
publishableKey: '<api-key>',
})
- const session = await client.checkout.paymentSessions.create({
+ const session = await client.carts.paymentSessions.create('cart_abc123', {
payment_method_id: 'pm_abc123',
}, {
bearerToken: '<token>',
@@ -5774,6 +5765,12 @@ paths:
description: Bearer token for authenticated customers
schema:
type: string
+ - name: cart_id
+ in: path
+ required: true
+ description: Cart prefixed ID (e.g., cart_abc123)
+ schema:
+ type: string
- name: x-spree-token
in: header
required: false
@@ -5795,13 +5792,13 @@ paths:
id: ps_gbHJdmfrXB
status: pending
currency: USD
- external_id: bogus_0908915197a432f75f23ec94
+ external_id: bogus_c1526626d193bf755f2ef14e
external_data:
- client_secret: bogus_secret_cbc5c78c1fa0cc68
+ client_secret: bogus_secret_0a06a81f9e706212
customer_external_id:
expires_at:
- created_at: '2026-03-12T11:03:26.992Z'
- updated_at: '2026-03-12T11:03:26.992Z'
+ created_at: '2026-03-13T10:53:52.916Z'
+ updated_at: '2026-03-13T10:53:52.916Z'
amount: '110.0'
payment_method_id: pm_UkLWZg9DAJ
order_id: or_UkLWZg9DAJ
@@ -5833,7 +5830,7 @@ paths:
description: Provider-specific data passed to the gateway
required:
- payment_method_id
- "/api/v3/store/checkout/payment_sessions/{id}":
+ "/api/v3/store/carts/{cart_id}/payment_sessions/{id}":
parameters:
- name: x-spree-api-key
in: header
@@ -5846,6 +5843,12 @@ paths:
description: Bearer token for authenticated customers
schema:
type: string
+ - name: cart_id
+ in: path
+ required: true
+ description: Cart prefixed ID
+ schema:
+ type: string
- name: id
in: path
required: true
@@ -5861,7 +5864,7 @@ paths:
get:
summary: Get payment session
tags:
- - Checkout
+ - Carts
security:
- api_key: []
bearer_auth: []
@@ -5878,7 +5881,7 @@ paths:
publishableKey: '<api-key>',
})
- const session = await client.checkout.paymentSessions.get('ps_abc123', {
+ const session = await client.carts.paymentSessions.get('cart_abc123', 'ps_abc123', {
bearerToken: '<token>',
})
responses:
@@ -5890,13 +5893,13 @@ paths:
id: ps_UkLWZg9DAJ
status: pending
currency: USD
- external_id: bogus_805c9e470e9e60b226c649bb
+ external_id: bogus_6dbb9758c4b189b1d5c7ffe7
external_data:
client_secret: secret_123
customer_external_id:
expires_at:
- created_at: '2026-03-12T11:03:27.586Z'
- updated_at: '2026-03-12T11:03:27.586Z'
+ created_at: '2026-03-13T10:53:53.546Z'
+ updated_at: '2026-03-13T10:53:53.546Z'
amount: '110.0'
payment_method_id: pm_UkLWZg9DAJ
order_id: or_UkLWZg9DAJ
@@ -5921,7 +5924,7 @@ paths:
patch:
summary: Update payment session
tags:
- - Checkout
+ - Carts
security:
- api_key: []
bearer_auth: []
@@ -5938,7 +5941,7 @@ paths:
publishableKey: '<api-key>',
})
- const session = await client.checkout.paymentSessions.update('ps_abc123', {
+ const session = await client.carts.paymentSessions.update('cart_abc123', 'ps_abc123', {
amount: '50.00',
}, {
bearerToken: '<token>',
@@ -5953,13 +5956,13 @@ paths:
id: ps_UkLWZg9DAJ
status: pending
currency: USD
- external_id: bogus_e3691aaa7b754cb6a5723c32
+ external_id: bogus_ee4d9dc3663d5385214c77fc
external_data:
client_secret: secret_123
customer_external_id:
expires_at:
- created_at: '2026-03-12T11:03:28.810Z'
- updated_at: '2026-03-12T11:03:28.824Z'
+ created_at: '2026-03-13T10:53:54.828Z'
+ updated_at: '2026-03-13T10:53:54.843Z'
amount: '50.0'
payment_method_id: pm_UkLWZg9DAJ
order_id: or_UkLWZg9DAJ
@@ -5984,7 +5987,7 @@ paths:
external_data:
type: object
description: Provider-specific data to update
- "/api/v3/store/checkout/payment_sessions/{id}/complete":
+ "/api/v3/store/carts/{cart_id}/payment_sessions/{id}/complete":
parameters:
- name: x-spree-api-key
in: header
@@ -5997,6 +6000,12 @@ paths:
description: Bearer token for authenticated customers
schema:
type: string
+ - name: cart_id
+ in: path
+ required: true
+ description: Cart prefixed ID
+ schema:
+ type: string
- name: id
in: path
required: true
@@ -6012,7 +6021,7 @@ paths:
patch:
summary: Complete payment session
tags:
- - Checkout
+ - Carts
security:
- api_key: []
bearer_auth: []
@@ -6029,7 +6038,7 @@ paths:
publishableKey: '<api-key>',
})
- const session = await client.checkout.paymentSessions.complete('ps_abc123', {
+ const session = await client.carts.paymentSessions.complete('cart_abc123', 'ps_abc123', {
session_result: 'success',
}, {
bearerToken: '<token>',
@@ -6050,13 +6059,13 @@ paths:
id: ps_UkLWZg9DAJ
status: completed
currency: USD
- external_id: bogus_6efe50f584e39ef71d8a51d6
+ external_id: bogus_90ce9dc0139afabe92818af3
external_data:
client_secret: secret_123
customer_external_id:
expires_at:
- created_at: '2026-03-12T11:03:29.415Z'
- updated_at: '2026-03-12T11:03:29.429Z'
+ created_at: '2026-03-13T10:53:55.487Z'
+ updated_at: '2026-03-13T10:53:55.502Z'
amount: '110.0'
payment_method_id: pm_UkLWZg9DAJ
order_id: or_UkLWZg9DAJ
@@ -6136,11 +6145,11 @@ paths:
example:
id: pss_gbHJdmfrXB
status: pending
- external_id: bogus_seti_fd739262d1cf8622d6120f9b
- external_client_secret: bogus_seti_secret_2278cd088f53287f
+ external_id: bogus_seti_78ca1ac9bf6720645f9a7484
+ external_client_secret: bogus_seti_secret_f902125b47dd802b
external_data: {}
- created_at: '2026-03-12T11:03:30.597Z'
- updated_at: '2026-03-12T11:03:30.597Z'
+ created_at: '2026-03-13T10:53:56.726Z'
+ updated_at: '2026-03-13T10:53:56.726Z'
payment_method_id: pm_UkLWZg9DAJ
payment_source_id:
payment_source_type:
@@ -6237,12 +6246,12 @@ paths:
example:
id: pss_UkLWZg9DAJ
status: pending
- external_id: seti_test_b2aba257abc62d90c6a578e7
- external_client_secret: seti_secret_24386d85df69122030fb709a
+ external_id: seti_test_85ffddc05333ec2cb73a4646
+ external_client_secret: seti_secret_86eb6c07702ac25be489938e
external_data:
client_secret: secret_123
- created_at: '2026-03-12T11:03:32.243Z'
- updated_at: '2026-03-12T11:03:32.243Z'
+ created_at: '2026-03-13T10:53:58.480Z'
+ updated_at: '2026-03-13T10:53:58.480Z'
payment_method_id: pm_UkLWZg9DAJ
payment_source_id:
payment_source_type:
@@ -6315,12 +6324,12 @@ paths:
example:
id: pss_UkLWZg9DAJ
status: completed
- external_id: seti_test_a8725ff61951e1d4341fd93d
- external_client_secret: seti_secret_3b4c6c472bc6e8d08cf2127c
+ external_id: seti_test_726b12d2d5ebd64957c77302
+ external_client_secret: seti_secret_6d0f807178eb775a1bb28ff1
external_data:
client_secret: secret_123
- created_at: '2026-03-12T11:03:33.331Z'
- updated_at: '2026-03-12T11:03:33.344Z'
+ created_at: '2026-03-13T10:53:59.661Z'
+ updated_at: '2026-03-13T10:53:59.678Z'
payment_method_id: pm_UkLWZg9DAJ
payment_source_id: card_UkLWZg9DAJ
payment_source_type: Spree::CreditCard
@@ -6352,15 +6361,15 @@ paths:
external_data:
type: object
description: Provider-specific completion data
- "/api/v3/store/checkout/payments":
+ "/api/v3/store/carts/{cart_id}/payments":
get:
summary: List payments
tags:
- - Checkout
+ - Carts
security:
- api_key: []
bearer_auth: []
- description: Returns all payments for the current cart.
+ description: Returns all payments for the cart.
x-codeSamples:
- lang: javascript
label: Spree SDK
@@ -6372,7 +6381,7 @@ paths:
publishableKey: '<api-key>',
})
- const payments = await client.checkout.payments.list({
+ const payments = await client.carts.payments.list('cart_abc123', {
bearerToken: '<token>',
})
parameters:
@@ -6386,6 +6395,12 @@ paths:
required: false
schema:
type: string
+ - name: cart_id
+ in: path
+ required: true
+ description: Cart prefixed ID (e.g., cart_abc123)
+ schema:
+ type: string
- name: x-spree-token
in: header
required: false
@@ -6402,11 +6417,11 @@ paths:
payment_method_id: pm_UkLWZg9DAJ
state: checkout
response_code: '12345'
- number: PV2GSDE4
+ number: PAPIG76R
amount: '110.0'
display_amount: "$110.00"
- created_at: '2026-03-12T11:03:34.525Z'
- updated_at: '2026-03-12T11:03:34.525Z'
+ created_at: '2026-03-13T10:54:00.902Z'
+ updated_at: '2026-03-13T10:54:00.902Z'
source_type: credit_card
source_id: card_UkLWZg9DAJ
source:
@@ -6437,7 +6452,7 @@ paths:
post:
summary: Create payment
tags:
- - Checkout
+ - Carts
security:
- api_key: []
bearer_auth: []
@@ -6455,7 +6470,7 @@ paths:
publishableKey: '<api-key>',
})
- const payment = await client.checkout.createPayment({
+ const payment = await client.carts.payments.create('cart_abc123', {
payment_method_id: 'pm_abc123',
}, {
bearerToken: '<token>',
@@ -6471,6 +6486,12 @@ paths:
required: false
schema:
type: string
+ - name: cart_id
+ in: path
+ required: true
+ description: Cart prefixed ID
+ schema:
+ type: string
- name: x-spree-token
in: header
required: false
@@ -6487,11 +6508,11 @@ paths:
payment_method_id: pm_UkLWZg9DAJ
state: checkout
response_code:
- number: PIENLJLP
+ number: PDIN151Y
amount: '110.0'
display_amount: "$110.00"
- created_at: '2026-03-12T11:03:35.211Z'
- updated_at: '2026-03-12T11:03:35.211Z'
+ created_at: '2026-03-13T10:54:01.561Z'
+ updated_at: '2026-03-13T10:54:01.561Z'
source_type:
source_id:
source:
@@ -6648,19 +6669,18 @@ paths:
example:
data:
- id: prod_UkLWZg9DAJ
- name: Product 647331
+ name: Product 592545
description: |-
- Repellat debitis autem iste accusantium porro. Placeat quibusdam ad ex occaecati explicabo. Sed saepe explicabo iure mollitia minima occaecati qui ea. Neque aspernatur iste vitae dolorem architecto impedit maiores voluptates. Fugit voluptas aut voluptates vitae quibusdam.
- Sit corrupti illum consectetur dicta doloribus reprehenderit veritatis totam. Sed harum ratione ipsa doloribus. Dolorem repudiandae explicabo reiciendis sequi magnam ad molestiae. Ipsa ab itaque sint ex veniam quasi.
- Doloribus itaque ex corrupti temporibus. Architecto porro fuga accusamus tenetur nesciunt velit vero nostrum. Quod adipisci nisi incidunt praesentium eum veniam tempore. Nobis sequi provident quas ab alias voluptatem. Ipsam tempora eos est rem ullam modi laboriosam corporis.
- Voluptas quas officiis qui sed cupiditate id consectetur necessitatibus. Fugiat accusantium distinctio fuga non corporis. Incidunt autem veniam modi consequatur. Deserunt beatae eius rem inventore id doloribus.
- slug: product-647331
+ Sint ratione neque velit numquam deleniti perspiciatis. Quis nesciunt ut consequuntur quam explicabo. Hic nulla cupiditate illo sint recusandae odio. Pariatur ducimus culpa debitis nihil impedit reprehenderit. Ad accusantium autem quibusdam possimus atque.
+ Fugiat assumenda perferendis modi reiciendis velit dolorem. Architecto error fuga quia molestiae aspernatur. Aperiam tempora at fuga ea similique nobis sit doloremque.
+ Officiis laborum et voluptas reiciendis dolor incidunt. Suscipit repudiandae quod quidem excepturi laborum voluptatem. Placeat corporis rem vitae non corrupti.
+ slug: product-592545
meta_description:
meta_keywords:
variant_count: 1
- available_on: '2025-03-12T11:03:35.851Z'
- created_at: '2026-03-12T11:03:35.864Z'
- updated_at: '2026-03-12T11:03:35.903Z'
+ available_on: '2025-03-13T10:54:02.259Z'
+ created_at: '2026-03-13T10:54:02.275Z'
+ updated_at: '2026-03-13T10:54:02.324Z'
purchasable: true
in_stock: false
backorderable: true
@@ -6680,16 +6700,20 @@ paths:
price_list_id:
original_price:
- id: prod_gbHJdmfrXB
- name: Product 657176
- description: Omnis nesciunt quia vitae possimus. Minus dolor similique
- qui fuga quidem. Itaque quasi at asperiores id.
- slug: product-657176
+ name: Product 602680
+ description: |-
+ Incidunt asperiores voluptate vero non. Voluptate ipsum laborum fuga culpa dolor. Nobis eos cum vel suscipit. Exercitationem enim sint adipisci dicta tempora maxime quod aliquid.
+ Libero magni illum facilis nesciunt. Temporibus repellendus nihil quos ratione. Quia temporibus facilis saepe nobis minima. Fugit facilis debitis ex ipsam pariatur. Eligendi sed tempore sint itaque.
+ Quaerat ex possimus molestias voluptatibus culpa odio sapiente. Sunt ab natus consequatur possimus quaerat quod. A dignissimos ipsa quasi libero culpa. Magni numquam itaque delectus ipsam. Quam omnis rerum aspernatur neque quos accusantium at.
+ Asperiores qui modi dicta sint magni amet sequi. Voluptas aperiam autem aliquam iusto provident. Iste vero hic explicabo culpa. Totam molestiae veniam quam qui labore ipsam odio dicta.
+ Voluptatibus iure sunt fugit natus. Distinctio error perferendis totam qui nesciunt ipsum modi facere. Voluptas sapiente nihil earum facilis.
+ slug: product-602680
meta_description:
meta_keywords:
variant_count: 0
- available_on: '2025-03-12T11:03:35.908Z'
- created_at: '2026-03-12T11:03:35.917Z'
- updated_at: '2026-03-12T11:03:35.929Z'
+ available_on: '2025-03-13T10:54:02.330Z'
+ created_at: '2026-03-13T10:54:02.341Z'
+ updated_at: '2026-03-13T10:54:02.355Z'
purchasable: true
in_stock: false
backorderable: true
@@ -6795,20 +6819,19 @@ paths:
application/json:
example:
id: prod_UkLWZg9DAJ
- name: Product 763933
+ name: Product 717882
description: |-
- Omnis nihil aut libero fuga nulla minima itaque laudantium. Modi corrupti esse a dolorem quas ducimus repellat tenetur. Autem dolorum earum commodi occaecati ut nisi laboriosam blanditiis. Earum at repellat ea in corrupti. Labore aut facilis excepturi quae laudantium sunt consectetur.
- Quod excepturi incidunt explicabo repudiandae adipisci ipsam. Necessitatibus natus magni rem unde pariatur est. Consequatur unde quo doloremque ipsa deserunt sed aliquid. Doloremque omnis enim laboriosam quibusdam eum dolore sed.
- Id porro iste dolorum a occaecati molestias. Aut rem ex necessitatibus accusantium quasi aperiam. Debitis minima veritatis vel commodi autem dolor blanditiis.
- Consectetur cumque aliquid exercitationem accusantium itaque ratione necessitatibus cum. Non quidem architecto quibusdam quasi suscipit. Hic ipsum veniam veritatis recusandae.
- Iure rerum eligendi incidunt velit dignissimos consequatur. Aliquid deserunt itaque vitae molestiae dolorem sit modi repellendus. In cupiditate veritatis excepturi eveniet commodi pariatur beatae consequatur. Ullam repellat vel minus quia quaerat officia minima itaque.
- slug: product-763933
+ Voluptatibus quas eos accusamus eveniet saepe consectetur explicabo. Ad fugit illo perspiciatis molestiae cum. Laborum rem nam doloribus sequi dolorum voluptates ratione. Nobis quia delectus saepe blanditiis. Sequi nam omnis doloremque ipsam.
+ Reiciendis fuga ab voluptatum incidunt sit. Vel maiores beatae dicta ipsa sit rem. Dicta odit temporibus atque vero ratione. Ipsum rem praesentium nihil iure totam veniam doloribus.
+ Qui repellat accusamus voluptatibus perferendis quod maxime sed. Tempore soluta molestiae modi quidem. Iure ea distinctio ratione ullam quas facilis rerum.
+ Error nulla architecto quaerat possimus. Iusto nemo harum itaque corporis. Velit eligendi praesentium accusamus ducimus a atque occaecati.
+ slug: product-717882
meta_description:
meta_keywords:
variant_count: 1
- available_on: '2025-03-12T11:03:36.463Z'
- created_at: '2026-03-12T11:03:36.480Z'
- updated_at: '2026-03-12T11:03:36.517Z'
+ available_on: '2025-03-13T10:54:02.986Z'
+ created_at: '2026-03-13T10:54:03.004Z'
+ updated_at: '2026-03-13T10:54:03.045Z'
purchasable: true
in_stock: false
backorderable: true
@@ -6972,15 +6995,15 @@ paths:
message: Valid API key required
schema:
"$ref": "#/components/schemas/ErrorResponse"
- "/api/v3/store/checkout/shipments":
+ "/api/v3/store/carts/{cart_id}/shipments":
get:
summary: List shipments
tags:
- - Checkout
+ - Carts
security:
- api_key: []
bearer_auth: []
- description: Returns all shipments with shipping rates for the current cart.
+ description: Returns all shipments with shipping rates for the cart.
x-codeSamples:
- lang: javascript
label: Spree SDK
@@ -6992,7 +7015,7 @@ paths:
publishableKey: '<api-key>',
})
- const shipments = await client.checkout.shipments.list({
+ const shipments = await client.carts.shipments.list('cart_abc123', {
bearerToken: '<token>',
})
parameters:
@@ -7006,6 +7029,12 @@ paths:
required: false
schema:
type: string
+ - name: cart_id
+ in: path
+ required: true
+ description: Cart prefixed ID (e.g., cart_abc123)
+ schema:
+ type: string
- name: x-spree-token
in: header
required: false
@@ -7020,29 +7049,29 @@ paths:
example:
data:
- id: ship_UkLWZg9DAJ
- number: H40658723961
+ number: H10511607162
state: pending
tracking: U10000
tracking_url:
cost: '100.0'
display_cost: "$100.00"
shipped_at:
- created_at: '2026-03-12T11:03:38.450Z'
- updated_at: '2026-03-12T11:03:38.465Z'
+ created_at: '2026-03-13T10:54:05.142Z'
+ updated_at: '2026-03-13T10:54:05.158Z'
shipping_method:
id: shpm_UkLWZg9DAJ
name: UPS Ground
code: UPS_GROUND
stock_location:
id: sloc_UkLWZg9DAJ
- state_abbr: STATE_ABBR_269
- name: Georgeann Marquardt
+ state_abbr: STATE_ABBR_250
+ name: Kyla Lueilwitz
address1: 1600 Pennsylvania Ave NW
city: Washington
zipcode: '20500'
country_iso: US
country_name: United States of America
- state_text: STATE_ABBR_269
+ state_text: STATE_ABBR_250
shipping_rates:
- id: shpr_UkLWZg9DAJ
shipping_method_id: shpm_UkLWZg9DAJ
@@ -7056,11 +7085,11 @@ paths:
code: UPS_GROUND
meta:
count: 1
- "/api/v3/store/checkout/shipments/{id}":
+ "/api/v3/store/carts/{cart_id}/shipments/{id}":
patch:
summary: Select shipping rate for shipment
tags:
- - Checkout
+ - Carts
security:
- api_key: []
bearer_auth: []
@@ -7077,7 +7106,7 @@ paths:
publishableKey: '<api-key>',
})
- const cart = await client.checkout.shipments.update('ship_abc123', {
+ const cart = await client.carts.shipments.update('cart_abc123', 'ship_abc123', {
selected_shipping_rate_id: 'shpr_abc123',
}, {
bearerToken: '<token>',
@@ -7093,6 +7122,12 @@ paths:
required: false
schema:
type: string
+ - name: cart_id
+ in: path
+ required: true
+ description: Cart prefixed ID
+ schema:
+ type: string
- name: id
in: path
required: true
@@ -7112,9 +7147,9 @@ paths:
application/json:
example:
id: cart_UkLWZg9DAJ
- number: R214105735
- token: J21UZ987T6vdk8HLeuRfaf7zf1EFoqccMEM
+ number: R569739782
+ token: 9eYJphx4nGx8ghFa2Yk146RJjC4zvUsijps
special_instructions:
currency: USD
locale: en
@@ -7135,11 +7170,12 @@ paths:
display_additional_tax_total: "$0.00"
total: '110.0'
display_total: "$110.00"
- created_at: '2026-03-12T11:03:39.027Z'
- updated_at: '2026-03-12T11:03:39.101Z'
- current_step: delivery
+ created_at: '2026-03-13T10:54:05.740Z'
+ updated_at: '2026-03-13T10:54:05.831Z'
+ current_step: payment
completed_steps:
- address
+ - delivery
requirements:
- step: payment
field: payment
@@ -7150,8 +7186,8 @@ paths:
variant_id: variant_UkLWZg9DAJ
quantity: 1
currency: USD
- name: Product 1051948
- slug: product-1051948
+ name: Product 1004535
+ slug: product-1004535
options_text: ''
price: '10.0'
display_price: "$10.00"
@@ -7170,37 +7206,37 @@ paths:
discounted_amount: '10.0'
display_discounted_amount: "$10.00"
display_compare_at_amount: "$0.00"
- created_at: '2026-03-12T11:03:39.059Z'
- updated_at: '2026-03-12T11:03:39.059Z'
+ created_at: '2026-03-13T10:54:05.772Z'
+ updated_at: '2026-03-13T10:54:05.772Z'
compare_at_amount:
thumbnail_url:
option_values: []
digital_links: []
shipments:
- id: ship_UkLWZg9DAJ
- number: H17947471362
+ number: H91093012769
state: pending
tracking: U10000
tracking_url:
cost: '100.0'
display_cost: "$100.00"
shipped_at:
- created_at: '2026-03-12T11:03:39.066Z'
- updated_at: '2026-03-12T11:03:39.100Z'
+ created_at: '2026-03-13T10:54:05.777Z'
+ updated_at: '2026-03-13T10:54:05.816Z'
shipping_method:
id: shpm_UkLWZg9DAJ
name: UPS Ground
code: UPS_GROUND
stock_location:
id: sloc_UkLWZg9DAJ
- state_abbr: STATE_ABBR_273
- name: Alfonzo Simonis
+ state_abbr: STATE_ABBR_254
+ name: Roscoe Hayes
address1: 1600 Pennsylvania Ave NW
city: Washington
zipcode: '20500'
country_iso: US
country_name: United States of America
- state_text: STATE_ABBR_273
+ state_text: STATE_ABBR_254
shipping_rates:
- id: shpr_UkLWZg9DAJ
shipping_method_id: shpm_UkLWZg9DAJ
@@ -7218,7 +7254,7 @@ paths:
firstname: John
lastname: Doe
full_name: John Doe
- address1: 254 Lovely Street
+ address1: 236 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -7226,16 +7262,16 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_275
- state_abbr: STATE_ABBR_275
+ state_text: STATE_ABBR_256
+ state_abbr: STATE_ABBR_256
quick_checkout: false
- state_name: STATE_NAME_275
+ state_name: STATE_NAME_256
ship_address:
id: addr_VqXmZF31wY
firstname: John
lastname: Doe
full_name: John Doe
- address1: 255 Lovely Street
+ address1: 237 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -7243,10 +7279,10 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_276
- state_abbr: STATE_ABBR_276
+ state_text: STATE_ABBR_257
+ state_abbr: STATE_ABBR_257
quick_checkout: false
- state_name: STATE_NAME_276
+ state_name: STATE_NAME_257
payment_methods: []
schema:
"$ref": "#/components/schemas/Cart"
@@ -7257,8 +7293,7 @@ paths:
example:
error:
code: record_not_found
- message: Couldn't find Spree::ShippingRate with 'id'=31178106422
- [WHERE "spree_shipping_rates"."shipment_id" = ?]
+ message: Shipping rate not found
schema:
"$ref": "#/components/schemas/ErrorResponse"
requestBody:
@@ -7273,15 +7308,15 @@ paths:
description: Shipping rate ID to select
required:
- selected_shipping_rate_id
- "/api/v3/store/checkout/store_credits":
+ "/api/v3/store/carts/{cart_id}/store_credits":
post:
summary: Apply store credit
tags:
- - Checkout
+ - Carts
security:
- api_key: []
bearer_auth: []
- description: Applies store credit to the current cart during checkout.
+ description: Applies store credit to the cart during checkout.
x-codeSamples:
- lang: javascript
label: Spree SDK
@@ -7293,7 +7328,7 @@ paths:
publishableKey: '<api-key>',
})
- const cart = await client.checkout.applyStoreCredit(10.0, {
+ const cart = await client.carts.storeCredits.apply('cart_abc123', 10.0, {
bearerToken: '<token>',
})
parameters:
@@ -7307,6 +7342,12 @@ paths:
required: true
schema:
type: string
+ - name: cart_id
+ in: path
+ required: true
+ description: Cart prefixed ID (e.g., cart_abc123)
+ schema:
+ type: string
- name: x-spree-token
in: header
required: false
@@ -7325,9 +7366,9 @@ paths:
application/json:
example:
id: cart_UkLWZg9DAJ
- number: R931310416
- token: LmVmBgYQJXmdFQMAitHzVHKYn7Tzwg2PDuQ
+ number: R801224178
+ token: 9or7Ht7uVnx4tpYMY6piZ5HYtgpJHTE6Y6D
special_instructions:
currency: USD
locale: en
@@ -7348,8 +7389,8 @@ paths:
display_additional_tax_total: "$0.00"
total: '110.0'
display_total: "$110.00"
- created_at: '2026-03-12T11:03:40.266Z'
- updated_at: '2026-03-12T11:03:40.312Z'
+ created_at: '2026-03-13T10:54:07.091Z'
+ updated_at: '2026-03-13T10:54:07.150Z'
current_step: address
completed_steps: []
requirements: []
@@ -7359,8 +7400,8 @@ paths:
variant_id: variant_UkLWZg9DAJ
quantity: 1
currency: USD
- name: Product 1079130
- slug: product-1079130
+ name: Product 1029948
+ slug: product-1029948
options_text: ''
price: '10.0'
display_price: "$10.00"
@@ -7379,37 +7420,37 @@ paths:
discounted_amount: '10.0'
display_discounted_amount: "$10.00"
display_compare_at_amount: "$0.00"
- created_at: '2026-03-12T11:03:40.293Z'
- updated_at: '2026-03-12T11:03:40.293Z'
+ created_at: '2026-03-13T10:54:07.124Z'
+ updated_at: '2026-03-13T10:54:07.124Z'
compare_at_amount:
thumbnail_url:
option_values: []
digital_links: []
shipments:
- id: ship_UkLWZg9DAJ
- number: H52211052578
+ number: H76641019615
state: pending
tracking: U10000
tracking_url:
cost: '100.0'
display_cost: "$100.00"
shipped_at:
- created_at: '2026-03-12T11:03:40.297Z'
- updated_at: '2026-03-12T11:03:40.310Z'
+ created_at: '2026-03-13T10:54:07.129Z'
+ updated_at: '2026-03-13T10:54:07.147Z'
shipping_method:
id: shpm_UkLWZg9DAJ
name: UPS Ground
code: UPS_GROUND
stock_location:
id: sloc_UkLWZg9DAJ
- state_abbr: STATE_ABBR_281
- name: Lamont Adams
+ state_abbr: STATE_ABBR_262
+ name: Oma Hane
address1: 1600 Pennsylvania Ave NW
city: Washington
zipcode: '20500'
country_iso: US
country_name: United States of America
- state_text: STATE_ABBR_281
+ state_text: STATE_ABBR_262
shipping_rates:
- id: shpr_UkLWZg9DAJ
shipping_method_id: shpm_UkLWZg9DAJ
@@ -7425,12 +7466,12 @@ paths:
- id: py_UkLWZg9DAJ
payment_method_id: pm_UkLWZg9DAJ
state: checkout
- response_code: 1-SC-20260312110340616671
- number: PM556UT3
+ response_code: 1-SC-20260313105407469474
+ number: PYVG22DW
amount: '10.0'
display_amount: "$10.00"
- created_at: '2026-03-12T11:03:40.620Z'
- updated_at: '2026-03-12T11:03:40.620Z'
+ created_at: '2026-03-13T10:54:07.473Z'
+ updated_at: '2026-03-13T10:54:07.473Z'
source_type: store_credit
source_id: credit_UkLWZg9DAJ
source:
@@ -7453,7 +7494,7 @@ paths:
firstname: John
lastname: Doe
full_name: John Doe
- address1: 262 Lovely Street
+ address1: 244 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -7461,16 +7502,16 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_283
- state_abbr: STATE_ABBR_283
+ state_text: STATE_ABBR_264
+ state_abbr: STATE_ABBR_264
quick_checkout: false
- state_name: STATE_NAME_283
+ state_name: STATE_NAME_264
ship_address:
id: addr_VqXmZF31wY
firstname: John
lastname: Doe
full_name: John Doe
- address1: 263 Lovely Street
+ address1: 245 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -7478,10 +7519,10 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_284
- state_abbr: STATE_ABBR_284
+ state_text: STATE_ABBR_265
+ state_abbr: STATE_ABBR_265
quick_checkout: false
- state_name: STATE_NAME_284
+ state_name: STATE_NAME_265
payment_methods:
- id: pm_UkLWZg9DAJ
name: Store Credit
@@ -7513,11 +7554,11 @@ paths:
delete:
summary: Remove store credit
tags:
- - Checkout
+ - Carts
security:
- api_key: []
bearer_auth: []
- description: Removes store credit from the current cart.
+ description: Removes store credit from the cart.
x-codeSamples:
- lang: javascript
label: Spree SDK
@@ -7529,7 +7570,7 @@ paths:
publishableKey: '<api-key>',
})
- const cart = await client.checkout.removeStoreCredit({
+ const cart = await client.carts.storeCredits.remove('cart_abc123', {
bearerToken: '<token>',
})
parameters:
@@ -7543,6 +7584,12 @@ paths:
required: true
schema:
type: string
+ - name: cart_id
+ in: path
+ required: true
+ description: Cart prefixed ID
+ schema:
+ type: string
- name: x-spree-token
in: header
required: false
@@ -7555,9 +7602,9 @@ paths:
application/json:
example:
id: cart_UkLWZg9DAJ
- number: R118253424
- token: 4aFcY7GRY1HBm7yJ1oACFsyjeXT5i3rS4d2
+ number: R233424337
+ token: R51cNj2Wvug82tXAQMdXipv15yizmJBUW9B
special_instructions:
currency: USD
locale: en
@@ -7578,8 +7625,8 @@ paths:
display_additional_tax_total: "$0.00"
total: '110.0'
display_total: "$110.00"
- created_at: '2026-03-12T11:03:41.801Z'
- updated_at: '2026-03-12T11:03:41.851Z'
+ created_at: '2026-03-13T10:54:08.719Z'
+ updated_at: '2026-03-13T10:54:08.791Z'
current_step: address
completed_steps: []
requirements:
@@ -7592,8 +7639,8 @@ paths:
variant_id: variant_UkLWZg9DAJ
quantity: 1
currency: USD
- name: Product 1091704
- slug: product-1091704
+ name: Product 1043422
+ slug: product-1043422
options_text: ''
price: '10.0'
display_price: "$10.00"
@@ -7612,37 +7659,37 @@ paths:
discounted_amount: '10.0'
display_discounted_amount: "$10.00"
display_compare_at_amount: "$0.00"
- created_at: '2026-03-12T11:03:41.830Z'
- updated_at: '2026-03-12T11:03:41.830Z'
+ created_at: '2026-03-13T10:54:08.764Z'
+ updated_at: '2026-03-13T10:54:08.764Z'
compare_at_amount:
thumbnail_url:
option_values: []
digital_links: []
shipments:
- id: ship_UkLWZg9DAJ
- number: H95577787913
+ number: H52897976695
state: pending
tracking: U10000
tracking_url:
cost: '100.0'
display_cost: "$100.00"
shipped_at:
- created_at: '2026-03-12T11:03:41.836Z'
- updated_at: '2026-03-12T11:03:41.849Z'
+ created_at: '2026-03-13T10:54:08.771Z'
+ updated_at: '2026-03-13T10:54:08.788Z'
shipping_method:
id: shpm_UkLWZg9DAJ
name: UPS Ground
code: UPS_GROUND
stock_location:
id: sloc_UkLWZg9DAJ
- state_abbr: STATE_ABBR_289
- name: Tula Cruickshank
+ state_abbr: STATE_ABBR_270
+ name: Elinore Muller
address1: 1600 Pennsylvania Ave NW
city: Washington
zipcode: '20500'
country_iso: US
country_name: United States of America
- state_text: STATE_ABBR_289
+ state_text: STATE_ABBR_270
shipping_rates:
- id: shpr_UkLWZg9DAJ
shipping_method_id: shpm_UkLWZg9DAJ
@@ -7660,7 +7707,7 @@ paths:
firstname: John
lastname: Doe
full_name: John Doe
- address1: 270 Lovely Street
+ address1: 252 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -7668,16 +7715,16 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_291
- state_abbr: STATE_ABBR_291
+ state_text: STATE_ABBR_272
+ state_abbr: STATE_ABBR_272
quick_checkout: false
- state_name: STATE_NAME_291
+ state_name: STATE_NAME_272
ship_address:
id: addr_VqXmZF31wY
firstname: John
lastname: Doe
full_name: John Doe
- address1: 271 Lovely Street
+ address1: 253 Lovely Street
address2: Northwest
city: Herndon
zipcode: '35005'
@@ -7685,10 +7732,10 @@ paths:
company: Company
country_name: United States of America
country_iso: US
- state_text: STATE_ABBR_292
- state_abbr: STATE_ABBR_292
+ state_text: STATE_ABBR_273
+ state_abbr: STATE_ABBR_273
quick_checkout: false
- state_name: STATE_NAME_292
+ state_name: STATE_NAME_273
payment_methods: []
schema:
"$ref": "#/components/schemas/Cart"
@@ -7752,9 +7799,9 @@ paths:
data:
- id: wl_UkLWZg9DAJ
name: My Wishlist
- token: Dj8pwFAnFgwJRmhKTsmtLyUv
- created_at: '2026-03-12T11:03:42.418Z'
- updated_at: '2026-03-12T11:03:42.418Z'
+ token: dfZRsbA8CQBhPSgciUXH2V4M
+ created_at: '2026-03-13T10:54:09.381Z'
+ updated_at: '2026-03-13T10:54:09.381Z'
is_default: false
is_private: true
meta:
@@ -7830,9 +7877,9 @@ paths:
example:
id: wl_gbHJdmfrXB
name: Birthday Ideas
- token: 46SeewNe18s7mrncyyCMUvj3
- created_at: '2026-03-12T11:03:43.688Z'
- updated_at: '2026-03-12T11:03:43.688Z'
+ token: ZpFcCBmGzxdnK5vgSZCsQWL6
+ created_at: '2026-03-13T10:54:10.574Z'
+ updated_at: '2026-03-13T10:54:10.574Z'
is_default: false
is_private: true
schema:
@@ -7928,9 +7975,9 @@ paths:
example:
id: wl_UkLWZg9DAJ
name: My Wishlist
- token: Dx3enhfSCUfDaGRTNjirim6Y
- created_at: '2026-03-12T11:03:45.001Z'
- updated_at: '2026-03-12T11:03:45.001Z'
+ token: YHyiAmJrueiWnhefKidp1C7h
+ created_at: '2026-03-13T10:54:11.683Z'
+ updated_at: '2026-03-13T10:54:11.683Z'
is_default: false
is_private: true
schema:
@@ -7992,9 +8039,9 @@ paths:
example:
id: wl_UkLWZg9DAJ
name: Updated Name
- token: chzedzK3Gwdv3TZaXJvxFKvj
- created_at: '2026-03-12T11:03:46.163Z'
- updated_at: '2026-03-12T11:03:46.203Z'
+ token: iTCxuYLNQwKBGCiHQaAaQxg7
+ created_at: '2026-03-13T10:54:12.839Z'
+ updated_at: '2026-03-13T10:54:12.878Z'
is_default: false
is_private: true
schema:
@@ -8106,18 +8153,18 @@ paths:
variant_id: variant_gbHJdmfrXB
wishlist_id: wl_UkLWZg9DAJ
quantity: 1
- created_at: '2026-03-12T11:03:47.388Z'
- updated_at: '2026-03-12T11:03:47.388Z'
+ created_at: '2026-03-13T10:54:14.063Z'
+ updated_at: '2026-03-13T10:54:14.063Z'
variant:
id: variant_gbHJdmfrXB
product_id: prod_gbHJdmfrXB
- sku: SKU-130
+ sku: SKU-124
is_master: true
options_text: ''
track_inventory: true
image_count: 0
- created_at: '2026-03-12T11:03:47.357Z'
- updated_at: '2026-03-12T11:03:47.370Z'
+ created_at: '2026-03-13T10:54:14.041Z'
+ updated_at: '2026-03-13T10:54:14.049Z'
thumbnail:
purchasable: true
in_stock: false
diff --git a/docs/developer/core-concepts/addresses.mdx b/docs/developer/core-concepts/addresses.mdx
index ebc22ab8c5..63f89779fa 100644
--- a/docs/developer/core-concepts/addresses.mdx
+++ b/docs/developer/core-concepts/addresses.mdx
@@ -109,13 +109,13 @@ During checkout, you can either reference a saved address by ID or pass a new ad
```typescript SDK
// Use saved addresses
-await client.orders.update(orderId, {
+await client.carts.update(cartId, {
ship_address_id: 'addr_xxx',
bill_address_id: 'addr_yyy',
})
// Or pass new addresses inline
-await client.orders.update(orderId, {
+await client.carts.update(cartId, {
ship_address: {
firstname: 'John',
lastname: 'Doe',
@@ -131,16 +131,16 @@ await client.orders.update(orderId, {
```bash cURL
# Use a saved address
-curl -X PATCH 'https://api.mystore.com/api/v3/store/orders/or_xxx' \
+curl -X PATCH 'https://api.mystore.com/api/v3/store/carts/cart_xxx' \
-H 'Authorization: Bearer spree_pk_xxx' \
- -H 'X-Spree-Order-Token: order_token' \
+ -H 'X-Spree-Token: order_token' \
-H 'Content-Type: application/json' \
-d '{ "ship_address_id": "addr_xxx", "bill_address_id": "addr_yyy" }'
# Or pass a new address inline
-curl -X PATCH 'https://api.mystore.com/api/v3/store/orders/or_xxx' \
+curl -X PATCH 'https://api.mystore.com/api/v3/store/carts/cart_xxx' \
-H 'Authorization: Bearer spree_pk_xxx' \
- -H 'X-Spree-Order-Token: order_token' \
+ -H 'X-Spree-Token: order_token' \
-H 'Content-Type: application/json' \
-d '{
"ship_address": {
diff --git a/docs/developer/core-concepts/adjustments.mdx b/docs/developer/core-concepts/adjustments.mdx
index 1a5348e0ee..bd5f9bb1b1 100644
--- a/docs/developer/core-concepts/adjustments.mdx
+++ b/docs/developer/core-concepts/adjustments.mdx
@@ -76,8 +76,7 @@ Adjustments appear in order responses when you expand line items or shipments:
```typescript SDK
const order = await client.orders.get('or_abc123', {
- expand: ['items', 'shipments'],
- orderToken: '<token>',
+ spreeToken: '<token>',
})
// Line item adjustments (promotions, taxes)
@@ -97,7 +96,7 @@ order.included_tax_total
```bash cURL
curl 'https://api.mystore.com/api/v3/store/orders/or_abc123?expand=items,shipments' \
-H 'Authorization: Bearer spree_pk_xxx' \
- -H 'X-Spree-Order-Token: <token>'
+ -H 'X-Spree-Token: <token>'
```
</CodeGroup>
diff --git a/docs/developer/core-concepts/customers.mdx b/docs/developer/core-concepts/customers.mdx
index bb07ba50e1..6e6c14884b 100644
--- a/docs/developer/core-concepts/customers.mdx
+++ b/docs/developer/core-concepts/customers.mdx
@@ -170,7 +170,7 @@ Authenticated customers have access to these resources:
## Guest Checkout
-Customers don't need to register to purchase. Guest checkout uses an order token (`X-Spree-Order-Token`) to identify the cart. See [Orders — Cart](/developer/core-concepts/orders#cart) for details.
+Customers don't need to register to purchase. Guest checkout uses an order token (`X-Spree-Token`) to identify the cart. See [Orders — Cart](/developer/core-concepts/orders#cart) for details.
## Related Documentation
diff --git a/docs/developer/core-concepts/orders.mdx b/docs/developer/core-concepts/orders.mdx
index bc6987dd04..b2b25c47a3 100644
--- a/docs/developer/core-concepts/orders.mdx
+++ b/docs/developer/core-concepts/orders.mdx
@@ -86,60 +86,60 @@ A cart is simply an order in the `cart` state. Guest carts are identified by a c
```typescript SDK
// Create a cart
-const cart = await client.cart.create()
+const cart = await client.carts.create()
// cart.token => "abc123" (save this for guest checkout)
// Get existing cart
-const cart = await client.cart.get()
+const cart = await client.carts.get(cartId, { spreeToken: 'xxx' })
// Add an item
-const updatedOrder = await client.orders.lineItems.create(cart.id, {
+const updatedOrder = await client.carts.items.create(cart.id, {
variant_id: 'var_xxx',
quantity: 2,
})
// Update quantity
-await client.orders.lineItems.update(cart.id, 'li_xxx', {
+await client.carts.items.update(cart.id, 'li_xxx', {
quantity: 3,
})
// Remove an item
-await client.orders.lineItems.delete(cart.id, 'li_xxx')
+await client.carts.items.delete(cart.id, 'li_xxx')
```
```bash cURL
# Create a cart
-curl -X POST 'https://api.mystore.com/api/v3/store/cart' \
+curl -X POST 'https://api.mystore.com/api/v3/store/carts' \
-H 'Authorization: Bearer spree_pk_xxx'
# Get existing cart
-curl 'https://api.mystore.com/api/v3/store/cart' \
+curl 'https://api.mystore.com/api/v3/store/carts/cart_xxx' \
-H 'Authorization: Bearer spree_pk_xxx' \
- -H 'X-Spree-Order-Token: abc123'
+ -H 'X-Spree-Token: abc123'
# Add an item
-curl -X POST 'https://api.mystore.com/api/v3/store/orders/or_xxx/line_items' \
+curl -X POST 'https://api.mystore.com/api/v3/store/carts/cart_xxx/items' \
-H 'Authorization: Bearer spree_pk_xxx' \
- -H 'X-Spree-Order-Token: abc123' \
+ -H 'X-Spree-Token: abc123' \
-H 'Content-Type: application/json' \
-d '{ "variant_id": "var_xxx", "quantity": 2 }'
# Update quantity
-curl -X PATCH 'https://api.mystore.com/api/v3/store/orders/or_xxx/line_items/li_xxx' \
+curl -X PATCH 'https://api.mystore.com/api/v3/store/carts/cart_xxx/items/li_xxx' \
-H 'Authorization: Bearer spree_pk_xxx' \
- -H 'X-Spree-Order-Token: abc123' \
+ -H 'X-Spree-Token: abc123' \
-H 'Content-Type: application/json' \
-d '{ "quantity": 3 }'
# Remove an item
-curl -X DELETE 'https://api.mystore.com/api/v3/store/orders/or_xxx/line_items/li_xxx' \
+curl -X DELETE 'https://api.mystore.com/api/v3/store/carts/cart_xxx/items/li_xxx' \
-H 'Authorization: Bearer spree_pk_xxx' \
- -H 'X-Spree-Order-Token: abc123'
+ -H 'X-Spree-Token: abc123'
```
</CodeGroup>
-Every line item mutation returns the full updated order with recalculated totals.
+Every item mutation returns the full updated order with recalculated totals.
## Checkout Flow
@@ -166,13 +166,13 @@ The checkout is a state machine that advances the order through a series of step
</Step>
</Steps>
-Advance to the next step with `next`. If the order doesn't meet the requirements for the next state (e.g., missing address), the API returns an error.
+If the order doesn't meet the requirements for the next state (e.g., missing address), the API returns an error.
<CodeGroup>
```typescript SDK
// Set addresses
-await client.orders.update(orderId, {
+await client.carts.update(cartId, {
ship_address: {
firstname: 'John', lastname: 'Doe',
@@ -182,36 +182,30 @@ await client.orders.update(orderId, {
},
})
-// Advance to delivery
-await client.orders.next(orderId)
-
// Get shipments and select a shipping rate
-const { data: shipments } = await client.orders.shipments.list(orderId)
-await client.orders.shipments.update(orderId, shipments[0].id, {
+const { data: shipments } = await client.carts.shipments.list(cartId)
+await client.carts.shipments.update(cartId, shipments[0].id, {
selected_shipping_rate_id: 'sr_xxx',
})
-// Advance to payment
-await client.orders.next(orderId)
-
// Create a payment session (e.g., Stripe)
-const session = await client.orders.paymentSessions.create(orderId, {
+const session = await client.carts.paymentSessions.create(cartId, {
payment_method_id: 'pm_xxx',
})
// session.external_data.client_secret => use with Stripe.js
// Complete the payment session after provider confirmation
-await client.orders.paymentSessions.complete(orderId, session.id)
+await client.carts.paymentSessions.complete(cartId, session.id)
// Complete the order
-await client.orders.complete(orderId)
+await client.carts.complete(cartId)
```
```bash cURL
# Set addresses
-curl -X PATCH 'https://api.mystore.com/api/v3/store/orders/or_xxx' \
+curl -X PATCH 'https://api.mystore.com/api/v3/store/carts/cart_xxx' \
-H 'Authorization: Bearer spree_pk_xxx' \
- -H 'X-Spree-Order-Token: abc123' \
+ -H 'X-Spree-Token: abc123' \
-H 'Content-Type: application/json' \
-d '{
"email": "[email protected]",
@@ -223,22 +217,17 @@ curl -X PATCH 'https://api.mystore.com/api/v3/store/orders/or_xxx' \
}
}'
-# Advance to next step
-curl -X PATCH 'https://api.mystore.com/api/v3/store/orders/or_xxx/next' \
- -H 'Authorization: Bearer spree_pk_xxx' \
- -H 'X-Spree-Order-Token: abc123'
-
# Select a shipping rate
-curl -X PATCH 'https://api.mystore.com/api/v3/store/orders/or_xxx/shipments/shp_xxx' \
+curl -X PATCH 'https://api.mystore.com/api/v3/store/carts/cart_xxx/shipments/shp_xxx' \
-H 'Authorization: Bearer spree_pk_xxx' \
- -H 'X-Spree-Order-Token: abc123' \
+ -H 'X-Spree-Token: abc123' \
-H 'Content-Type: application/json' \
-d '{ "selected_shipping_rate_id": "sr_xxx" }'
# Complete the order
-curl -X PATCH 'https://api.mystore.com/api/v3/store/orders/or_xxx/complete' \
+curl -X POST 'https://api.mystore.com/api/v3/store/carts/cart_xxx/complete' \
-H 'Authorization: Bearer spree_pk_xxx' \
- -H 'X-Spree-Order-Token: abc123'
+ -H 'X-Spree-Token: abc123'
```
</CodeGroup>
@@ -251,24 +240,24 @@ Apply or remove promotional coupon codes during checkout:
```typescript SDK
// Apply a coupon
-await client.orders.couponCodes.apply(orderId, 'SAVE20')
+await client.carts.couponCodes.apply(cartId, 'SAVE20')
// Remove a coupon
-await client.orders.couponCodes.remove(orderId, 'promo_xxx')
+await client.carts.couponCodes.remove(cartId, 'SAVE20')
```
```bash cURL
# Apply a coupon
-curl -X POST 'https://api.mystore.com/api/v3/store/orders/or_xxx/coupon_codes' \
+curl -X POST 'https://api.mystore.com/api/v3/store/carts/cart_xxx/coupon_codes' \
-H 'Authorization: Bearer spree_pk_xxx' \
- -H 'X-Spree-Order-Token: abc123' \
+ -H 'X-Spree-Token: abc123' \
-H 'Content-Type: application/json' \
-d '{ "code": "SAVE20" }'
# Remove a coupon
-curl -X DELETE 'https://api.mystore.com/api/v3/store/orders/or_xxx/coupon_codes/promo_xxx' \
+curl -X DELETE 'https://api.mystore.com/api/v3/store/carts/cart_xxx/coupon_codes/SAVE20' \
-H 'Authorization: Bearer spree_pk_xxx' \
- -H 'X-Spree-Order-Token: abc123'
+ -H 'X-Spree-Token: abc123'
```
</CodeGroup>
diff --git a/docs/developer/core-concepts/payments.mdx b/docs/developer/core-concepts/payments.mdx
index 3317fa872f..daab708fdd 100644
--- a/docs/developer/core-concepts/payments.mdx
+++ b/docs/developer/core-concepts/payments.mdx
@@ -160,10 +160,10 @@ Payment methods where `session_required?` returns `false` don't need a payment s
For these methods, the Store API allows creating a payment directly without going through the payment session flow:
```typescript
-const options = { orderToken: cart.token }
+const options = { spreeToken: cart.token }
// Create a payment for a non-session payment method
-const payment = await client.orders.payments.create(cart.id, {
+const payment = await client.carts.payments.create(cart.id, {
payment_method_id: 'pm_xyz789',
amount: '99.99', // Optional, defaults to order total minus store credits
metadata: { // Optional, write-only metadata (e.g. PO number)
@@ -302,10 +302,10 @@ stateDiagram-v2
**Create a Payment Session:**
```typescript
-const options = { orderToken: cart.token }
+const options = { spreeToken: cart.token }
// Create a payment session for the selected payment method
-const session = await client.orders.paymentSessions.create(cart.id, {
+const session = await client.carts.paymentSessions.create(cart.id, {
payment_method_id: 'pm_xyz789',
amount: '99.99', // Optional, defaults to order total
external_data: {}, // Optional, provider-specific data
@@ -339,7 +339,7 @@ console.log(session.external_data.client_secret) // Use with Stripe.js or Adyen
**Update a Payment Session** (e.g., after order total changes):
```typescript
-const updated = await client.orders.paymentSessions.update(
+const updated = await client.carts.paymentSessions.update(
cart.id, session.id,
{ amount: '149.99' },
options
@@ -349,7 +349,7 @@ const updated = await client.orders.paymentSessions.update(
**Complete a Payment Session** (after customer confirms payment on the frontend):
```typescript
-const completed = await client.orders.paymentSessions.complete(
+const completed = await client.carts.paymentSessions.complete(
cart.id, session.id,
{ session_result: '...', external_data: {} },
options
diff --git a/docs/developer/core-concepts/promotions.mdx b/docs/developer/core-concepts/promotions.mdx
index 9e4afa3990..77cb2cfd7c 100644
--- a/docs/developer/core-concepts/promotions.mdx
+++ b/docs/developer/core-concepts/promotions.mdx
@@ -279,24 +279,24 @@ Customers apply coupon codes during checkout via the Store API:
<CodeGroup>
```typescript SDK
-// Apply a coupon code to the order
-const order = await client.orders.couponCodes.apply('or_abc123', 'SUMMER20', {
- orderToken: '<token>',
+// Apply a coupon code to the cart
+const cart = await client.carts.couponCodes.apply('cart_abc123', 'SUMMER20', {
+ spreeToken: '<token>',
})
-// Remove a promotion from the order
-await client.orders.couponCodes.remove('or_abc123', 'promo_abc123', {
- orderToken: '<token>',
+// Remove a coupon code from the cart
+await client.carts.couponCodes.remove('cart_abc123', 'SUMMER20', {
+ spreeToken: '<token>',
})
```
```bash cURL
# Apply a coupon code
-curl -X POST 'https://api.mystore.com/api/v3/store/orders/or_abc123/coupon_codes' \
+curl -X POST 'https://api.mystore.com/api/v3/store/carts/cart_abc123/coupon_codes' \
-H 'Authorization: Bearer spree_pk_xxx' \
- -H 'X-Spree-Order-Token: <token>' \
+ -H 'X-Spree-Token: <token>' \
-H 'Content-Type: application/json' \
- -d '{ "coupon_code": "SUMMER20" }'
+ -d '{ "code": "SUMMER20" }'
```
</CodeGroup>
diff --git a/docs/developer/core-concepts/shipments.mdx b/docs/developer/core-concepts/shipments.mdx
index 3b6cd62982..d2641cae28 100644
--- a/docs/developer/core-concepts/shipments.mdx
+++ b/docs/developer/core-concepts/shipments.mdx
@@ -95,21 +95,21 @@ order.shipments?.forEach(shipment => {
})
// Select a shipping rate
-await client.orders.shipments.update(orderId, shipment.id, {
+await client.carts.shipments.update(cartId, shipment.id, {
selected_shipping_rate_id: 'sr_xxx',
})
```
```bash cURL
# Get shipments
-curl 'https://api.mystore.com/api/v3/store/orders/or_xxx?expand=shipments' \
+curl 'https://api.mystore.com/api/v3/store/carts/cart_xxx?expand=shipments' \
-H 'Authorization: Bearer spree_pk_xxx' \
- -H 'X-Spree-Order-Token: abc123'
+ -H 'X-Spree-Token: abc123'
# Select a shipping rate
-curl -X PATCH 'https://api.mystore.com/api/v3/store/orders/or_xxx/shipments/shp_xxx' \
+curl -X PATCH 'https://api.mystore.com/api/v3/store/carts/cart_xxx/shipments/shp_xxx' \
-H 'Authorization: Bearer spree_pk_xxx' \
- -H 'X-Spree-Order-Token: abc123' \
+ -H 'X-Spree-Token: abc123' \
-H 'Content-Type: application/json' \
-d '{ "selected_shipping_rate_id": "sr_xxx" }'
```
diff --git a/docs/developer/core-concepts/store-credits-gift-cards.mdx b/docs/developer/core-concepts/store-credits-gift-cards.mdx
index 437f2aa44a..86ae602cf4 100644
--- a/docs/developer/core-concepts/store-credits-gift-cards.mdx
+++ b/docs/developer/core-concepts/store-credits-gift-cards.mdx
@@ -256,18 +256,19 @@ Gift cards are applied using the same coupon codes endpoint as promotion codes.
<CodeGroup>
```typescript SDK
-// Apply gift card code to order (works for guests and registered customers)
-const order = await client.orders.couponCodes.apply('or_abc123', 'abc1234def', {
- orderToken: '<token>',
+// Apply gift card code to cart (works for guests and registered customers)
+const cart = await client.carts.couponCodes.apply('cart_abc123', 'abc1234def', {
+ spreeToken: '<token>',
})
```
```bash cURL
-# Apply gift card to order (works for guests and registered customers)
-curl -X POST 'https://api.mystore.com/api/v3/store/orders/or_abc123/coupon_codes' \
+# Apply gift card to cart (works for guests and registered customers)
+curl -X POST 'https://api.mystore.com/api/v3/store/carts/cart_abc123/coupon_codes' \
-H 'Authorization: Bearer spree_pk_xxx' \
+ -H 'X-Spree-Token: <token>' \
-H 'Content-Type: application/json' \
- -d '{ "coupon_code": "abc1234def" }'
+ -d '{ "code": "abc1234def" }'
```
</CodeGroup>
diff --git a/docs/developer/core-concepts/users.mdx b/docs/developer/core-concepts/users.mdx
index efd3c7227a..b5b716c1f0 100644
--- a/docs/developer/core-concepts/users.mdx
+++ b/docs/developer/core-concepts/users.mdx
@@ -186,7 +186,7 @@ Authenticated customers have access to these resources:
### Guest Checkout
-Customers don't need to register to purchase. Guest checkout uses an order token (`X-Spree-Order-Token`) to identify the cart. See [Orders — Cart](/developer/core-concepts/orders#cart) for details.
+Customers don't need to register to purchase. Guest checkout uses an order token (`X-Spree-Token`) to identify the cart. See [Orders — Cart](/developer/core-concepts/orders#cart) for details.
## Admin Users
diff --git a/docs/developer/customization/metadata.mdx b/docs/developer/customization/metadata.mdx
index 93c9b0d843..b36b56a68c 100644
--- a/docs/developer/customization/metadata.mdx
+++ b/docs/developer/customization/metadata.mdx
@@ -19,7 +19,7 @@ For structured, type-safe custom attributes with admin UI support, use [Metafiel
Set metadata when creating a new cart:
```bash
-POST /api/v3/store/cart
+POST /api/v3/store/carts
Content-Type: application/json
{
@@ -32,7 +32,7 @@ Content-Type: application/json
```typescript
// @spree/sdk
-const cart = await client.cart.create({
+const cart = await client.carts.create({
metadata: { source: 'mobile_app', campaign: 'summer_sale' }
})
@@ -40,12 +40,12 @@ const cart = await client.cart.create({
const cart = await getOrCreateCart({ source: 'mobile_app' })
```
-### Adding line items
+### Adding items
Set metadata when adding items to the cart:
```bash
-POST /api/v3/store/orders/:order_id/line_items
+POST /api/v3/store/carts/:cart_id/items
Content-Type: application/json
{
@@ -59,19 +59,19 @@ Content-Type: application/json
```
```typescript
-const order = await client.orders.lineItems.create(orderId, {
+const order = await client.carts.items.create(cartId, {
variant_id: 'variant_k5nR8xLq',
quantity: 1,
metadata: { gift_note: 'Happy Birthday!' },
})
```
-### Updating line items
+### Updating items
Metadata is **merged** with existing values on update. Set a key to `null` to remove it.
```bash
-PATCH /api/v3/store/orders/:order_id/line_items/:id
+PATCH /api/v3/store/carts/:cart_id/items/:id
Content-Type: application/json
{
@@ -86,21 +86,21 @@ You can update metadata without changing quantity, or update both at once:
```typescript
// Metadata only
-await client.orders.lineItems.update(orderId, lineItemId, {
+await client.carts.items.update(cartId, lineItemId, {
metadata: { engraving: 'A.B.' },
})
// Both quantity and metadata
-await client.orders.lineItems.update(orderId, lineItemId, {
+await client.carts.items.update(cartId, lineItemId, {
quantity: 3,
metadata: { gift_note: 'Happy Birthday!' },
})
```
-### Updating orders
+### Updating carts
```bash
-PATCH /api/v3/store/orders/:id
+PATCH /api/v3/store/carts/:id
Content-Type: application/json
{
@@ -112,9 +112,9 @@ Content-Type: application/json
```
```typescript
-await client.orders.update(orderId, {
+await client.carts.update(cartId, {
metadata: { utm_source: 'google' },
-}, { orderToken })
+}, { spreeToken })
```
## Admin API
@@ -219,9 +219,8 @@ All models that include the `Spree::Metadata` concern support metadata. This inc
The Store API currently supports writing metadata on:
-- **Cart** — on creation (`POST /api/v3/store/cart`)
-- **Line Items** — on create and update (`POST/PATCH /api/v3/store/orders/:id/line_items`)
-- **Orders** — on update (`PATCH /api/v3/store/orders/:id`)
+- **Carts** — on creation and update (`POST /api/v3/store/carts`, `PATCH /api/v3/store/carts/:id`)
+- **Items** — on create and update (`POST/PATCH /api/v3/store/carts/:id/items`)
## Migration from public_metadata
diff --git a/docs/developer/how-to/custom-payment-method.mdx b/docs/developer/how-to/custom-payment-method.mdx
index 01bb209416..bb44ca7ffb 100644
--- a/docs/developer/how-to/custom-payment-method.mdx
+++ b/docs/developer/how-to/custom-payment-method.mdx
@@ -168,13 +168,13 @@ The frontend creates a session, then uses the provider's SDK to collect payment:
```typescript
// 1. Get available payment methods
-const methods = await client.orders.paymentMethods.list(cart.id, options)
+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
-const session = await client.orders.paymentSessions.create(cart.id, {
+const session = await client.carts.paymentSessions.create(cart.id, {
payment_method_id: myGateway.id,
}, options)
@@ -182,7 +182,7 @@ const session = await client.orders.paymentSessions.create(cart.id, {
const result = await MyProviderSDK.confirmPayment(session.external_data.client_secret)
// 5. Complete the session
-const completed = await client.orders.paymentSessions.complete(
+const completed = await client.carts.paymentSessions.complete(
cart.id, session.id,
{ session_result: result.id },
options
diff --git a/docs/developer/sdk/authentication.mdx b/docs/developer/sdk/authentication.mdx
index e3a96cd789..a8939bac89 100644
--- a/docs/developer/sdk/authentication.mdx
+++ b/docs/developer/sdk/authentication.mdx
@@ -52,11 +52,11 @@ For guest checkout, use the `token` returned when creating a cart. The SDK autom
```typescript
const options = { spreeToken: cart.token }
-// Update checkout with email
-await client.checkout.update({
+// Update cart with email
+await client.carts.update(cart.id, {
}, options)
// Complete checkout
-await client.checkout.complete(options)
+await client.carts.complete(cart.id, options)
```
diff --git a/docs/developer/sdk/quickstart.mdx b/docs/developer/sdk/quickstart.mdx
index 0008adb074..cd34aaeb50 100644
--- a/docs/developer/sdk/quickstart.mdx
+++ b/docs/developer/sdk/quickstart.mdx
@@ -40,15 +40,14 @@ const { token, user } = await client.auth.login({
});
// Create a cart and add items
-const cart = await client.cart.create();
-await client.orders.lineItems.create(cart.id, {
+const cart = await client.carts.create();
+await client.carts.items.create(cart.id, {
variant_id: 'var_abc123',
quantity: 2,
-}, { orderToken: cart.token });
+}, { spreeToken: cart.token });
// Checkout flow
-await client.orders.next(cart.id, { orderToken: cart.token });
-await client.orders.complete(cart.id, { orderToken: cart.token });
+await client.carts.complete(cart.id, { spreeToken: cart.token });
```
## Nested Resources
@@ -57,12 +56,13 @@ The SDK uses a resource builder pattern for nested resources:
| Parent Resource | Nested Resource | Available Methods |
|-----------------|-----------------|-------------------|
-| `orders` | `lineItems` | `create`, `update`, `delete` |
-| `orders` | `payments` | `list`, `get`, `create` |
-| `orders` | `paymentMethods` | `list` |
-| `orders` | `paymentSessions` | `create`, `get`, `update`, `complete` |
-| `orders` | `shipments` | `list`, `update` |
-| `orders` | `couponCodes` | `apply`, `remove` |
+| `carts` | `items` | `create`, `update`, `delete` |
+| `carts` | `payments` | `list`, `get`, `create` |
+| `carts` | `paymentMethods` | `list` |
+| `carts` | `paymentSessions` | `create`, `get`, `update`, `complete` |
+| `carts` | `shipments` | `list`, `update` |
+| `carts` | `couponCodes` | `apply`, `remove` |
+| `carts` | `storeCredits` | `apply`, `remove` |
| `customer` | `addresses` | `list`, `get`, `create`, `update`, `delete`, `markAsDefault` |
| `customer` | `creditCards` | `list`, `get`, `delete` |
| `customer` | `giftCards` | `list`, `get` |
@@ -73,9 +73,9 @@ The SDK uses a resource builder pattern for nested resources:
```typescript
// Nested resources follow the pattern: client.parent.nested.method(parentId, ...)
-await client.orders.lineItems.create(orderId, params, options);
-await client.orders.payments.list(orderId, options);
-await client.orders.shipments.update(orderId, shipmentId, params, options);
+await client.carts.items.create(cartId, params, options);
+await client.carts.payments.list(cartId, options);
+await client.carts.shipments.update(cartId, shipmentId, params, options);
await client.customer.addresses.list({}, options);
await client.categories.products.list(categoryId, params, options);
await client.wishlists.items.create(wishlistId, params, options);
diff --git a/docs/developer/sdk/store/cart-checkout.mdx b/docs/developer/sdk/store/cart-checkout.mdx
index 3eb4c3fbac..a98f4b5583 100644
--- a/docs/developer/sdk/store/cart-checkout.mdx
+++ b/docs/developer/sdk/store/cart-checkout.mdx
@@ -3,51 +3,56 @@ title: Cart, Checkout & Orders
description: Manage carts, line items, coupons, checkout flow, and completed orders with the Spree SDK
---
-The Store API is split into three resource groups:
+The Store API is split into two resource groups:
-- **Cart** — managing the shopping cart (items, coupon codes)
-- **Checkout** — advancing through checkout (addresses, shipping, payments, completion)
+- **Carts** — managing shopping carts, items, coupon codes, checkout flow (addresses, shipping, payments, completion)
- **Orders** — retrieving completed orders
-All cart and checkout endpoints use an **implicit cart** resolved from the `spreeToken` header (guest) or JWT (authenticated customer). You never pass an `orderId`.
+All cart and checkout endpoints require a `cartId` as the first argument.
-## Cart
+## Carts
### Create & Retrieve
```typescript
// Create a new cart
-const cart = await client.cart.create();
+const cart = await client.carts.create();
-// Get current cart
-const cart = await client.cart.get({ spreeToken: 'xxx' });
+// Get a specific cart
+const cart = await client.carts.get(cartId, { spreeToken: 'xxx' });
+
+// List carts
+const carts = await client.carts.list();
+
+// Delete a cart
+await client.carts.delete(cartId, { spreeToken: cart.token });
// Associate guest cart with authenticated user
// (after user logs in, merge their guest cart with their account)
-await client.cart.associate({
+await client.carts.associate(cartId, {
token: jwtToken, // User's JWT token
spreeToken: cart.token, // Guest cart token
});
```
-### Line Items
+### Items
```typescript
const options = { spreeToken: cart.token };
// Add item
-await client.cart.items.create({
+await client.carts.items.create(cartId, {
variant_id: 'var_123',
quantity: 2,
}, options);
// Update item quantity
-await client.cart.items.update(lineItemId, {
+await client.carts.items.update(cartId, lineItemId, {
quantity: 3,
}, options);
// Remove item
-await client.cart.items.delete(lineItemId, options);
+await client.carts.items.delete(cartId, lineItemId, options);
```
### Coupon Codes
@@ -56,18 +61,18 @@ await client.cart.items.delete(lineItemId, options);
const options = { spreeToken: cart.token };
// Apply a coupon code
-await client.cart.couponCodes.apply('SAVE20', options);
+await client.carts.couponCodes.apply(cartId, 'SAVE20', options);
// Remove a coupon code
-await client.cart.couponCodes.remove('promo_xxx', options);
+await client.carts.couponCodes.remove(cartId, 'SUMMER20', options);
```
## Checkout
-### Update Checkout
+### Update Cart
```typescript
-await client.checkout.update({
+await client.carts.update(cartId, {
ship_address: {
firstname: 'John',
@@ -86,7 +91,7 @@ await client.checkout.update({
### Complete Checkout
```typescript
-await client.checkout.complete({ spreeToken: cart.token });
+await client.carts.complete(cartId, { spreeToken: cart.token });
```
### Shipments
@@ -95,10 +100,10 @@ await client.checkout.complete({ spreeToken: cart.token });
const options = { spreeToken: cart.token };
// List shipments
-const shipments = await client.checkout.shipments.list(options);
+const shipments = await client.carts.shipments.list(cartId, options);
// Select a shipping rate
-await client.checkout.shipments.update(shipmentId, {
+await client.carts.shipments.update(cartId, shipmentId, {
selected_shipping_rate_id: 'rate_xxx',
}, options);
```
@@ -109,13 +114,13 @@ await client.checkout.shipments.update(shipmentId, {
const options = { spreeToken: cart.token };
// Apply store credit (applies maximum available by default)
-await client.checkout.storeCredits.apply(undefined, options);
+await client.carts.storeCredits.apply(cartId, undefined, options);
// Apply specific amount of store credit
-await client.checkout.storeCredits.apply(25.00, options);
+await client.carts.storeCredits.apply(cartId, 25.00, options);
// Remove store credit from order
-await client.checkout.storeCredits.remove(options);
+await client.carts.storeCredits.remove(cartId, options);
```
## Orders
diff --git a/docs/developer/sdk/store/payments.mdx b/docs/developer/sdk/store/payments.mdx
index a1a0267273..5d84cebf2b 100644
--- a/docs/developer/sdk/store/payments.mdx
+++ b/docs/developer/sdk/store/payments.mdx
@@ -3,15 +3,15 @@ title: Payments & Shipping
description: Handle payments, payment sessions, and shipping with the Spree SDK
---
-All payment and shipping endpoints use the **implicit cart** resolved from the `spreeToken` header or JWT. You never pass an `orderId`.
+All payment and shipping endpoints require a `cartId` as the first argument.
## Payment Methods
```typescript
const options = { spreeToken: cart.token };
-// Get available payment methods for the current checkout
-const methods = await client.checkout.paymentMethods.list(options);
+// Get available payment methods for the current cart
+const methods = await client.carts.paymentMethods.list(cartId, options);
// Each method includes a `session_required` flag:
// - true → use Payment Sessions (Stripe, Adyen, PayPal, etc.)
@@ -23,15 +23,15 @@ const methods = await client.checkout.paymentMethods.list(options);
```typescript
const options = { spreeToken: cart.token };
-// List payments on the current checkout
-const payments = await client.checkout.payments.list(options);
+// List payments on the current cart
+const payments = await client.carts.payments.list(cartId, options);
// Get a specific payment
-const payment = await client.checkout.payments.get(paymentId, options);
+const payment = await client.carts.payments.get(cartId, paymentId, options);
// Create a payment for a non-session payment method
// (e.g. Check, Cash on Delivery, Bank Transfer, Purchase Order)
-const payment = await client.checkout.payments.create({
+const payment = await client.carts.payments.create(cartId, {
payment_method_id: 'pm_xxx',
amount: '99.99', // Optional, defaults to order total minus store credits
metadata: { // Optional, write-only metadata
@@ -53,7 +53,7 @@ Payment sessions provide a unified, provider-agnostic interface for payment proc
const options = { spreeToken: cart.token };
// Create a payment session (initializes a session with the payment gateway)
-const session = await client.checkout.paymentSessions.create({
+const session = await client.carts.paymentSessions.create(cartId, {
payment_method_id: 'pm_xxx',
amount: '99.99', // Optional, defaults to order total
external_data: { // Optional, provider-specific data
@@ -65,18 +65,18 @@ const session = await client.checkout.paymentSessions.create({
console.log(session.external_data.client_secret);
// Get a payment session
-const existing = await client.checkout.paymentSessions.get(
- session.id, options
+const existing = await client.carts.paymentSessions.get(
+ cartId, session.id, options
);
// Update a payment session (e.g., after order total changes)
-await client.checkout.paymentSessions.update(session.id, {
+await client.carts.paymentSessions.update(cartId, session.id, {
amount: '149.99',
}, options);
// Complete the payment session (after customer confirms payment on the frontend)
-const completed = await client.checkout.paymentSessions.complete(
- session.id,
+const completed = await client.carts.paymentSessions.complete(
+ cartId, session.id,
{ session_result: 'success' },
options
);
@@ -88,11 +88,11 @@ console.log(completed.status); // 'completed'
```typescript
const options = { spreeToken: cart.token };
-// List shipments for the current checkout
-const shipments = await client.checkout.shipments.list(options);
+// List shipments for the current cart
+const shipments = await client.carts.shipments.list(cartId, options);
// Select a shipping rate
-await client.checkout.shipments.update(shipmentId, {
+await client.carts.shipments.update(cartId, shipmentId, {
selected_shipping_rate_id: 'rate_xxx',
}, options);
```
diff --git a/docs/snippets/store-api/auth-guest-cart.mdx b/docs/snippets/store-api/auth-guest-cart.mdx
index ba14ee7b5b..79377380e7 100644
--- a/docs/snippets/store-api/auth-guest-cart.mdx
+++ b/docs/snippets/store-api/auth-guest-cart.mdx
@@ -1,12 +1,12 @@
```typescript
// Create a cart (guest)
-const cart = await client.cart.create()
+const cart = await client.carts.create()
// Use spreeToken for all cart and checkout operations
const options = { spreeToken: cart.token }
// Add items
-await client.cart.items.create({
+await client.carts.items.create(cart.id, {
variant_id: 'variant_abc123',
quantity: 1,
}, options)
diff --git a/packages/next/CHANGELOG.md b/packages/next/CHANGELOG.md
index 8530c91c57..ef97d090f6 100644
--- a/packages/next/CHANGELOG.md
+++ b/packages/next/CHANGELOG.md
@@ -1,5 +1,30 @@
# @spree/next
+## 0.10.0
+
+### Minor Changes
+
+- Unified cart and checkout server actions under single `cart.ts` module
+
+ **Breaking changes:**
+
+ - `getCheckout()` removed — use `getCart()` instead
+ - `updateCheckout(params)` renamed to `updateCart(params)`
+ - `checkout.ts` action file deleted — all exports now come from `cart.ts`
+ - `UpdateCheckoutParams` type removed — use `UpdateCartParams` instead
+
+ **Other changes:**
+
+ - All cart and checkout server actions now use explicit cart IDs via the `carts` namespace
+ - Added cart ID cookie storage (`getCartId`, `setCartId`, `clearCartId`)
+ - Cart ID is now persisted alongside the cart token for REST endpoint routing
+ - Deduplicated `requireCartId` helper (was copied in 3 files)
+
+### Patch Changes
+
+- Updated dependencies:
+
## 0.9.0
### Minor Changes
diff --git a/packages/next/README.md b/packages/next/README.md
index 2e31cae5ea..9a95e249fe 100644
--- a/packages/next/README.md
+++ b/packages/next/README.md
@@ -307,7 +307,7 @@ import type {
StoreLineItem,
StorePaymentSession,
StoreCategory,
- UpdateCheckoutParams,
+ UpdateCartParams,
PaginatedResponse,
SpreeError,
} from '@spree/next';
diff --git a/packages/next/package.json b/packages/next/package.json
index c6ae74f469..aee092773d 100644
--- a/packages/next/package.json
+++ b/packages/next/package.json
@@ -1,6 +1,6 @@
{
"name": "@spree/next",
- "version": "0.9.0",
+ "version": "0.10.0",
"description": "Next.js integration for Spree Commerce — server actions, caching, and cookie-based auth",
"type": "module",
"main": "./dist/index.js",
@@ -62,7 +62,7 @@
"url": "https://github.com/spree/spree/issues"
},
"peerDependencies": {
- "@spree/sdk": ">=0.9.0",
+ "@spree/sdk": ">=0.10.0",
"next": ">=15.0.0",
"react": ">=19.0.0"
},
diff --git a/packages/next/src/actions/auth.ts b/packages/next/src/actions/auth.ts
index a6506e12b0..2c2b7c3649 100644
--- a/packages/next/src/actions/auth.ts
+++ b/packages/next/src/actions/auth.ts
@@ -3,7 +3,7 @@
import { revalidateTag } from 'next/cache';
import type { Customer } from '@spree/sdk';
import { getClient } from '../config';
-import { setAccessToken, clearAccessToken, getAccessToken, getCartToken } from '../cookies';
+import { setAccessToken, clearAccessToken, getAccessToken, getCartToken, getCartId } from '../cookies';
import { withAuthRefresh } from '../auth-helpers';
/**
@@ -20,9 +20,10 @@ export async function login(
// Associate guest cart if one exists
const cartToken = await getCartToken();
- if (cartToken) {
+ const cartId = await getCartId();
+ if (cartToken && cartId) {
try {
- await getClient().cart.associate({
+ await getClient().carts.associate(cartId, {
token: result.token,
spreeToken: cartToken,
});
@@ -64,9 +65,10 @@ export async function register(
// Associate guest cart
const cartToken = await getCartToken();
- if (cartToken) {
+ const cartId = await getCartId();
+ if (cartToken && cartId) {
try {
- await getClient().cart.associate({
+ await getClient().carts.associate(cartId, {
token: result.token,
spreeToken: cartToken,
});
diff --git a/packages/next/src/actions/cart.ts b/packages/next/src/actions/cart.ts
index 92c8c4916c..f53375481a 100644
--- a/packages/next/src/actions/cart.ts
+++ b/packages/next/src/actions/cart.ts
@@ -1,9 +1,14 @@
'use server';
import { revalidateTag } from 'next/cache';
-import type { Cart, CreateCartParams } from '@spree/sdk';
+import type { Cart, Order, Shipment, CreateCartParams, UpdateCartParams, ListResponse } from '@spree/sdk';
import { getClient } from '../config';
-import { getCartToken, setCartToken, clearCartToken, getAccessToken } from '../cookies';
+import {
+ getCartToken, setCartToken, clearCartToken,
+ getCartId, setCartId, clearCartId,
+ getAccessToken,
+ getCartOptions, requireCartId,
+} from '../cookies';
/**
* Get the current cart. Returns null if no cart exists.
@@ -11,22 +16,38 @@ import { getCartToken, setCartToken, clearCartToken, getAccessToken } from '../c
export async function getCart(): Promise<Cart | null> {
const spreeToken = await getCartToken();
const token = await getAccessToken();
- if (!spreeToken && !token) return null;
+ const cartId = await getCartId();
+
+ if (!cartId && !token) return null;
try {
- return await getClient().cart.get({ spreeToken, token });
- } catch {
- // Cart not found (e.g., order was completed) — clear stale token
- if (spreeToken) {
- await clearCartToken();
+ if (cartId) {
+ return await getClient().carts.get(cartId, { spreeToken, token });
+ }
+
+ // Authenticated user without stored cart ID — find their most recent cart
+ if (token) {
+ const response = await getClient().carts.list({ token });
+ if (response.data.length > 0) {
+ const cart = response.data[0];
+ await setCartId(cart.id);
+ if (cart.token) await setCartToken(cart.token);
+ return cart;
+ }
}
+
+ return null;
+ } catch {
+ // Cart not found (e.g., order was completed) — clear stale cookies
+ await clearCartToken();
+ await clearCartId();
return null;
}
}
/**
* Get existing cart or create a new one.
- * @param params - Optional cart creation params (metadata, line_items)
+ * @param params - Optional cart creation params (metadata, items)
*/
export async function getOrCreateCart(
params?: CreateCartParams
@@ -36,11 +57,12 @@ export async function getOrCreateCart(
const token = await getAccessToken();
const cartParams = params && Object.keys(params).length > 0 ? params : undefined;
- const cart = await getClient().cart.create(cartParams, token ? { token } : undefined);
+ const cart = await getClient().carts.create(cartParams, token ? { token } : undefined);
if (cart.token) {
await setCartToken(cart.token);
}
+ await setCartId(cart.id);
revalidateTag('cart');
return cart;
@@ -55,45 +77,36 @@ export async function addItem(
quantity: number = 1,
metadata?: Record<string, unknown>
): Promise<Cart> {
- await getOrCreateCart();
+ const cart = await getOrCreateCart();
const spreeToken = await getCartToken();
const token = await getAccessToken();
- const cart = await getClient().cart.items.create(
+ const updatedCart = await getClient().carts.items.create(
+ cart.id,
{ variant_id: variantId, quantity, metadata },
{ spreeToken, token }
);
revalidateTag('cart');
- return cart;
+ return updatedCart;
}
/**
* Update a line item in the cart (quantity and/or metadata).
* Returns the updated cart with recalculated totals.
- *
- * @example
- * // Update quantity only
- * await updateItem(lineItemId, { quantity: 3 })
- *
- * // Update metadata only
- * await updateItem(lineItemId, { metadata: { gift_message: 'Happy Birthday!' } })
- *
- * // Update both
- * await updateItem(lineItemId, { quantity: 2, metadata: { engraving: 'J.D.' } })
*/
export async function updateItem(
lineItemId: string,
params: { quantity?: number; metadata?: Record<string, unknown> }
): Promise<Cart> {
- const spreeToken = await getCartToken();
- const token = await getAccessToken();
- if (!spreeToken && !token) throw new Error('No cart found');
+ const options = await getCartOptions();
+ const cartId = await requireCartId();
- const cart = await getClient().cart.items.update(
+ const cart = await getClient().carts.items.update(
+ cartId,
lineItemId,
params,
- { spreeToken, token }
+ options
);
revalidateTag('cart');
@@ -105,14 +118,10 @@ export async function updateItem(
* Returns the updated cart with recalculated totals.
*/
export async function removeItem(lineItemId: string): Promise<Cart> {
- const spreeToken = await getCartToken();
- const token = await getAccessToken();
- if (!spreeToken && !token) throw new Error('No cart found');
+ const options = await getCartOptions();
+ const cartId = await requireCartId();
- const cart = await getClient().cart.items.delete(lineItemId, {
- spreeToken,
- token,
- });
+ const cart = await getClient().carts.items.delete(cartId, lineItemId, options);
revalidateTag('cart');
return cart;
@@ -123,6 +132,7 @@ export async function removeItem(lineItemId: string): Promise<Cart> {
*/
export async function clearCart(): Promise<void> {
await clearCartToken();
+ await clearCartId();
revalidateTag('cart');
}
@@ -133,16 +143,100 @@ export async function clearCart(): Promise<void> {
export async function associateCart(): Promise<Cart | null> {
const spreeToken = await getCartToken();
const token = await getAccessToken();
- if (!spreeToken || !token) return null;
+ const cartId = await getCartId();
+ if (!cartId || !token) return null;
try {
- const result = await getClient().cart.associate({ spreeToken, token });
+ const result = await getClient().carts.associate(cartId, { spreeToken, token });
revalidateTag('cart');
return result;
} catch {
// Cart might already belong to another user — clear it
await clearCartToken();
+ await clearCartId();
revalidateTag('cart');
return null;
}
}
+
+/**
+ * Update cart info (email, addresses, special instructions).
+ */
+export async function updateCart(
+ params: UpdateCartParams
+): Promise<Cart> {
+ const options = await getCartOptions();
+ const cartId = await requireCartId();
+ const result = await getClient().carts.update(cartId, params, options);
+ revalidateTag('checkout');
+ return result;
+}
+
+/**
+ * Get shipments with shipping rates for the current cart.
+ */
+export async function getShipments(): Promise<ListResponse<Shipment>> {
+ const options = await getCartOptions();
+ const cartId = await requireCartId();
+ return getClient().carts.shipments.list(cartId, options);
+}
+
+/**
+ * Select a shipping rate for a shipment.
+ * Returns the updated cart with recalculated totals.
+ */
+export async function selectShippingRate(
+ shipmentId: string,
+ shippingRateId: string
+): Promise<Cart> {
+ const options = await getCartOptions();
+ const cartId = await requireCartId();
+ const result = await getClient().carts.shipments.update(
+ cartId,
+ shipmentId,
+ { selected_shipping_rate_id: shippingRateId },
+ options
+ );
+ revalidateTag('checkout');
+ return result;
+}
+
+/**
+ * Apply a coupon code to the cart.
+ */
+export async function applyCoupon(
+ code: string
+): Promise<Cart> {
+ const options = await getCartOptions();
+ const cartId = await requireCartId();
+ const result = await getClient().carts.couponCodes.apply(cartId, code, options);
+ revalidateTag('checkout');
+ revalidateTag('cart');
+ return result;
+}
+
+/**
+ * Remove a coupon code from the cart.
+ */
+export async function removeCoupon(
+ code: string
+): Promise<Cart> {
+ const options = await getCartOptions();
+ const cartId = await requireCartId();
+ const result = await getClient().carts.couponCodes.remove(cartId, code, options);
+ revalidateTag('checkout');
+ revalidateTag('cart');
+ return result;
+}
+
+/**
+ * Complete the checkout and place the order.
+ */
+export async function complete(): Promise<Order> {
+ const options = await getCartOptions();
+ const cartId = await requireCartId();
+ const result = await getClient().carts.complete(cartId, options);
+ revalidateTag('checkout');
+ revalidateTag('cart');
+ return result;
+}
diff --git a/packages/next/src/actions/checkout.ts b/packages/next/src/actions/checkout.ts
deleted file mode 100644
index 1acd44253e..0000000000
--- a/packages/next/src/actions/checkout.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-'use server';
-
-import { revalidateTag } from 'next/cache';
-import type { Cart, Order, Shipment, UpdateCheckoutParams, ListResponse } from '@spree/sdk';
-import { getClient } from '../config';
-import { getCheckoutOptions } from '../cookies';
-
-/**
- * Get the current checkout state (cart with expanded associations).
- */
-export async function getCheckout(): Promise<Cart> {
- const options = await getCheckoutOptions();
- return getClient().cart.get(options);
-}
-
-/**
- * Update checkout info (email, addresses, special instructions).
- */
-export async function updateCheckout(
- params: UpdateCheckoutParams
-): Promise<Cart> {
- const options = await getCheckoutOptions();
- const result = await getClient().checkout.update(params, options);
- revalidateTag('checkout');
- return result;
-}
-
-/**
- * Get shipments with shipping rates for the current cart.
- */
-export async function getShipments(): Promise<ListResponse<Shipment>> {
- const options = await getCheckoutOptions();
- return getClient().checkout.shipments.list(options);
-}
-
-/**
- * Select a shipping rate for a shipment.
- * Returns the updated cart with recalculated totals.
- */
-export async function selectShippingRate(
- shipmentId: string,
- shippingRateId: string
-): Promise<Cart> {
- const options = await getCheckoutOptions();
- const result = await getClient().checkout.shipments.update(
- shipmentId,
- { selected_shipping_rate_id: shippingRateId },
- options
- );
- revalidateTag('checkout');
- return result;
-}
-
-/**
- * Apply a coupon code to the cart.
- */
-export async function applyCoupon(
- code: string
-): Promise<Cart> {
- const options = await getCheckoutOptions();
- const result = await getClient().cart.couponCodes.apply(code, options);
- revalidateTag('checkout');
- revalidateTag('cart');
- return result;
-}
-
-/**
- * Remove a coupon code from the cart.
- */
-export async function removeCoupon(
- code: string
-): Promise<Cart> {
- const options = await getCheckoutOptions();
- const result = await getClient().cart.couponCodes.remove(code, options);
- revalidateTag('checkout');
- revalidateTag('cart');
- return result;
-}
-
-/**
- * Complete the checkout and place the order.
- */
-export async function complete(): Promise<Order> {
- const options = await getCheckoutOptions();
- const result = await getClient().checkout.complete(options);
- revalidateTag('checkout');
- revalidateTag('cart');
- return result;
-}
diff --git a/packages/next/src/actions/payment-sessions.ts b/packages/next/src/actions/payment-sessions.ts
index 222362cd74..1a7ea931bf 100644
--- a/packages/next/src/actions/payment-sessions.ts
+++ b/packages/next/src/actions/payment-sessions.ts
@@ -8,7 +8,7 @@ import type {
CompletePaymentSessionParams,
} from '@spree/sdk';
import { getClient } from '../config';
-import { getCheckoutOptions } from '../cookies';
+import { getCartOptions, requireCartId } from '../cookies';
/**
* Create a payment session for the current cart.
@@ -17,8 +17,9 @@ import { getCheckoutOptions } from '../cookies';
export async function createPaymentSession(
params: CreatePaymentSessionParams
): Promise<PaymentSession> {
- const options = await getCheckoutOptions();
- const result = await getClient().checkout.paymentSessions.create(params, options);
+ const options = await getCartOptions();
+ const cartId = await requireCartId();
+ const result = await getClient().carts.paymentSessions.create(cartId, params, options);
revalidateTag('checkout');
return result;
}
@@ -29,8 +30,9 @@ export async function createPaymentSession(
export async function getPaymentSession(
sessionId: string
): Promise<PaymentSession> {
- const options = await getCheckoutOptions();
- return getClient().checkout.paymentSessions.get(sessionId, options);
+ const options = await getCartOptions();
+ const cartId = await requireCartId();
+ return getClient().carts.paymentSessions.get(cartId, sessionId, options);
}
/**
@@ -41,8 +43,9 @@ export async function updatePaymentSession(
sessionId: string,
params: UpdatePaymentSessionParams
): Promise<PaymentSession> {
- const options = await getCheckoutOptions();
- const result = await getClient().checkout.paymentSessions.update(sessionId, params, options);
+ const options = await getCartOptions();
+ const cartId = await requireCartId();
+ const result = await getClient().carts.paymentSessions.update(cartId, sessionId, params, options);
revalidateTag('checkout');
return result;
}
@@ -55,8 +58,9 @@ export async function completePaymentSession(
sessionId: string,
params?: CompletePaymentSessionParams
): Promise<PaymentSession> {
- const options = await getCheckoutOptions();
- const result = await getClient().checkout.paymentSessions.complete(sessionId, params, options);
+ const options = await getCartOptions();
+ const cartId = await requireCartId();
+ const result = await getClient().carts.paymentSessions.complete(cartId, sessionId, params, options);
revalidateTag('checkout');
return result;
}
diff --git a/packages/next/src/actions/payments.ts b/packages/next/src/actions/payments.ts
index 484fbff65f..beb12e5f4f 100644
--- a/packages/next/src/actions/payments.ts
+++ b/packages/next/src/actions/payments.ts
@@ -3,7 +3,7 @@
import { revalidateTag } from 'next/cache';
import type { Payment, CreatePaymentParams } from '@spree/sdk';
import { getClient } from '../config';
-import { getCheckoutOptions } from '../cookies';
+import { getCartOptions, requireCartId } from '../cookies';
/**
* Create a payment for a non-session payment method (e.g. Check, Cash on Delivery, Bank Transfer).
@@ -12,8 +12,9 @@ import { getCheckoutOptions } from '../cookies';
export async function createPayment(
params: CreatePaymentParams
): Promise<Payment> {
- const options = await getCheckoutOptions();
- const result = await getClient().checkout.payments.create(params, options);
+ const options = await getCartOptions();
+ const cartId = await requireCartId();
+ const result = await getClient().carts.payments.create(cartId, params, options);
revalidateTag('checkout');
return result;
}
diff --git a/packages/next/src/cookies.ts b/packages/next/src/cookies.ts
index 6658cd8a46..aa3071f06b 100644
--- a/packages/next/src/cookies.ts
+++ b/packages/next/src/cookies.ts
@@ -14,6 +14,10 @@ function getCartCookieName(): string {
}
}
+function getCartIdCookieName(): string {
+ return `${getCartCookieName()}_id`;
+}
+
function getAccessTokenCookieName(): string {
try {
return getConfig().accessTokenCookieName ?? DEFAULT_ACCESS_TOKEN_COOKIE;
@@ -48,6 +52,32 @@ export async function clearCartToken(): Promise<void> {
});
}
+// --- Cart ID (prefixed ID stored alongside token for REST API) ---
+
+export async function getCartId(): Promise<string | undefined> {
+ const cookieStore = await cookies();
+ return cookieStore.get(getCartIdCookieName())?.value;
+}
+
+export async function setCartId(id: string): Promise<void> {
+ const cookieStore = await cookies();
+ cookieStore.set(getCartIdCookieName(), id, {
+ httpOnly: true,
+ secure: process.env.NODE_ENV === 'production',
+ sameSite: 'lax',
+ path: '/',
+ maxAge: CART_TOKEN_MAX_AGE,
+ });
+}
+
+export async function clearCartId(): Promise<void> {
+ const cookieStore = await cookies();
+ cookieStore.set(getCartIdCookieName(), '', {
+ maxAge: -1,
+ path: '/',
+ });
+}
+
// --- Access Token (JWT) ---
export async function getAccessToken(): Promise<string | undefined> {
@@ -74,9 +104,9 @@ export async function clearAccessToken(): Promise<void> {
});
}
-// --- Checkout Options (combined cart + access tokens for checkout/payment actions) ---
+// --- Cart Options (combined cart + access tokens for cart/checkout/payment actions) ---
-export async function getCheckoutOptions(): Promise<{
+export async function getCartOptions(): Promise<{
spreeToken: string | undefined;
token: string | undefined;
}> {
@@ -84,3 +114,11 @@ export async function getCheckoutOptions(): Promise<{
const token = await getAccessToken();
return { spreeToken, token };
}
+
+// --- Cart ID (required) ---
+
+export async function requireCartId(): Promise<string> {
+ const cartId = await getCartId();
+ if (!cartId) throw new Error('No cart found');
+ return cartId;
+}
diff --git a/packages/next/src/index.ts b/packages/next/src/index.ts
index 1bf0a98bcf..3e568cdac0 100644
--- a/packages/next/src/index.ts
+++ b/packages/next/src/index.ts
@@ -19,17 +19,13 @@ export {
removeItem,
clearCart,
associateCart,
-} from './actions/cart';
-
-export {
- getCheckout,
- updateCheckout,
+ updateCart,
getShipments,
selectShippingRate,
applyCoupon,
removeCoupon,
complete,
-} from './actions/checkout';
+} from './actions/cart';
export {
login,
@@ -100,7 +96,7 @@ export type {
AddressParams,
CreateCartParams,
LineItemInput,
- UpdateCheckoutParams,
+ UpdateCartParams,
ProductFiltersResponse,
CreatePaymentParams,
CreatePaymentSessionParams,
diff --git a/packages/next/tests/actions/auth.test.ts b/packages/next/tests/actions/auth.test.ts
index d8d082ffa3..e29dcd4610 100644
--- a/packages/next/tests/actions/auth.test.ts
+++ b/packages/next/tests/actions/auth.test.ts
@@ -14,7 +14,7 @@ const mockClient = {
get: vi.fn(),
update: vi.fn(),
},
- cart: {
+ carts: {
associate: vi.fn(),
},
};
@@ -35,6 +35,13 @@ vi.mock('@spree/sdk', () => ({
import { login, register, logout, getCustomer, updateCustomer } from '../../src/actions/auth';
import { revalidateTag } from 'next/cache';
+function mockCookies(values: Record<string, string | undefined>) {
+ mockCookieStore.get.mockImplementation((name: string) => {
+ const val = values[name];
+ return val ? { value: val } : undefined;
+ });
+}
+
describe('auth actions', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -48,7 +55,7 @@ describe('auth actions', () => {
token: 'jwt_new',
user: { id: '1', email: '[email protected]', first_name: 'Test', last_name: 'User' },
};
- mockCookieStore.get.mockReturnValue(undefined); // no cart token
+ mockCookies({}); // no cart token
mockClient.auth.login.mockResolvedValue(authResult);
const result = await login('[email protected]', 'password123');
@@ -64,16 +71,21 @@ describe('auth actions', () => {
it('associates guest cart after login', async () => {
const authResult = { token: 'jwt_new', user: { id: '1', email: '[email protected]' } };
- mockCookieStore.get
- .mockReturnValueOnce({ value: 'guest_cart_token' }); // getCartToken
+ mockCookies({
+ '_spree_cart_token': 'guest_cart_token',
+ '_spree_cart_token_id': 'cart_1',
+ });
mockClient.auth.login.mockResolvedValue(authResult);
- mockClient.cart.associate.mockResolvedValue({});
+ mockClient.carts.associate.mockResolvedValue({});
await login('[email protected]', 'pass');
- expect(mockClient.cart.associate).toHaveBeenCalledWith({
- token: 'jwt_new',
- spreeToken: 'guest_cart_token',
- });
+ expect(mockClient.carts.associate).toHaveBeenCalledWith(
+ 'cart_1',
+ {
+ token: 'jwt_new',
+ spreeToken: 'guest_cart_token',
+ }
+ );
});
it('returns error on failure', async () => {
@@ -106,7 +118,7 @@ describe('auth actions', () => {
token: 'jwt_new',
user: { id: '1', email: '[email protected]', first_name: 'John', last_name: 'Doe' },
};
- mockCookieStore.get.mockReturnValue(undefined); // no cart token
+ mockCookies({}); // no cart token
mockClient.customers.create.mockResolvedValue(authResult);
const result = await register({
@@ -143,10 +155,12 @@ describe('auth actions', () => {
it('associates guest cart after registration', async () => {
const authResult = { token: 'jwt_new', user: { id: '1', email: '[email protected]' } };
- mockCookieStore.get
- .mockReturnValueOnce({ value: 'guest_cart_token' });
+ mockCookies({
+ '_spree_cart_token': 'guest_cart_token',
+ '_spree_cart_token_id': 'cart_1',
+ });
mockClient.customers.create.mockResolvedValue(authResult);
- mockClient.cart.associate.mockResolvedValue({});
+ mockClient.carts.associate.mockResolvedValue({});
await register({
@@ -154,10 +168,13 @@ describe('auth actions', () => {
password_confirmation: 'password123',
});
- expect(mockClient.cart.associate).toHaveBeenCalledWith({
- token: 'jwt_new',
- spreeToken: 'guest_cart_token',
- });
+ expect(mockClient.carts.associate).toHaveBeenCalledWith(
+ 'cart_1',
+ {
+ token: 'jwt_new',
+ spreeToken: 'guest_cart_token',
+ }
+ );
});
it('returns error on failure', async () => {
@@ -184,7 +201,7 @@ describe('auth actions', () => {
phone: '+1234567890',
accepts_email_marketing: true,
};
- mockCookieStore.get.mockReturnValue({ value: 'valid_jwt' });
+ mockCookies({ '_spree_jwt': 'valid_jwt' });
mockClient.customer.update.mockResolvedValue(updatedCustomer);
const result = await updateCustomer({
@@ -210,14 +227,14 @@ describe('auth actions', () => {
describe('getCustomer', () => {
it('returns null when not authenticated', async () => {
- mockCookieStore.get.mockReturnValue(undefined);
+ mockCookies({});
const customer = await getCustomer();
expect(customer).toBeNull();
});
it('returns customer when authenticated', async () => {
const mockUser = { id: '1', email: '[email protected]' };
- mockCookieStore.get.mockReturnValue({ value: 'valid_jwt' });
+ mockCookies({ '_spree_jwt': 'valid_jwt' });
mockClient.customer.get.mockResolvedValue(mockUser);
const customer = await getCustomer();
diff --git a/packages/next/tests/actions/cart.test.ts b/packages/next/tests/actions/cart.test.ts
index e1bcf2cc6b..7f5a24e68f 100644
--- a/packages/next/tests/actions/cart.test.ts
+++ b/packages/next/tests/actions/cart.test.ts
@@ -4,15 +4,22 @@ import { initSpreeNext, resetClient } from '../../src/config';
// Mock the SDK client
const mockClient = {
- cart: {
+ carts: {
get: vi.fn(),
+ list: vi.fn(),
create: vi.fn(),
+ update: vi.fn(),
+ complete: vi.fn(),
associate: vi.fn(),
items: {
create: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
},
+ shipments: {
+ list: vi.fn(),
+ update: vi.fn(),
+ },
couponCodes: {
apply: vi.fn(),
remove: vi.fn(),
@@ -24,9 +31,24 @@ vi.mock('@spree/sdk', () => ({
createClient: vi.fn(() => mockClient),
}));
-import { getCart, getOrCreateCart, addItem, updateItem, removeItem, clearCart, associateCart } from '../../src/actions/cart';
+import {
+ getCart, getOrCreateCart, addItem, updateItem, removeItem, clearCart, associateCart,
+ updateCart, getShipments, selectShippingRate, applyCoupon, removeCoupon, complete,
+} from '../../src/actions/cart';
import { revalidateTag } from 'next/cache';
+// Cookie names used by the actions:
+// _spree_cart_token → getCartToken()
+// _spree_cart_token_id → getCartId()
+// _spree_jwt → getAccessToken()
+
+function mockCookies(values: Record<string, string | undefined>) {
+ mockCookieStore.get.mockImplementation((name: string) => {
+ const val = values[name];
+ return val ? { value: val } : undefined;
+ });
+}
+
describe('cart actions', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -36,26 +58,33 @@ describe('cart actions', () => {
describe('getCart', () => {
it('returns null when no tokens exist', async () => {
- mockCookieStore.get.mockReturnValue(undefined);
+ mockCookies({});
const cart = await getCart();
expect(cart).toBeNull();
});
- it('returns cart when order token exists', async () => {
- const mockCart = { id: '1', token: 'order_abc', line_items: [] };
- mockCookieStore.get.mockReturnValue({ value: 'order_abc' });
- mockClient.cart.get.mockResolvedValue(mockCart);
+ it('returns cart when cart ID and token exist', async () => {
+ const mockCart = { id: 'cart_1', token: 'order_abc', items: [] };
+ mockCookies({
+ '_spree_cart_token': 'order_abc',
+ '_spree_cart_token_id': 'cart_1',
+ });
+ mockClient.carts.get.mockResolvedValue(mockCart);
const cart = await getCart();
expect(cart).toEqual(mockCart);
- expect(mockClient.cart.get).toHaveBeenCalledWith(
+ expect(mockClient.carts.get).toHaveBeenCalledWith(
+ 'cart_1',
expect.objectContaining({ spreeToken: 'order_abc' })
);
});
it('returns null when cart fetch fails', async () => {
- mockCookieStore.get.mockReturnValue({ value: 'bad_token' });
- mockClient.cart.get.mockRejectedValue(new Error('Not found'));
+ mockCookies({
+ '_spree_cart_token': 'bad_token',
+ '_spree_cart_token_id': 'cart_1',
+ });
+ mockClient.carts.get.mockRejectedValue(new Error('Not found'));
const cart = await getCart();
expect(cart).toBeNull();
@@ -64,43 +93,55 @@ describe('cart actions', () => {
describe('getOrCreateCart', () => {
it('returns existing cart if available', async () => {
- const mockCart = { id: '1', token: 'existing', line_items: [] };
- mockCookieStore.get.mockReturnValue({ value: 'existing' });
- mockClient.cart.get.mockResolvedValue(mockCart);
+ const mockCart = { id: 'cart_1', token: 'existing', items: [] };
+ mockCookies({
+ '_spree_cart_token': 'existing',
+ '_spree_cart_token_id': 'cart_1',
+ });
+ mockClient.carts.get.mockResolvedValue(mockCart);
const cart = await getOrCreateCart();
expect(cart).toEqual(mockCart);
- expect(mockClient.cart.create).not.toHaveBeenCalled();
+ expect(mockClient.carts.create).not.toHaveBeenCalled();
});
it('creates new cart when none exists', async () => {
- const newCart = { id: '2', token: 'new_token', line_items: [] };
- mockCookieStore.get.mockReturnValue(undefined);
- mockClient.cart.create.mockResolvedValue(newCart);
+ const newCart = { id: 'cart_2', token: 'new_token', items: [] };
+ mockCookies({});
+ mockClient.carts.create.mockResolvedValue(newCart);
const cart = await getOrCreateCart();
expect(cart).toEqual(newCart);
- expect(mockClient.cart.create).toHaveBeenCalled();
+ expect(mockClient.carts.create).toHaveBeenCalled();
expect(mockCookieStore.set).toHaveBeenCalledWith(
'_spree_cart_token',
'new_token',
expect.any(Object)
);
+ expect(mockCookieStore.set).toHaveBeenCalledWith(
+ '_spree_cart_token_id',
+ 'cart_2',
+ expect.any(Object)
+ );
});
});
describe('addItem', () => {
- it('adds line item and invalidates cache', async () => {
- const mockCart = { id: '1', token: 'cart_token', line_items: [] };
- const updatedCart = { id: '1', token: 'cart_token', line_items: [{ id: 'li_1' }] };
- mockCookieStore.get.mockReturnValue({ value: 'cart_token' });
- mockClient.cart.get.mockResolvedValue(mockCart);
- mockClient.cart.items.create.mockResolvedValue(updatedCart);
+ it('adds item and invalidates cache', async () => {
+ const mockCart = { id: 'cart_1', token: 'cart_token', items: [] };
+ const updatedCart = { id: 'cart_1', token: 'cart_token', items: [{ id: 'li_1' }] };
+ mockCookies({
+ '_spree_cart_token': 'cart_token',
+ '_spree_cart_token_id': 'cart_1',
+ });
+ mockClient.carts.get.mockResolvedValue(mockCart);
+ mockClient.carts.items.create.mockResolvedValue(updatedCart);
const result = await addItem('v1', 2);
expect(result).toEqual(updatedCart);
- expect(mockClient.cart.items.create).toHaveBeenCalledWith(
- { variant_id: 'v1', quantity: 2 },
+ expect(mockClient.carts.items.create).toHaveBeenCalledWith(
+ 'cart_1',
+ { variant_id: 'v1', quantity: 2, metadata: undefined },
expect.objectContaining({ spreeToken: 'cart_token' })
);
expect(revalidateTag).toHaveBeenCalledWith('cart');
@@ -108,14 +149,18 @@ describe('cart actions', () => {
});
describe('updateItem', () => {
- it('updates line item and invalidates cache', async () => {
- const updatedCart = { id: '1', token: 'cart_token', item_count: 3 };
- mockCookieStore.get.mockReturnValue({ value: 'cart_token' });
- mockClient.cart.items.update.mockResolvedValue(updatedCart);
+ it('updates item and invalidates cache', async () => {
+ const updatedCart = { id: 'cart_1', token: 'cart_token', item_count: 3 };
+ mockCookies({
+ '_spree_cart_token': 'cart_token',
+ '_spree_cart_token_id': 'cart_1',
+ });
+ mockClient.carts.items.update.mockResolvedValue(updatedCart);
const result = await updateItem('li_1', { quantity: 3 });
expect(result).toEqual(updatedCart);
- expect(mockClient.cart.items.update).toHaveBeenCalledWith(
+ expect(mockClient.carts.items.update).toHaveBeenCalledWith(
+ 'cart_1',
'li_1',
{ quantity: 3 },
expect.objectContaining({ spreeToken: 'cart_token' })
@@ -125,14 +170,18 @@ describe('cart actions', () => {
});
describe('removeItem', () => {
- it('deletes line item and invalidates cache', async () => {
- const updatedCart = { id: '1', token: 'cart_token', item_count: 0 };
- mockCookieStore.get.mockReturnValue({ value: 'cart_token' });
- mockClient.cart.items.delete.mockResolvedValue(updatedCart);
+ it('removes item and invalidates cache', async () => {
+ const updatedCart = { id: 'cart_1', token: 'cart_token', item_count: 0 };
+ mockCookies({
+ '_spree_cart_token': 'cart_token',
+ '_spree_cart_token_id': 'cart_1',
+ });
+ mockClient.carts.items.delete.mockResolvedValue(updatedCart);
const result = await removeItem('li_1');
expect(result).toEqual(updatedCart);
- expect(mockClient.cart.items.delete).toHaveBeenCalledWith(
+ expect(mockClient.carts.items.delete).toHaveBeenCalledWith(
+ 'cart_1',
'li_1',
expect.objectContaining({ spreeToken: 'cart_token' })
);
@@ -141,38 +190,172 @@ describe('cart actions', () => {
});
describe('clearCart', () => {
- it('clears cart cookie and invalidates cache', async () => {
+ it('clears cart cookies and invalidates cache', async () => {
await clearCart();
expect(mockCookieStore.set).toHaveBeenCalledWith(
'_spree_cart_token',
'',
expect.objectContaining({ maxAge: -1 })
);
+ expect(mockCookieStore.set).toHaveBeenCalledWith(
+ '_spree_cart_token_id',
+ '',
+ expect.objectContaining({ maxAge: -1 })
+ );
expect(revalidateTag).toHaveBeenCalledWith('cart');
});
});
describe('associateCart', () => {
- it('returns null when no cart token', async () => {
- mockCookieStore.get.mockReturnValue(undefined);
+ it('returns null when no cart ID', async () => {
+ mockCookies({});
const result = await associateCart();
expect(result).toBeNull();
});
- it('associates cart when both tokens exist', async () => {
- const mockCart = { id: '1', token: 'cart_token' };
- // First call returns cart token, second returns access token
- mockCookieStore.get
- .mockReturnValueOnce({ value: 'cart_token' })
- .mockReturnValueOnce({ value: 'jwt_token' });
- mockClient.cart.associate.mockResolvedValue(mockCart);
+ it('associates cart when cart ID and JWT exist', async () => {
+ const mockCart = { id: 'cart_1', token: 'cart_token' };
+ mockCookies({
+ '_spree_cart_token': 'cart_token',
+ '_spree_cart_token_id': 'cart_1',
+ '_spree_jwt': 'jwt_token',
+ });
+ mockClient.carts.associate.mockResolvedValue(mockCart);
const result = await associateCart();
expect(result).toEqual(mockCart);
- expect(mockClient.cart.associate).toHaveBeenCalledWith({
- spreeToken: 'cart_token',
- token: 'jwt_token',
+ expect(mockClient.carts.associate).toHaveBeenCalledWith(
+ 'cart_1',
+ { spreeToken: 'cart_token', token: 'jwt_token' }
+ );
+ });
+ });
+
+ describe('updateCart', () => {
+ it('updates cart and revalidates', async () => {
+ const updatedCart = { id: 'cart_1', number: 'R123' };
+ const params = { email: '[email protected]' };
+ mockCookies({
+ '_spree_cart_token': 'order_token',
+ '_spree_cart_token_id': 'cart_1',
+ '_spree_jwt': 'jwt_token',
+ });
+ mockClient.carts.update.mockResolvedValue(updatedCart);
+
+ const result = await updateCart(params);
+ expect(result).toEqual(updatedCart);
+ expect(mockClient.carts.update).toHaveBeenCalledWith(
+ 'cart_1',
+ params,
+ { spreeToken: 'order_token', token: 'jwt_token' }
+ );
+ expect(revalidateTag).toHaveBeenCalledWith('checkout');
+ });
+ });
+
+ describe('getShipments', () => {
+ it('returns shipments for the cart', async () => {
+ const mockShipments = { data: [{ id: 's1', shipping_rates: [] }] };
+ mockCookies({
+ '_spree_cart_token': 'order_token',
+ '_spree_cart_token_id': 'cart_1',
+ '_spree_jwt': 'jwt_token',
+ });
+ mockClient.carts.shipments.list.mockResolvedValue(mockShipments);
+
+ const result = await getShipments();
+ expect(result).toEqual(mockShipments);
+ expect(mockClient.carts.shipments.list).toHaveBeenCalledWith(
+ 'cart_1',
+ { spreeToken: 'order_token', token: 'jwt_token' }
+ );
+ });
+ });
+
+ describe('selectShippingRate', () => {
+ it('selects shipping rate and revalidates', async () => {
+ const updatedCart = { id: 'cart_1', ship_total: '10.0' };
+ mockCookies({
+ '_spree_cart_token': 'order_token',
+ '_spree_cart_token_id': 'cart_1',
+ '_spree_jwt': 'jwt_token',
+ });
+ mockClient.carts.shipments.update.mockResolvedValue(updatedCart);
+
+ const result = await selectShippingRate('s1', 'sr1');
+ expect(result).toEqual(updatedCart);
+ expect(mockClient.carts.shipments.update).toHaveBeenCalledWith(
+ 'cart_1',
+ 's1',
+ { selected_shipping_rate_id: 'sr1' },
+ { spreeToken: 'order_token', token: 'jwt_token' }
+ );
+ expect(revalidateTag).toHaveBeenCalledWith('checkout');
+ });
+ });
+
+ describe('applyCoupon', () => {
+ it('applies coupon and revalidates checkout and cart', async () => {
+ const updatedCart = { id: 'cart_1', promo_total: -10 };
+ mockCookies({
+ '_spree_cart_token': 'order_token',
+ '_spree_cart_token_id': 'cart_1',
+ '_spree_jwt': 'jwt_token',
});
+ mockClient.carts.couponCodes.apply.mockResolvedValue(updatedCart);
+
+ const result = await applyCoupon('SAVE10');
+ expect(result).toEqual(updatedCart);
+ expect(mockClient.carts.couponCodes.apply).toHaveBeenCalledWith(
+ 'cart_1',
+ 'SAVE10',
+ { spreeToken: 'order_token', token: 'jwt_token' }
+ );
+ expect(revalidateTag).toHaveBeenCalledWith('checkout');
+ expect(revalidateTag).toHaveBeenCalledWith('cart');
+ });
+ });
+
+ describe('removeCoupon', () => {
+ it('removes coupon and revalidates checkout and cart', async () => {
+ const updatedCart = { id: 'cart_1', promo_total: 0 };
+ mockCookies({
+ '_spree_cart_token': 'order_token',
+ '_spree_cart_token_id': 'cart_1',
+ '_spree_jwt': 'jwt_token',
+ });
+ mockClient.carts.couponCodes.remove.mockResolvedValue(updatedCart);
+
+ const result = await removeCoupon('SAVE10');
+ expect(result).toEqual(updatedCart);
+ expect(mockClient.carts.couponCodes.remove).toHaveBeenCalledWith(
+ 'cart_1',
+ 'SAVE10',
+ { spreeToken: 'order_token', token: 'jwt_token' }
+ );
+ expect(revalidateTag).toHaveBeenCalledWith('checkout');
+ expect(revalidateTag).toHaveBeenCalledWith('cart');
+ });
+ });
+
+ describe('complete', () => {
+ it('completes checkout and revalidates', async () => {
+ const mockOrder = { id: 'cart_1', state: 'complete' };
+ mockCookies({
+ '_spree_cart_token': 'order_token',
+ '_spree_cart_token_id': 'cart_1',
+ '_spree_jwt': 'jwt_token',
+ });
+ mockClient.carts.complete.mockResolvedValue(mockOrder);
+
+ const result = await complete();
+ expect(result).toEqual(mockOrder);
+ expect(mockClient.carts.complete).toHaveBeenCalledWith(
+ 'cart_1',
+ { spreeToken: 'order_token', token: 'jwt_token' }
+ );
+ expect(revalidateTag).toHaveBeenCalledWith('checkout');
+ expect(revalidateTag).toHaveBeenCalledWith('cart');
});
});
});
diff --git a/packages/next/tests/actions/checkout.test.ts b/packages/next/tests/actions/checkout.test.ts
deleted file mode 100644
index 731889ba9f..0000000000
--- a/packages/next/tests/actions/checkout.test.ts
+++ /dev/null
@@ -1,157 +0,0 @@
-import { describe, it, expect, beforeEach, vi } from 'vitest';
-import { mockCookieStore } from '../setup';
-import { initSpreeNext, resetClient } from '../../src/config';
-
-const mockClient = {
- cart: {
- get: vi.fn(),
- couponCodes: {
- apply: vi.fn(),
- remove: vi.fn(),
- },
- },
- checkout: {
- update: vi.fn(),
- complete: vi.fn(),
- shipments: {
- list: vi.fn(),
- update: vi.fn(),
- },
- },
-};
-
-vi.mock('@spree/sdk', () => ({
- createClient: vi.fn(() => mockClient),
-}));
-
-import {
- getCheckout,
- updateCheckout,
- getShipments,
- selectShippingRate,
- applyCoupon,
- removeCoupon,
- complete,
-} from '../../src/actions/checkout';
-import { revalidateTag } from 'next/cache';
-
-describe('checkout actions', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- resetClient();
- initSpreeNext({ baseUrl: 'https://api.test.com', publishableKey: 'pk_test' });
- // Default: cart token and access token available
- mockCookieStore.get
- .mockReturnValueOnce({ value: 'order_token_123' }) // getCartToken
- .mockReturnValueOnce({ value: 'jwt_token_abc' }); // getAccessToken
- });
-
- describe('getCheckout', () => {
- it('fetches cart with auth options', async () => {
- const mockCart = { id: '1', number: 'R123', line_items: [{ id: 'li1' }] };
- mockClient.cart.get.mockResolvedValue(mockCart);
-
- const result = await getCheckout();
- expect(result).toEqual(mockCart);
- expect(mockClient.cart.get).toHaveBeenCalledWith({
- spreeToken: 'order_token_123',
- token: 'jwt_token_abc',
- });
- });
- });
-
- describe('updateCheckout', () => {
- it('updates checkout and revalidates', async () => {
- const mockCart = { id: '1', number: 'R123' };
- const params = {
- email: '[email protected]',
- ship_address: { firstname: 'John', lastname: 'Doe', address1: '123 Main St', city: 'NY', zipcode: '10001', country_iso: 'US' },
- };
- mockClient.checkout.update.mockResolvedValue(mockCart);
-
- const result = await updateCheckout(params);
- expect(result).toEqual(mockCart);
- expect(mockClient.checkout.update).toHaveBeenCalledWith(
- params,
- { spreeToken: 'order_token_123', token: 'jwt_token_abc' }
- );
- expect(revalidateTag).toHaveBeenCalledWith('checkout');
- });
- });
-
- describe('getShipments', () => {
- it('returns shipments for the cart', async () => {
- const mockShipments = { data: [{ id: 's1', shipping_rates: [] }] };
- mockClient.checkout.shipments.list.mockResolvedValue(mockShipments);
-
- const result = await getShipments();
- expect(result).toEqual(mockShipments);
- expect(mockClient.checkout.shipments.list).toHaveBeenCalledWith(
- { spreeToken: 'order_token_123', token: 'jwt_token_abc' }
- );
- });
- });
-
- describe('selectShippingRate', () => {
- it('selects shipping rate and revalidates checkout', async () => {
- const mockCart = { id: '1', number: 'R123', ship_total: '10.0' };
- mockClient.checkout.shipments.update.mockResolvedValue(mockCart);
-
- const result = await selectShippingRate('s1', 'sr1');
- expect(result).toEqual(mockCart);
- expect(mockClient.checkout.shipments.update).toHaveBeenCalledWith(
- 's1',
- { selected_shipping_rate_id: 'sr1' },
- { spreeToken: 'order_token_123', token: 'jwt_token_abc' }
- );
- expect(revalidateTag).toHaveBeenCalledWith('checkout');
- });
- });
-
- describe('applyCoupon', () => {
- it('applies coupon and revalidates checkout and cart', async () => {
- const mockCart = { id: '1', promo_total: -10 };
- mockClient.cart.couponCodes.apply.mockResolvedValue(mockCart);
-
- const result = await applyCoupon('SAVE10');
- expect(result).toEqual(mockCart);
- expect(mockClient.cart.couponCodes.apply).toHaveBeenCalledWith(
- 'SAVE10',
- { spreeToken: 'order_token_123', token: 'jwt_token_abc' }
- );
- expect(revalidateTag).toHaveBeenCalledWith('checkout');
- expect(revalidateTag).toHaveBeenCalledWith('cart');
- });
- });
-
- describe('removeCoupon', () => {
- it('removes coupon and revalidates checkout and cart', async () => {
- const mockCart = { id: '1', promo_total: 0 };
- mockClient.cart.couponCodes.remove.mockResolvedValue(mockCart);
-
- const result = await removeCoupon('SAVE10');
- expect(result).toEqual(mockCart);
- expect(mockClient.cart.couponCodes.remove).toHaveBeenCalledWith(
- 'SAVE10',
- { spreeToken: 'order_token_123', token: 'jwt_token_abc' }
- );
- expect(revalidateTag).toHaveBeenCalledWith('checkout');
- expect(revalidateTag).toHaveBeenCalledWith('cart');
- });
- });
-
- describe('complete', () => {
- it('completes checkout and revalidates checkout and cart', async () => {
- const mockOrder = { id: '1', state: 'complete' };
- mockClient.checkout.complete.mockResolvedValue(mockOrder);
-
- const result = await complete();
- expect(result).toEqual(mockOrder);
- expect(mockClient.checkout.complete).toHaveBeenCalledWith(
- { spreeToken: 'order_token_123', token: 'jwt_token_abc' }
- );
- expect(revalidateTag).toHaveBeenCalledWith('checkout');
- expect(revalidateTag).toHaveBeenCalledWith('cart');
- });
- });
-});
diff --git a/packages/next/tests/actions/payment-sessions.test.ts b/packages/next/tests/actions/payment-sessions.test.ts
index b23ecab932..efceb07817 100644
--- a/packages/next/tests/actions/payment-sessions.test.ts
+++ b/packages/next/tests/actions/payment-sessions.test.ts
@@ -3,7 +3,7 @@ import { mockCookieStore } from '../setup';
import { initSpreeNext, resetClient } from '../../src/config';
const mockClient = {
- checkout: {
+ carts: {
paymentSessions: {
create: vi.fn(),
get: vi.fn(),
@@ -25,24 +25,34 @@ import {
} from '../../src/actions/payment-sessions';
import { revalidateTag } from 'next/cache';
+function mockCookies(values: Record<string, string | undefined>) {
+ mockCookieStore.get.mockImplementation((name: string) => {
+ const val = values[name];
+ return val ? { value: val } : undefined;
+ });
+}
+
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' });
+ mockCookies({
+ '_spree_cart_token': 'order_token_123',
+ '_spree_cart_token_id': 'cart_1',
+ '_spree_jwt': '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.checkout.paymentSessions.create.mockResolvedValue(mockSession);
+ mockClient.carts.paymentSessions.create.mockResolvedValue(mockSession);
const result = await createPaymentSession({ payment_method_id: 'pm_1' });
expect(result).toEqual(mockSession);
- expect(mockClient.checkout.paymentSessions.create).toHaveBeenCalledWith(
+ expect(mockClient.carts.paymentSessions.create).toHaveBeenCalledWith(
+ 'cart_1',
{ payment_method_id: 'pm_1' },
{ spreeToken: 'order_token_123', token: 'jwt_token_abc' }
);
@@ -53,11 +63,12 @@ describe('payment session actions', () => {
describe('getPaymentSession', () => {
it('returns a payment session by ID', async () => {
const mockSession = { id: 'ps_1', status: 'pending', amount: '99.99' };
- mockClient.checkout.paymentSessions.get.mockResolvedValue(mockSession);
+ mockClient.carts.paymentSessions.get.mockResolvedValue(mockSession);
const result = await getPaymentSession('ps_1');
expect(result).toEqual(mockSession);
- expect(mockClient.checkout.paymentSessions.get).toHaveBeenCalledWith(
+ expect(mockClient.carts.paymentSessions.get).toHaveBeenCalledWith(
+ 'cart_1',
'ps_1',
{ spreeToken: 'order_token_123', token: 'jwt_token_abc' }
);
@@ -67,11 +78,12 @@ describe('payment session actions', () => {
describe('updatePaymentSession', () => {
it('updates a payment session and revalidates checkout', async () => {
const mockSession = { id: 'ps_1', status: 'pending', amount: '50.00' };
- mockClient.checkout.paymentSessions.update.mockResolvedValue(mockSession);
+ mockClient.carts.paymentSessions.update.mockResolvedValue(mockSession);
const result = await updatePaymentSession('ps_1', { amount: '50.00' });
expect(result).toEqual(mockSession);
- expect(mockClient.checkout.paymentSessions.update).toHaveBeenCalledWith(
+ expect(mockClient.carts.paymentSessions.update).toHaveBeenCalledWith(
+ 'cart_1',
'ps_1',
{ amount: '50.00' },
{ spreeToken: 'order_token_123', token: 'jwt_token_abc' }
@@ -83,11 +95,12 @@ describe('payment session actions', () => {
describe('completePaymentSession', () => {
it('completes a payment session and revalidates checkout', async () => {
const mockSession = { id: 'ps_1', status: 'completed' };
- mockClient.checkout.paymentSessions.complete.mockResolvedValue(mockSession);
+ mockClient.carts.paymentSessions.complete.mockResolvedValue(mockSession);
const result = await completePaymentSession('ps_1', { session_result: 'success' });
expect(result).toEqual(mockSession);
- expect(mockClient.checkout.paymentSessions.complete).toHaveBeenCalledWith(
+ expect(mockClient.carts.paymentSessions.complete).toHaveBeenCalledWith(
+ 'cart_1',
'ps_1',
{ session_result: 'success' },
{ spreeToken: 'order_token_123', token: 'jwt_token_abc' }
@@ -97,11 +110,12 @@ describe('payment session actions', () => {
it('completes without params', async () => {
const mockSession = { id: 'ps_1', status: 'completed' };
- mockClient.checkout.paymentSessions.complete.mockResolvedValue(mockSession);
+ mockClient.carts.paymentSessions.complete.mockResolvedValue(mockSession);
const result = await completePaymentSession('ps_1');
expect(result).toEqual(mockSession);
- expect(mockClient.checkout.paymentSessions.complete).toHaveBeenCalledWith(
+ expect(mockClient.carts.paymentSessions.complete).toHaveBeenCalledWith(
+ 'cart_1',
'ps_1',
undefined,
{ spreeToken: 'order_token_123', token: 'jwt_token_abc' }
diff --git a/packages/next/tsup.config.ts b/packages/next/tsup.config.ts
index 93e50a80e6..23cafd2dc0 100644
--- a/packages/next/tsup.config.ts
+++ b/packages/next/tsup.config.ts
@@ -26,7 +26,6 @@ export default defineConfig([
{
entry: {
'actions/cart': 'src/actions/cart.ts',
- 'actions/checkout': 'src/actions/checkout.ts',
'actions/auth': 'src/actions/auth.ts',
'actions/addresses': 'src/actions/addresses.ts',
'actions/orders': 'src/actions/orders.ts',
diff --git a/packages/sdk/CHANGELOG.md b/packages/sdk/CHANGELOG.md
index 5b8e968761..0d3c248464 100644
--- a/packages/sdk/CHANGELOG.md
+++ b/packages/sdk/CHANGELOG.md
@@ -1,10 +1,48 @@
# @spree/sdk
+## 0.10.0
+
+### Minor Changes
+
+- Unified cart and checkout under single `carts` resource
+
+ **Breaking changes:**
+
+ - Removed `client.cart` (singular) and `client.checkout` namespaces
+ - All cart and checkout operations are now under `client.carts`
+ - All operations on a specific cart now require `cartId` as the first argument
+ - `UpdateCheckoutParams` renamed to `UpdateCartParams`
+
+ **Migration guide:**
+
+ ```typescript
+ // Before (0.9.x)
+ client.cart.create();
+ client.cart.get(options);
+ client.cart.items.create(params, options);
+ client.checkout.update(params, options);
+ client.checkout.complete(options);
+ client.checkout.shipments.list(options);
+ client.checkout.payments.create(params, options);
+ client.checkout.paymentSessions.create(params, options);
+
+ // After (0.10.0)
+ client.carts.create();
+ client.carts.get(cartId, options);
+ client.carts.items.create(cartId, params, options);
+ client.carts.update(cartId, params, options);
+ client.carts.complete(cartId, options);
+ client.carts.shipments.list(cartId, options);
+ client.carts.payments.create(cartId, params, options);
+ client.carts.paymentSessions.create(cartId, params, options);
+ ```
+
## 0.9.0
### Minor Changes
- **Breaking:** Cart API no longer returns `state`, `checkout_steps`, or `state_lock_version`. These are replaced by:
+
- `current_step` — the current checkout step (e.g. `"address"`, `"delivery"`, `"payment"`)
- `completed_steps` — array of steps already completed
- `requirements` — array of `{ step, field, message }` objects describing what's still needed to complete checkout
diff --git a/packages/sdk/README.md b/packages/sdk/README.md
index bc1ba9a220..29d57954d7 100644
--- a/packages/sdk/README.md
+++ b/packages/sdk/README.md
@@ -39,17 +39,17 @@ const { token, user } = await client.auth.login({
});
// Create a cart and add items
-const cart = await client.cart.create();
-await client.cart.items.create({
+const cart = await client.carts.create();
+await client.carts.items.create(cart.id, {
variant_id: 'var_abc123',
quantity: 2,
}, { spreeToken: cart.token });
-// Checkout flow
-await client.checkout.update({
+// Update cart and complete
+await client.carts.update(cart.id, {
}, { spreeToken: cart.token });
-await client.checkout.complete({ spreeToken: cart.token });
+await client.carts.complete(cart.id, { spreeToken: cart.token });
```
## Client Architecture
@@ -57,14 +57,15 @@ await client.checkout.complete({ spreeToken: cart.token });
All Store API resources are available directly on the client:
```typescript
-client.products.list() // Products
-client.cart.create() // Cart (singleton)
-client.cart.items.create(params) // Cart line items
-client.carts.list() // List active carts
-client.checkout.complete(opt) // Checkout
-client.customers.create(params) // Registration
-client.customer.get(opt) // Account
-client.customer.orders.list() // Order history
+client.products.list() // Products
+client.carts.create() // Create a cart
+client.carts.get(cartId) // Get a cart by ID
+client.carts.items.create(cartId, params) // Cart line items
+client.carts.complete(cartId, opt) // Complete cart
+client.carts.list(opt) // List active carts
+client.customers.create(params) // Registration
+client.customer.get(opt) // Account
+client.customer.orders.list() // Order history
```
## Authentication
@@ -117,24 +118,24 @@ For guest checkout, use the `token` returned when creating a cart:
```typescript
// Create a cart (guest)
-const cart = await client.cart.create();
+const cart = await client.carts.create();
-// Use spreeToken for all cart/checkout operations
+// Use spreeToken for all cart operations
const options = { spreeToken: cart.token };
// Add items
-await client.cart.items.create({
+await client.carts.items.create(cart.id, {
variant_id: 'var_abc123',
quantity: 1,
}, options);
-// Update checkout with email and addresses
-await client.checkout.update({
+// Update cart with email and addresses
+await client.carts.update(cart.id, {
}, options);
-// Complete checkout
-await client.checkout.complete(options);
+// Complete the order
+await client.carts.complete(cart.id, options);
```
## API Reference
@@ -190,30 +191,46 @@ const categoryProducts = await client.categories.products.list('clothing/shirts'
});
```
-### Cart
+### Carts
-The cart API uses an implicit cart model -- no order ID is needed. The cart is resolved
-from the `spreeToken` header (guest) or JWT token (authenticated user).
+All cart operations use explicit cart IDs (`cart_xxx`). The cart is authorized
+via `spreeToken` header (guest) or JWT token (authenticated user).
```typescript
// Create a new cart
-const cart = await client.cart.create();
+const cart = await client.carts.create();
-// Get current cart
-const cart = await client.cart.get({ spreeToken: cart.token });
+// Get a cart by ID
+const cart = await client.carts.get('cart_xxx', { spreeToken: cart.token });
-// Delete / empty current cart
-await client.cart.delete({ spreeToken: cart.token });
+// Delete / abandon a cart
+await client.carts.delete('cart_xxx', { spreeToken: cart.token });
// Associate guest cart with authenticated user
-// (after user logs in, merge their guest cart with their account)
-await client.cart.associate({
+await client.carts.associate('cart_xxx', {
token: jwtToken, // User's JWT token
- spreeToken: cart.token, // Guest cart token
});
// List all active carts for authenticated user
const { data: carts } = await client.carts.list({ token: jwtToken });
+
+// Update cart (email, addresses, special instructions)
+await client.carts.update('cart_xxx', {
+ email: '[email protected]',
+ ship_address: {
+ firstname: 'John',
+ lastname: 'Doe',
+ address1: '123 Main St',
+ city: 'New York',
+ zipcode: '10001',
+ phone: '+1 555 123 4567',
+ country_iso: 'US',
+ state_abbr: 'NY',
+ },
+}, options);
+
+// Complete the order
+await client.carts.complete('cart_xxx', options);
```
### Cart Items (Line Items)
@@ -222,18 +239,18 @@ const { data: carts } = await client.carts.list({ token: jwtToken });
const options = { spreeToken: cart.token };
// Add item
-await client.cart.items.create({
+await client.carts.items.create('cart_xxx', {
variant_id: 'var_123',
quantity: 2,
}, options);
// Update item quantity
-await client.cart.items.update(lineItemId, {
+await client.carts.items.update('cart_xxx', lineItemId, {
quantity: 3,
}, options);
// Remove item
-await client.cart.items.delete(lineItemId, options);
+await client.carts.items.delete('cart_xxx', lineItemId, options);
```
### Coupon Codes
@@ -242,38 +259,10 @@ await client.cart.items.delete(lineItemId, options);
const options = { spreeToken: cart.token };
// Apply a coupon code
-await client.cart.couponCodes.apply('SAVE20', options);
+await client.carts.couponCodes.apply('cart_xxx', 'SAVE20', options);
// Remove a coupon code
-await client.cart.couponCodes.remove('promo_xxx', options);
-```
-
-### Checkout
-
-The checkout API operates on the current cart, resolved implicitly from the
-`spreeToken` header or JWT token.
-
-```typescript
-const options = { spreeToken: cart.token };
-
-// Update checkout (email, addresses)
-await client.checkout.update({
- email: '[email protected]',
- ship_address: {
- firstname: 'John',
- lastname: 'Doe',
- address1: '123 Main St',
- city: 'New York',
- zipcode: '10001',
- phone: '+1 555 123 4567',
- country_iso: 'US',
- state_abbr: 'NY',
- },
- bill_address_id: 'addr_xxx', // Or use existing address by ID
-}, options);
-
-// Complete the order
-await client.checkout.complete(options);
+await client.carts.couponCodes.remove('cart_xxx', 'SAVE20', options);
```
### Shipments
@@ -281,11 +270,11 @@ await client.checkout.complete(options);
```typescript
const options = { spreeToken: cart.token };
-// List shipments for the current checkout
-const shipments = await client.checkout.shipments.list(options);
+// List shipments for the cart
+const shipments = await client.carts.shipments.list('cart_xxx', options);
// Select a shipping rate
-await client.checkout.shipments.update(shipmentId, {
+await client.carts.shipments.update('cart_xxx', shipmentId, {
selected_shipping_rate_id: 'rate_xxx',
}, options);
```
@@ -295,14 +284,14 @@ await client.checkout.shipments.update(shipmentId, {
```typescript
const options = { spreeToken: cart.token };
-// Apply store credit to checkout (applies maximum available by default)
-await client.checkout.storeCredits.apply(undefined, options);
+// Apply store credit (applies maximum available by default)
+await client.carts.storeCredits.apply('cart_xxx', undefined, options);
// Apply specific amount of store credit
-await client.checkout.storeCredits.apply(25.00, options);
+await client.carts.storeCredits.apply('cart_xxx', 25.00, options);
-// Remove store credit from checkout
-await client.checkout.storeCredits.remove(options);
+// Remove store credit
+await client.carts.storeCredits.remove('cart_xxx', options);
```
### Payments
@@ -311,20 +300,20 @@ await client.checkout.storeCredits.remove(options);
const options = { spreeToken: cart.token };
// Get available payment methods for the current checkout
-const methods = await client.checkout.paymentMethods.list(options);
+const methods = await client.carts.paymentMethods.list('cart_xxx', options);
// Each method includes `session_required` flag:
// - true -> use paymentSessions (Stripe, Adyen, PayPal, etc.)
// - false -> use payments.create (Check, Cash on Delivery, Bank Transfer, etc.)
-// List payments on the current checkout
-const payments = await client.checkout.payments.list(options);
+// List payments on the cart
+const payments = await client.carts.payments.list('cart_xxx', options);
// Get a specific payment
-const payment = await client.checkout.payments.get(paymentId, options);
+const payment = await client.carts.payments.get('cart_xxx', paymentId, options);
// Create a payment for a non-session payment method
// (e.g. Check, Cash on Delivery, Bank Transfer, Purchase Order)
-const payment = await client.checkout.payments.create({
+const payment = await client.carts.payments.create('cart_xxx', {
payment_method_id: 'pm_xxx',
amount: '99.99', // Optional, defaults to order total minus store credits
metadata: { // Optional, write-only metadata
@@ -341,7 +330,7 @@ Payment sessions provide a unified, provider-agnostic interface for payment proc
const options = { spreeToken: cart.token };
// Create a payment session (initializes a session with the payment gateway)
-const session = await client.checkout.paymentSessions.create({
+const session = await client.carts.paymentSessions.create('cart_xxx', {
payment_method_id: 'pm_xxx',
amount: '99.99', // Optional, defaults to order total
external_data: { // Optional, provider-specific data
@@ -353,17 +342,18 @@ const session = await client.checkout.paymentSessions.create({
console.log(session.external_data.client_secret);
// Get a payment session
-const existing = await client.checkout.paymentSessions.get(
- session.id, options
+const existing = await client.carts.paymentSessions.get(
+ 'cart_xxx', session.id, options
);
// Update a payment session (e.g., after order total changes)
-await client.checkout.paymentSessions.update(session.id, {
+await client.carts.paymentSessions.update('cart_xxx', session.id, {
amount: '149.99',
}, options);
// Complete the payment session (after customer confirms payment on the frontend)
-const completed = await client.checkout.paymentSessions.complete(
+const completed = await client.carts.paymentSessions.complete(
+ 'cart_xxx',
session.id,
{ session_result: 'success' },
options
@@ -547,13 +537,13 @@ The SDK uses a resource builder pattern for nested resources:
| Parent Resource | Nested Resource | Available Methods |
|-----------------|-----------------|-------------------|
-| `cart` | `items` | `create`, `update`, `delete` |
-| `cart` | `couponCodes` | `apply`, `remove` |
-| `checkout` | `shipments` | `list`, `update` |
-| `checkout` | `paymentMethods` | `list` |
-| `checkout` | `payments` | `list`, `get`, `create` |
-| `checkout` | `paymentSessions` | `create`, `get`, `update`, `complete` |
-| `checkout` | `storeCredits` | `apply`, `remove` |
+| `carts` | `items` | `create`, `update`, `delete` |
+| `carts` | `couponCodes` | `apply`, `remove` |
+| `carts` | `shipments` | `list`, `update` |
+| `carts` | `paymentMethods` | `list` |
+| `carts` | `payments` | `list`, `get`, `create` |
+| `carts` | `paymentSessions` | `create`, `get`, `update`, `complete` |
+| `carts` | `storeCredits` | `apply`, `remove` |
| `customer` | `addresses` | `list`, `get`, `create`, `update`, `delete`, `markAsDefault` |
| `customer` | `creditCards` | `list`, `get`, `delete` |
| `customer` | `giftCards` | `list`, `get` |
@@ -564,15 +554,15 @@ The SDK uses a resource builder pattern for nested resources:
Example:
```typescript
-// Cart and checkout resources are implicit -- no order ID needed
-await client.cart.items.create(params, options);
-await client.cart.couponCodes.apply(code, options);
-await client.checkout.shipments.update(shipmentId, params, options);
-await client.checkout.payments.list(options);
-await client.checkout.paymentSessions.create(params, options);
-await client.checkout.storeCredits.apply(amount, options);
+// Cart resources take cartId as first argument
+await client.carts.items.create(cartId, params, options);
+await client.carts.couponCodes.apply(cartId, code, options);
+await client.carts.shipments.update(cartId, shipmentId, params, options);
+await client.carts.payments.list(cartId, options);
+await client.carts.paymentSessions.create(cartId, params, options);
+await client.carts.storeCredits.apply(cartId, amount, options);
-// Other nested resources follow the pattern: client.parent.nested.method(parentId, ...)
+// Other nested resources follow the same pattern
await client.customer.addresses.list({}, options);
await client.customer.orders.list({}, options);
await client.markets.countries.list(marketId);
@@ -656,7 +646,7 @@ import type {
// All responses are fully typed
const products: PaginatedResponse<StoreProduct> = await client.products.list();
const category: StoreCategory = await client.categories.get('clothing');
-const cart: StoreCart = await client.cart.create();
+const cart: StoreCart = await client.carts.get('cart_xxx');
```
## Available Types
@@ -711,7 +701,7 @@ The SDK exports all Store API types:
- `PaginatedResponse<T>` - Paginated API response
- `AuthTokens` - JWT tokens from login
- `AddressParams` - Address input parameters
-- `UpdateCheckoutParams` - Checkout update parameters
+- `UpdateCartParams` - Cart update parameters (email, addresses, etc.)
- `CreatePaymentParams` - Direct payment creation parameters (for non-session payment methods)
- `CreatePaymentSessionParams` - Payment session creation parameters
- `UpdatePaymentSessionParams` - Payment session update parameters
diff --git a/packages/sdk/package.json b/packages/sdk/package.json
index 2b5effc0fd..e1c19319f2 100644
--- a/packages/sdk/package.json
+++ b/packages/sdk/package.json
@@ -1,6 +1,6 @@
{
"name": "@spree/sdk",
- "version": "0.9.0",
+ "version": "0.10.0",
"description": "Official TypeScript SDK for Spree Commerce Store API",
"type": "module",
"main": "./dist/index.cjs",
diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts
index 4da4e01f03..22438f5d10 100644
--- a/packages/sdk/src/client.ts
+++ b/packages/sdk/src/client.ts
@@ -35,7 +35,7 @@ export interface Client extends StoreClient {
* ```ts
* const client = createClient({ baseUrl: '...', publishableKey: '...' })
* client.products.list()
- * client.cart.create()
+ * client.carts.create()
* client.orders.get('order_1')
* ```
*/
diff --git a/packages/sdk/src/store-client.ts b/packages/sdk/src/store-client.ts
index 84da2e12f7..7da5fe321c 100644
--- a/packages/sdk/src/store-client.ts
+++ b/packages/sdk/src/store-client.ts
@@ -18,7 +18,7 @@ import type {
CreateCartParams,
AddLineItemParams,
UpdateLineItemParams,
- UpdateCheckoutParams,
+ UpdateCartParams,
CreatePaymentParams,
CreatePaymentSessionParams,
UpdatePaymentSessionParams,
@@ -279,52 +279,70 @@ export class StoreClient {
};
// ============================================
- // Carts (list all active carts for authenticated users)
+ // Carts
// ============================================
readonly carts = {
/**
* List all active (incomplete) carts for the authenticated user
*/
- list: (options?: RequestOptions): Promise<ListResponse<Cart>> =>
- this.request<ListResponse<Cart>>('GET', '/carts', options),
- };
+ list: (options?: RequestOptions): Promise<PaginatedResponse<Cart>> =>
+ this.request<PaginatedResponse<Cart>>('GET', '/carts', options),
- // ============================================
- // Cart (pre-purchase, mutable)
- // ============================================
-
- readonly cart = {
/**
- * Get current cart
- * Pass spreeToken for guest checkout, or use JWT for authenticated users
+ * Get a cart by prefixed ID
+ * @param cartId - Cart prefixed ID (e.g., "cart_abc123")
*/
- get: (options?: RequestOptions): Promise<Cart> =>
- this.request<Cart>('GET', '/cart', options),
+ get: (cartId: string, options?: RequestOptions): Promise<Cart> =>
+ this.request<Cart>('GET', `/carts/${cartId}`, options),
/**
* Create a new cart
- * @param params - Optional cart parameters (e.g., metadata, line_items)
+ * @param params - Optional cart parameters (e.g., metadata, items)
*/
create: (params?: CreateCartParams, options?: RequestOptions): Promise<Cart> =>
- this.request<Cart>('POST', '/cart', {
+ this.request<Cart>('POST', '/carts', {
...options,
body: params,
}),
/**
- * Delete the current cart
+ * Update a cart (email, addresses, special instructions)
+ * @param cartId - Cart prefixed ID
+ * @param params - Cart update parameters
*/
- delete: (options?: RequestOptions): Promise<void> =>
- this.request<void>('DELETE', '/cart', options),
+ update: (
+ cartId: string,
+ params: UpdateCartParams,
+ options?: RequestOptions
+ ): Promise<Cart> =>
+ this.request<Cart>('PATCH', `/carts/${cartId}`, {
+ ...options,
+ body: params,
+ }),
+
+ /**
+ * Delete/abandon a cart
+ * @param cartId - Cart prefixed ID
+ */
+ delete: (cartId: string, options?: RequestOptions): Promise<void> =>
+ this.request<void>('DELETE', `/carts/${cartId}`, options),
/**
* Associate a guest cart with the currently authenticated user
- * Requires both JWT token (for authentication) and spreeToken (to identify the cart)
- * @param options - Must include both `token` (JWT) and `spreeToken` (guest cart token)
+ * @param cartId - Cart prefixed ID
+ * @param options - Must include `token` (JWT) for authentication
+ */
+ associate: (cartId: string, options: RequestOptions): Promise<Cart> =>
+ this.request<Cart>('PATCH', `/carts/${cartId}/associate`, options),
+
+ /**
+ * Complete the cart and finalize the purchase.
+ * Returns an Order (not Cart).
+ * @param cartId - Cart prefixed ID
*/
- associate: (options: RequestOptions): Promise<Cart> =>
- this.request<Cart>('PATCH', '/cart/associate', options),
+ complete: (cartId: string, options?: RequestOptions): Promise<Order> =>
+ this.request<Order>('POST', `/carts/${cartId}/complete`, options),
/**
* Nested resource: Line items
@@ -333,12 +351,14 @@ export class StoreClient {
/**
* Add an item to the cart.
* Returns the updated cart with recalculated totals.
+ * @param cartId - Cart prefixed ID
*/
create: (
+ cartId: string,
params: AddLineItemParams,
options?: RequestOptions
): Promise<Cart> =>
- this.request<Cart>('POST', '/cart/items', {
+ this.request<Cart>('POST', `/carts/${cartId}/items`, {
...options,
body: params,
}),
@@ -346,29 +366,33 @@ export class StoreClient {
/**
* Update a line item quantity.
* Returns the updated cart with recalculated totals.
+ * @param cartId - Cart prefixed ID
*/
update: (
+ cartId: string,
lineItemId: string,
params: UpdateLineItemParams,
options?: RequestOptions
): Promise<Cart> =>
this.request<Cart>(
'PATCH',
- `/cart/items/${lineItemId}`,
+ `/carts/${cartId}/items/${lineItemId}`,
{ ...options, body: params }
),
/**
* Remove a line item from the cart.
* Returns the updated cart with recalculated totals.
+ * @param cartId - Cart prefixed ID
*/
delete: (
+ cartId: string,
lineItemId: string,
options?: RequestOptions
): Promise<Cart> =>
this.request<Cart>(
'DELETE',
- `/cart/items/${lineItemId}`,
+ `/carts/${cartId}/items/${lineItemId}`,
options
),
},
@@ -379,84 +403,64 @@ export class StoreClient {
couponCodes: {
/**
* Apply a coupon code to the cart
+ * @param cartId - Cart prefixed ID
*/
apply: (
+ cartId: string,
code: string,
options?: RequestOptions
): Promise<Cart> =>
- this.request<Cart>('POST', '/cart/coupon_codes', {
+ this.request<Cart>('POST', `/carts/${cartId}/coupon_codes`, {
...options,
body: { code },
}),
/**
* Remove a coupon code from the cart
+ * @param cartId - Cart prefixed ID
* @param code - The coupon code string to remove (e.g., 'SAVE10')
*/
remove: (
+ cartId: string,
code: string,
options?: RequestOptions
): Promise<Cart> =>
this.request<Cart>(
'DELETE',
- `/cart/coupon_codes/${code}`,
+ `/carts/${cartId}/coupon_codes/${code}`,
options
),
},
- };
-
- // ============================================
- // Checkout (cart → order transition)
- // ============================================
-
- readonly checkout = {
- /**
- * Update checkout info (email, addresses, special instructions).
- * When addresses change, the order state is reverted to address
- * to ensure shipments are recalculated.
- */
- update: (
- params: UpdateCheckoutParams,
- options?: RequestOptions
- ): Promise<Cart> =>
- this.request<Cart>('PATCH', '/checkout', {
- ...options,
- body: params,
- }),
-
- /**
- * Complete the checkout and finalize the purchase.
- * Returns an Order (not Cart).
- */
- complete: (options?: RequestOptions): Promise<Order> =>
- this.request<Order>('POST', '/checkout/complete', options),
/**
* Nested resource: Shipments
*/
shipments: {
/**
- * List shipments with shipping rates for the current cart
+ * List shipments with shipping rates for the cart
+ * @param cartId - Cart prefixed ID
*/
- list: (options?: RequestOptions): Promise<ListResponse<Shipment>> =>
+ list: (cartId: string, options?: RequestOptions): Promise<ListResponse<Shipment>> =>
this.request<ListResponse<Shipment>>(
'GET',
- '/checkout/shipments',
+ `/carts/${cartId}/shipments`,
options
),
/**
* Select a shipping rate for a specific shipment.
* Returns the updated cart with recalculated totals.
+ * @param cartId - Cart prefixed ID
*/
update: (
+ cartId: string,
shipmentId: string,
params: { selected_shipping_rate_id: string },
options?: RequestOptions
): Promise<Cart> =>
this.request<Cart>(
'PATCH',
- `/checkout/shipments/${shipmentId}`,
+ `/carts/${cartId}/shipments/${shipmentId}`,
{ ...options, body: params }
),
},
@@ -466,12 +470,13 @@ export class StoreClient {
*/
paymentMethods: {
/**
- * List available payment methods for the current cart
+ * List available payment methods for the cart
+ * @param cartId - Cart prefixed ID
*/
- list: (options?: RequestOptions): Promise<ListResponse<PaymentMethod>> =>
+ list: (cartId: string, options?: RequestOptions): Promise<ListResponse<PaymentMethod>> =>
this.request<ListResponse<PaymentMethod>>(
'GET',
- '/checkout/payment_methods',
+ `/carts/${cartId}/payment_methods`,
options
),
},
@@ -481,39 +486,44 @@ export class StoreClient {
*/
payments: {
/**
- * List payments for the current cart
+ * List payments for the cart
+ * @param cartId - Cart prefixed ID
*/
- list: (options?: RequestOptions): Promise<ListResponse<Payment>> =>
+ list: (cartId: string, options?: RequestOptions): Promise<ListResponse<Payment>> =>
this.request<ListResponse<Payment>>(
'GET',
- '/checkout/payments',
+ `/carts/${cartId}/payments`,
options
),
/**
* Get a payment by ID
+ * @param cartId - Cart prefixed ID
*/
get: (
+ cartId: string,
paymentId: string,
options?: RequestOptions
): Promise<Payment> =>
this.request<Payment>(
'GET',
- `/checkout/payments/${paymentId}`,
+ `/carts/${cartId}/payments/${paymentId}`,
options
),
/**
* Create a payment for a non-session payment method (e.g. Check, Cash on Delivery, Bank Transfer).
- * For session-based payment methods (e.g. Stripe, PayPal), use checkout.paymentSessions.create() instead.
+ * For session-based payment methods (e.g. Stripe, PayPal), use carts.paymentSessions.create() instead.
+ * @param cartId - Cart prefixed ID
*/
create: (
+ cartId: string,
params: CreatePaymentParams,
options?: RequestOptions
): Promise<Payment> =>
this.request<Payment>(
'POST',
- '/checkout/payments',
+ `/carts/${cartId}/payments`,
{ ...options, body: params }
),
},
@@ -523,59 +533,67 @@ export class StoreClient {
*/
paymentSessions: {
/**
- * Create a payment session for the current cart.
+ * Create a payment session for the cart.
* Delegates to the payment gateway to initialize a provider-specific session.
+ * @param cartId - Cart prefixed ID
*/
create: (
+ cartId: string,
params: CreatePaymentSessionParams,
options?: RequestOptions
): Promise<PaymentSession> =>
this.request<PaymentSession>(
'POST',
- '/checkout/payment_sessions',
+ `/carts/${cartId}/payment_sessions`,
{ ...options, body: params }
),
/**
* Get a payment session by ID
+ * @param cartId - Cart prefixed ID
*/
get: (
+ cartId: string,
sessionId: string,
options?: RequestOptions
): Promise<PaymentSession> =>
this.request<PaymentSession>(
'GET',
- `/checkout/payment_sessions/${sessionId}`,
+ `/carts/${cartId}/payment_sessions/${sessionId}`,
options
),
/**
* Update a payment session.
* Delegates to the payment gateway to sync changes with the provider.
+ * @param cartId - Cart prefixed ID
*/
update: (
+ cartId: string,
sessionId: string,
params: UpdatePaymentSessionParams,
options?: RequestOptions
): Promise<PaymentSession> =>
this.request<PaymentSession>(
'PATCH',
- `/checkout/payment_sessions/${sessionId}`,
+ `/carts/${cartId}/payment_sessions/${sessionId}`,
{ ...options, body: params }
),
/**
* Complete a payment session.
* Confirms the payment with the provider, triggering capture/authorization.
+ * @param cartId - Cart prefixed ID
*/
complete: (
+ cartId: string,
sessionId: string,
params?: CompletePaymentSessionParams,
options?: RequestOptions
): Promise<PaymentSession> =>
this.request<PaymentSession>(
'PATCH',
- `/checkout/payment_sessions/${sessionId}/complete`,
+ `/carts/${cartId}/payment_sessions/${sessionId}/complete`,
{ ...options, body: params }
),
},
@@ -585,24 +603,27 @@ export class StoreClient {
*/
storeCredits: {
/**
- * Apply store credit to the current cart
+ * Apply store credit to the cart
+ * @param cartId - Cart prefixed ID
*/
apply: (
+ cartId: string,
amount?: number,
options?: RequestOptions
): Promise<Cart> =>
- this.request<Cart>('POST', '/checkout/store_credits', {
+ this.request<Cart>('POST', `/carts/${cartId}/store_credits`, {
...options,
body: amount ? { amount } : undefined,
}),
/**
- * Remove store credit from the current cart
+ * Remove store credit from the cart
+ * @param cartId - Cart prefixed ID
*/
- remove: (options?: RequestOptions): Promise<Cart> =>
+ remove: (cartId: string, options?: RequestOptions): Promise<Cart> =>
this.request<Cart>(
'DELETE',
- '/checkout/store_credits',
+ `/carts/${cartId}/store_credits`,
options
),
},
diff --git a/packages/sdk/src/types/index.ts b/packages/sdk/src/types/index.ts
index 5db4377abf..8187b4d69b 100644
--- a/packages/sdk/src/types/index.ts
+++ b/packages/sdk/src/types/index.ts
@@ -218,8 +218,8 @@ export interface LineItemInput {
export interface CreateCartParams {
/** Arbitrary key-value metadata (stored, not returned in responses) */
metadata?: Record<string, unknown>;
- /** Line items to add to the cart on creation */
- line_items?: LineItemInput[];
+ /** Items to add to the cart on creation */
+ items?: LineItemInput[];
}
export interface AddLineItemParams {
@@ -235,7 +235,7 @@ export interface UpdateLineItemParams {
metadata?: Record<string, unknown>;
}
-export interface UpdateCheckoutParams {
+export interface UpdateCartParams {
email?: string;
currency?: string;
locale?: string;
@@ -250,8 +250,8 @@ export interface UpdateCheckoutParams {
bill_address?: AddressParams;
/** New shipping address */
ship_address?: AddressParams;
- /** Line items to upsert (sets quantity for existing, creates new) */
- line_items?: LineItemInput[];
+ /** Items to upsert (sets quantity for existing, creates new) */
+ items?: LineItemInput[];
}
// Payments
diff --git a/packages/sdk/tests/cart.test.ts b/packages/sdk/tests/cart.test.ts
index 773a2cacdd..5eddcd81b6 100644
--- a/packages/sdk/tests/cart.test.ts
+++ b/packages/sdk/tests/cart.test.ts
@@ -5,6 +5,7 @@ import type { Client } from '../src';
describe('carts', () => {
let client: Client;
beforeAll(() => { client = createTestClient(); });
+ const opts = { token: 'user-jwt' };
describe('list', () => {
it('lists all active carts for authenticated user', async () => {
@@ -14,16 +15,10 @@ describe('carts', () => {
expect(result.meta.count).toBe(1);
});
});
-});
-
-describe('cart', () => {
- let client: Client;
- beforeAll(() => { client = createTestClient(); });
- const opts = { token: 'user-jwt' };
describe('get', () => {
- it('returns the current cart', async () => {
- const result = await client.cart.get({ token: 'user-jwt' });
+ it('returns a cart by ID', async () => {
+ const result = await client.carts.get('cart_1', opts);
expect(result.id).toBe('cart_1');
expect(result.token).toBeDefined();
@@ -31,28 +26,39 @@ describe('cart', () => {
expect(result.checkout_steps).toBeDefined();
});
- it('works with order token for guest checkout', async () => {
- const result = await client.cart.get({ spreeToken: 'guest-token' });
+ it('works with spreeToken for guest checkout', async () => {
+ const result = await client.carts.get('cart_1', { spreeToken: 'guest-token' });
expect(result).toBeDefined();
});
});
describe('create', () => {
it('creates a new cart', async () => {
- const result = await client.cart.create();
+ const result = await client.carts.create();
expect(result.token).toBe('new-cart-token');
});
});
+ describe('update', () => {
+ it('updates cart info', async () => {
+ const result = await client.carts.update(
+ 'cart_1',
+ { email: '[email protected]' },
+ opts
+ );
+ expect(result.id).toBe('cart_1');
+ });
+ });
+
describe('delete', () => {
- it('deletes the current cart', async () => {
- await expect(client.cart.delete(opts)).resolves.toBeUndefined();
+ it('deletes a cart by ID', async () => {
+ await expect(client.carts.delete('cart_1', opts)).resolves.toBeUndefined();
});
});
describe('associate', () => {
it('associates guest cart with authenticated user', async () => {
- const result = await client.cart.associate({
+ const result = await client.carts.associate('cart_1', {
token: 'user-jwt',
spreeToken: 'guest-token',
});
@@ -60,9 +66,18 @@ describe('cart', () => {
});
});
+ describe('complete', () => {
+ it('completes the cart and returns an order', async () => {
+ const result = await client.carts.complete('cart_1', opts);
+ expect(result.id).toBe('or_1');
+ expect(result.completed_at).toBeDefined();
+ });
+ });
+
describe('items', () => {
it('adds an item to the cart', async () => {
- const result = await client.cart.items.create(
+ const result = await client.carts.items.create(
+ 'cart_1',
{ variant_id: 'var_1', quantity: 2 },
opts
);
@@ -70,7 +85,8 @@ describe('cart', () => {
});
it('updates a line item', async () => {
- const result = await client.cart.items.update(
+ const result = await client.carts.items.update(
+ 'cart_1',
'li_1',
{ quantity: 5 },
opts
@@ -79,19 +95,55 @@ describe('cart', () => {
});
it('removes a line item', async () => {
- const result = await client.cart.items.delete('li_1', opts);
+ const result = await client.carts.items.delete('cart_1', 'li_1', opts);
expect(result.id).toBe('cart_1');
});
});
describe('couponCodes', () => {
it('applies a coupon code', async () => {
- const result = await client.cart.couponCodes.apply('SAVE10', opts);
+ const result = await client.carts.couponCodes.apply('cart_1', 'SAVE10', opts);
expect(result.id).toBe('cart_1');
});
it('removes a coupon code by code string', async () => {
- const result = await client.cart.couponCodes.remove('SAVE10', opts);
+ const result = await client.carts.couponCodes.remove('cart_1', 'SAVE10', opts);
+ expect(result.id).toBe('cart_1');
+ });
+ });
+
+ describe('shipments', () => {
+ it('lists shipments', async () => {
+ const result = await client.carts.shipments.list('cart_1', opts);
+ expect(result.data).toBeDefined();
+ });
+
+ it('selects a shipping rate', async () => {
+ const result = await client.carts.shipments.update(
+ 'cart_1',
+ 'ship_1',
+ { selected_shipping_rate_id: 'rate_1' },
+ opts
+ );
+ expect(result.id).toBe('cart_1');
+ });
+ });
+
+ describe('paymentMethods', () => {
+ it('lists payment methods', async () => {
+ const result = await client.carts.paymentMethods.list('cart_1', opts);
+ expect(result.data).toBeDefined();
+ });
+ });
+
+ describe('storeCredits', () => {
+ it('applies store credit', async () => {
+ const result = await client.carts.storeCredits.apply('cart_1', 10, opts);
+ expect(result.id).toBe('cart_1');
+ });
+
+ it('removes store credit', async () => {
+ const result = await client.carts.storeCredits.remove('cart_1', opts);
expect(result.id).toBe('cart_1');
});
});
diff --git a/packages/sdk/tests/checkout.test.ts b/packages/sdk/tests/checkout.test.ts
deleted file mode 100644
index 8f6473724f..0000000000
--- a/packages/sdk/tests/checkout.test.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { describe, it, expect, beforeAll } from 'vitest';
-import { createTestClient } from './helpers';
-import type { Client } from '../src';
-
-describe('checkout', () => {
- let client: Client;
- beforeAll(() => { client = createTestClient(); });
- const opts = { token: 'user-jwt' };
-
- describe('update', () => {
- it('updates checkout info', async () => {
- const result = await client.checkout.update(
- { email: '[email protected]' },
- opts
- );
- expect(result.id).toBe('cart_1');
- });
- });
-
- describe('complete', () => {
- it('completes the checkout and returns an order', async () => {
- const result = await client.checkout.complete(opts);
- expect(result.id).toBe('or_1');
- expect(result.completed_at).toBeDefined();
- });
- });
-
- describe('shipments', () => {
- it('lists shipments', async () => {
- const result = await client.checkout.shipments.list(opts);
- expect(result.data).toBeDefined();
- });
-
- it('selects a shipping rate', async () => {
- const result = await client.checkout.shipments.update(
- 'ship_1',
- { selected_shipping_rate_id: 'rate_1' },
- opts
- );
- expect(result.id).toBe('cart_1');
- });
- });
-
- describe('paymentMethods', () => {
- it('lists payment methods', async () => {
- const result = await client.checkout.paymentMethods.list(opts);
- expect(result.data).toBeDefined();
- });
- });
-
- describe('storeCredits', () => {
- it('applies store credit', async () => {
- const result = await client.checkout.storeCredits.apply(10, opts);
- expect(result.id).toBe('cart_1');
- });
-
- it('removes store credit', async () => {
- const result = await client.checkout.storeCredits.remove(opts);
- expect(result.id).toBe('cart_1');
- });
- });
-});
diff --git a/packages/sdk/tests/client.test.ts b/packages/sdk/tests/client.test.ts
index 21c2bb118a..07b19f8f8c 100644
--- a/packages/sdk/tests/client.test.ts
+++ b/packages/sdk/tests/client.test.ts
@@ -120,7 +120,7 @@ describe('createClient', () => {
expect(client.countries).toBeDefined();
expect(client.currencies).toBeDefined();
expect(client.locales).toBeDefined();
- expect(client.cart).toBeDefined();
+ expect(client.carts).toBeDefined();
expect(client.orders).toBeDefined();
expect(client.customer).toBeDefined();
expect(client.wishlists).toBeDefined();
diff --git a/packages/sdk/tests/error-handling.test.ts b/packages/sdk/tests/error-handling.test.ts
index 2414985aa1..cac0bb58a9 100644
--- a/packages/sdk/tests/error-handling.test.ts
+++ b/packages/sdk/tests/error-handling.test.ts
@@ -124,7 +124,7 @@ describe('error handling', () => {
it('handles 204 No Content responses', async () => {
const client = createTestClient();
- const result = await client.cart.delete({ token: 'jwt' });
+ const result = await client.carts.delete('cart_1', { token: 'jwt' });
expect(result).toBeUndefined();
});
});
diff --git a/packages/sdk/tests/mocks/handlers.ts b/packages/sdk/tests/mocks/handlers.ts
index fd8ead4996..0a3ce5e2b2 100644
--- a/packages/sdk/tests/mocks/handlers.ts
+++ b/packages/sdk/tests/mocks/handlers.ts
@@ -23,7 +23,7 @@ export const fixtures = {
token: 'guest-order-token',
checkout_steps: ['address', 'delivery', 'payment', 'confirm'],
state_lock_version: 0,
- line_items: [],
+ items: [],
payment_methods: [],
},
order: {
@@ -35,7 +35,7 @@ export const fixtures = {
completed_at: '2026-03-01T00:00:00.000Z',
shipment_state: 'shipped',
payment_state: 'paid',
- line_items: [],
+ items: [],
},
lineItem: {
id: 'li_1',
@@ -196,75 +196,73 @@ export const handlers = [
HttpResponse.json(fixtures.market)
),
- // Carts (list)
+ // Carts
http.get(`${API_PREFIX}/carts`, () =>
- HttpResponse.json({ data: [fixtures.cart], meta: { count: 1 } })
+ HttpResponse.json({ data: [fixtures.cart], meta: { page: 1, limit: 25, count: 1, pages: 1, from: 1, to: 1, in: 1, previous: null, next: null } })
),
- // Cart
- http.get(`${API_PREFIX}/cart`, () =>
+ http.post(`${API_PREFIX}/carts`, () =>
+ HttpResponse.json({ ...fixtures.cart, token: 'new-cart-token' })
+ ),
+
+ http.get(`${API_PREFIX}/carts/:cartId`, () =>
HttpResponse.json(fixtures.cart)
),
- http.post(`${API_PREFIX}/cart`, () =>
- HttpResponse.json({ ...fixtures.cart, token: 'new-cart-token' })
+ http.patch(`${API_PREFIX}/carts/:cartId`, () =>
+ HttpResponse.json(fixtures.cart)
),
- http.delete(`${API_PREFIX}/cart`, () =>
+ http.delete(`${API_PREFIX}/carts/:cartId`, () =>
new HttpResponse(null, { status: 204 })
),
- http.patch(`${API_PREFIX}/cart/associate`, () =>
+ http.patch(`${API_PREFIX}/carts/:cartId/associate`, () =>
HttpResponse.json(fixtures.cart)
),
- // Cart > Items
- http.post(`${API_PREFIX}/cart/items`, () =>
- HttpResponse.json(fixtures.cart)
+ http.post(`${API_PREFIX}/carts/:cartId/complete`, () =>
+ HttpResponse.json(fixtures.order)
),
- http.patch(`${API_PREFIX}/cart/items/:id`, () =>
+ // Carts > Items
+ http.post(`${API_PREFIX}/carts/:cartId/items`, () =>
HttpResponse.json(fixtures.cart)
),
- http.delete(`${API_PREFIX}/cart/items/:id`, () =>
+ http.patch(`${API_PREFIX}/carts/:cartId/items/:id`, () =>
HttpResponse.json(fixtures.cart)
),
- // Cart > Coupon Codes
- http.post(`${API_PREFIX}/cart/coupon_codes`, () =>
+ http.delete(`${API_PREFIX}/carts/:cartId/items/:id`, () =>
HttpResponse.json(fixtures.cart)
),
- http.delete(`${API_PREFIX}/cart/coupon_codes/:code`, () =>
+ // Carts > Coupon Codes
+ http.post(`${API_PREFIX}/carts/:cartId/coupon_codes`, () =>
HttpResponse.json(fixtures.cart)
),
- // Checkout
- http.patch(`${API_PREFIX}/checkout`, () =>
+ http.delete(`${API_PREFIX}/carts/:cartId/coupon_codes/:code`, () =>
HttpResponse.json(fixtures.cart)
),
- http.post(`${API_PREFIX}/checkout/complete`, () =>
- HttpResponse.json(fixtures.order)
- ),
-
- // Checkout > Shipments
- http.get(`${API_PREFIX}/checkout/shipments`, () =>
+ // Carts > Shipments
+ http.get(`${API_PREFIX}/carts/:cartId/shipments`, () =>
HttpResponse.json({ data: [], meta: { count: 0 } })
),
- http.patch(`${API_PREFIX}/checkout/shipments/:id`, () =>
+ http.patch(`${API_PREFIX}/carts/:cartId/shipments/:id`, () =>
HttpResponse.json(fixtures.cart)
),
- // Checkout > Payment Methods
- http.get(`${API_PREFIX}/checkout/payment_methods`, () =>
+ // Carts > Payment Methods
+ http.get(`${API_PREFIX}/carts/:cartId/payment_methods`, () =>
HttpResponse.json({ data: [], meta: { count: 0 } })
),
- // Checkout > Payments
- http.get(`${API_PREFIX}/checkout/payments`, () =>
+ // Carts > Payments
+ http.get(`${API_PREFIX}/carts/:cartId/payments`, () =>
HttpResponse.json({
data: [{
id: 'py_1',
@@ -285,7 +283,7 @@ export const handlers = [
})
),
- http.get(`${API_PREFIX}/checkout/payments/:id`, () =>
+ http.get(`${API_PREFIX}/carts/:cartId/payments/:id`, () =>
HttpResponse.json({
id: 'py_1',
payment_method_id: 'pm_1',
@@ -303,7 +301,7 @@ export const handlers = [
})
),
- http.post(`${API_PREFIX}/checkout/payments`, () =>
+ http.post(`${API_PREFIX}/carts/:cartId/payments`, () =>
HttpResponse.json({
id: 'py_2',
payment_method_id: 'pm_2',
@@ -321,8 +319,8 @@ export const handlers = [
}, { status: 201 })
),
- // Checkout > Payment Sessions
- http.post(`${API_PREFIX}/checkout/payment_sessions`, () =>
+ // Carts > Payment Sessions
+ http.post(`${API_PREFIX}/carts/:cartId/payment_sessions`, () =>
HttpResponse.json({
id: 'ps_1',
status: 'pending',
@@ -340,7 +338,7 @@ export const handlers = [
}, { status: 201 })
),
- http.get(`${API_PREFIX}/checkout/payment_sessions/:id`, () =>
+ http.get(`${API_PREFIX}/carts/:cartId/payment_sessions/:id`, () =>
HttpResponse.json({
id: 'ps_1',
status: 'pending',
@@ -358,7 +356,7 @@ export const handlers = [
})
),
- http.patch(`${API_PREFIX}/checkout/payment_sessions/:id/complete`, () =>
+ http.patch(`${API_PREFIX}/carts/:cartId/payment_sessions/:id/complete`, () =>
HttpResponse.json({
id: 'ps_1',
status: 'completed',
@@ -376,7 +374,7 @@ export const handlers = [
})
),
- http.patch(`${API_PREFIX}/checkout/payment_sessions/:id`, () =>
+ http.patch(`${API_PREFIX}/carts/:cartId/payment_sessions/:id`, () =>
HttpResponse.json({
id: 'ps_1',
status: 'pending',
@@ -394,12 +392,12 @@ export const handlers = [
})
),
- // Checkout > Store Credits
- http.post(`${API_PREFIX}/checkout/store_credits`, () =>
+ // Carts > Store Credits
+ http.post(`${API_PREFIX}/carts/:cartId/store_credits`, () =>
HttpResponse.json(fixtures.cart)
),
- http.delete(`${API_PREFIX}/checkout/store_credits`, () =>
+ http.delete(`${API_PREFIX}/carts/:cartId/store_credits`, () =>
HttpResponse.json(fixtures.cart)
),
diff --git a/packages/sdk/tests/payment-sessions.test.ts b/packages/sdk/tests/payment-sessions.test.ts
index 4facbae71d..7e43cef9e8 100644
--- a/packages/sdk/tests/payment-sessions.test.ts
+++ b/packages/sdk/tests/payment-sessions.test.ts
@@ -9,7 +9,8 @@ describe('paymentSessions', () => {
describe('create', () => {
it('creates a payment session', async () => {
- const result = await client.checkout.paymentSessions.create(
+ const result = await client.carts.paymentSessions.create(
+ 'cart_1',
{ payment_method_id: 'pm_1' },
opts
);
@@ -21,7 +22,8 @@ describe('paymentSessions', () => {
});
it('accepts optional amount and external_data', async () => {
- const result = await client.checkout.paymentSessions.create(
+ const result = await client.carts.paymentSessions.create(
+ 'cart_1',
{ payment_method_id: 'pm_1', amount: '50.00', external_data: { channel: 'Web' } },
opts
);
@@ -31,7 +33,7 @@ describe('paymentSessions', () => {
describe('get', () => {
it('returns a payment session by ID', async () => {
- const result = await client.checkout.paymentSessions.get('ps_1', opts);
+ const result = await client.carts.paymentSessions.get('cart_1', 'ps_1', opts);
expect(result.id).toBe('ps_1');
expect(result.status).toBe('pending');
expect(result.amount).toBe('99.99');
@@ -42,7 +44,8 @@ describe('paymentSessions', () => {
describe('update', () => {
it('updates a payment session', async () => {
- const result = await client.checkout.paymentSessions.update(
+ const result = await client.carts.paymentSessions.update(
+ 'cart_1',
'ps_1',
{ amount: '50.00' },
opts
@@ -54,7 +57,8 @@ describe('paymentSessions', () => {
describe('complete', () => {
it('completes a payment session', async () => {
- const result = await client.checkout.paymentSessions.complete(
+ const result = await client.carts.paymentSessions.complete(
+ 'cart_1',
'ps_1',
{ session_result: 'success' },
opts
@@ -64,7 +68,8 @@ describe('paymentSessions', () => {
});
it('completes without params', async () => {
- const result = await client.checkout.paymentSessions.complete(
+ const result = await client.carts.paymentSessions.complete(
+ 'cart_1',
'ps_1',
undefined,
opts
diff --git a/packages/sdk/tests/payments.test.ts b/packages/sdk/tests/payments.test.ts
index 9ffdccb46e..4e69c98b88 100644
--- a/packages/sdk/tests/payments.test.ts
+++ b/packages/sdk/tests/payments.test.ts
@@ -8,8 +8,8 @@ describe('payments', () => {
const opts = { token: 'user-jwt' };
describe('list', () => {
- it('returns payments for the current cart', async () => {
- const result = await client.checkout.payments.list(opts);
+ it('returns payments for the cart', async () => {
+ const result = await client.carts.payments.list('cart_1', opts);
expect(result.data).toHaveLength(1);
expect(result.data[0].id).toBe('py_1');
expect(result.data[0].state).toBe('checkout');
@@ -17,7 +17,7 @@ describe('payments', () => {
});
it('includes source_type, source_id, and source for credit card payments', async () => {
- const result = await client.checkout.payments.list(opts);
+ const result = await client.carts.payments.list('cart_1', opts);
const payment = result.data[0];
expect(payment.source_type).toBe('credit_card');
expect(payment.source_id).toBe('card_1');
@@ -31,7 +31,7 @@ describe('payments', () => {
});
it('includes payment_method association', async () => {
- const result = await client.checkout.payments.list(opts);
+ const result = await client.carts.payments.list('cart_1', opts);
expect(result.data[0].payment_method.id).toBe('pm_1');
expect(result.data[0].payment_method.name).toBe('Credit Card');
});
@@ -39,7 +39,7 @@ describe('payments', () => {
describe('get', () => {
it('returns a payment by ID', async () => {
- const result = await client.checkout.payments.get('py_1', opts);
+ const result = await client.carts.payments.get('cart_1', 'py_1', opts);
expect(result.id).toBe('py_1');
expect(result.state).toBe('checkout');
expect(result.number).toBe('P1234');
@@ -47,7 +47,7 @@ describe('payments', () => {
});
it('includes source details', async () => {
- const result = await client.checkout.payments.get('py_1', opts);
+ const result = await client.carts.payments.get('cart_1', 'py_1', opts);
expect(result.source_type).toBe('credit_card');
expect(result.source_id).toBe('card_1');
expect(result.source).toBeDefined();
@@ -57,7 +57,8 @@ describe('payments', () => {
describe('create', () => {
it('creates a payment for a non-session payment method', async () => {
- const result = await client.checkout.payments.create(
+ const result = await client.carts.payments.create(
+ 'cart_1',
{ payment_method_id: 'pm_2' },
opts
);
@@ -69,7 +70,8 @@ describe('payments', () => {
});
it('accepts optional amount', async () => {
- const result = await client.checkout.payments.create(
+ const result = await client.carts.payments.create(
+ 'cart_1',
{ payment_method_id: 'pm_2', amount: '50.00' },
opts
);
@@ -77,7 +79,8 @@ describe('payments', () => {
});
it('includes payment_method association', async () => {
- const result = await client.checkout.payments.create(
+ const result = await client.carts.payments.create(
+ 'cart_1',
{ payment_method_id: 'pm_2' },
opts
);
diff --git a/packages/sdk/tests/retry.test.ts b/packages/sdk/tests/retry.test.ts
index 7d120030a4..81c261f173 100644
--- a/packages/sdk/tests/retry.test.ts
+++ b/packages/sdk/tests/retry.test.ts
@@ -190,7 +190,7 @@ describe('Retry logic', () => {
.mockResolvedValueOnce(jsonResponse({ number: 'R123', token: 'cart-token' }));
const client = createClient({ ...baseConfig, fetch: mockFetch });
- await client.cart.create(undefined, { idempotencyKey: 'my-custom-key' });
+ await client.carts.create(undefined, { idempotencyKey: 'my-custom-key' });
const headers = mockFetch.mock.calls[0][1].headers;
expect(headers['Idempotency-Key']).toBe('my-custom-key');
diff --git a/spree/api/README.md b/spree/api/README.md
index d8dd3394e9..4224d4d903 100644
--- a/spree/api/README.md
+++ b/spree/api/README.md
@@ -82,10 +82,10 @@ curl -H "Authorization: Bearer spree_sk_xxx" \
### Guest Cart Token
-For guest checkout, use the `X-Spree-Order-Token` header:
+For guest checkout, use the `X-Spree-Token` header:
```bash
-curl -H "X-Spree-Order-Token: ORDER_TOKEN" \
+curl -H "X-Spree-Token: ORDER_TOKEN" \
https://your-store.com/api/v3/cart
```
@@ -134,4 +134,4 @@ bundle exec rspec
## Documentation
- [API Reference](https://docs.spreecommerce.org/api)
-- [Authentication Guide](https://docs.spreecommerce.org/developer/api/authentication)
\ No newline at end of file
+- [Authentication Guide](https://docs.spreecommerce.org/developer/api/authentication)
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rb b/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rb
index 28c897bb69..4d2f98c2b5 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rb
@@ -6,27 +6,20 @@ module Spree
protected
+ # Find cart by prefixed ID and authorize access via CanCanCan.
+ # @return [Spree::Order]
def find_cart
- scope = current_store.carts
-
- # Try order_token first (guest checkout)
- if cart_token.present?
- return scope.find_by!(token: cart_token)
- end
-
- # Then try JWT authenticated user
- if current_user.present?
- cart = scope.where(user: current_user).order(created_at: :desc).first
- return cart if cart
- end
-
- raise ActiveRecord::RecordNotFound.new(nil, 'Spree::Order')
+ cart_id = params[:cart_id] || params[:id]
+ @cart = current_store.carts.find_by_prefix_id!(cart_id)
+ authorize!(:show, @cart, cart_token)
+ @cart
end
- # Find the cart and authorize it for update using the cart token from the request headers.
+ # Find the cart and authorize it for update.
# @return [Spree::Order]
def find_cart!
- @cart = find_cart
+ cart_id = params[:cart_id] || params[:id]
+ @cart = current_store.carts.find_by_prefix_id!(cart_id)
authorize!(:update, @cart, cart_token)
@cart
end
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb b/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb
index ad8098a594..d4c54ae31f 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb
@@ -18,13 +18,16 @@ module Spree
record_not_found: 'record_not_found',
resource_invalid: 'resource_invalid',
+ # Cart errors
+ cart_not_found: 'cart_not_found',
+ cart_already_completed: 'cart_already_completed',
+ cart_cannot_transition: 'cart_cannot_transition',
+ cart_empty: 'cart_empty',
+ cart_invalid_state: 'cart_invalid_state',
+ cart_already_updated: 'cart_already_updated',
+
# Order errors
order_not_found: 'order_not_found',
- order_already_completed: 'order_already_completed',
- order_cannot_transition: 'order_cannot_transition',
- order_empty: 'order_empty',
- order_invalid_state: 'order_invalid_state',
- order_already_updated: 'order_already_updated',
# Line item errors
line_item_not_found: 'line_item_not_found',
@@ -191,7 +194,7 @@ module Spree
def handle_invalid_transition(exception)
Rails.error.report(exception, context: error_context, source: 'spree.api.v3')
render_error(
- code: ERROR_CODES[:order_cannot_transition],
+ code: ERROR_CODES[:cart_cannot_transition],
message: exception.message,
status: :unprocessable_content
)
@@ -229,7 +232,7 @@ module Spree
case model_name
when 'order'
- ERROR_CODES[:order_not_found]
+ request.path.include?('/carts') ? ERROR_CODES[:cart_not_found] : ERROR_CODES[:order_not_found]
when 'line_item'
ERROR_CODES[:line_item_not_found]
when 'variant'
@@ -240,15 +243,17 @@ module Spree
end
# Generate human-readable not found message
- # Uses the exception's own message when it contains useful context (e.g. prefixed ID),
- # otherwise falls back to a generic "[Model] not found" translation.
def generate_not_found_message(exception)
- if exception.id.present?
- exception.message
- else
- model_name = extract_model_name(exception)
- Spree.t(:record_not_found, scope: 'api', model: model_name&.humanize || 'record')
- end
+ model_name = extract_model_name(exception)
+
+ # Use "Cart" for order models in cart context
+ label = if model_name == 'order' && request.path.include?('/carts')
+ 'Cart'
+ else
+ model_name&.humanize || 'record'
+ end
+
+ Spree.t(:record_not_found, scope: 'api', model: label)
end
# Extract clean model name from exception
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/order_lock.rb b/spree/api/app/controllers/concerns/spree/api/v3/order_lock.rb
index 9f845b33a8..87d36b2e9b 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/order_lock.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/order_lock.rb
@@ -29,10 +29,10 @@ module Spree
end
def handle_order_lock_conflict(exception)
- Rails.error.report(exception, context: { order_id: (@order || @parent)&.id }, source: 'spree.api.v3')
+ Rails.error.report(exception, context: { order_id: (@order || @parent || @cart)&.id }, source: 'spree.api.v3')
render_error(
- code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:order_already_updated],
- message: Spree.t(:order_already_updated),
+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:cart_already_updated],
+ message: Spree.t(:cart_already_updated),
status: :conflict
)
end
diff --git a/spree/api/app/controllers/spree/api/v3/store/cart_controller.rb b/spree/api/app/controllers/spree/api/v3/store/cart_controller.rb
deleted file mode 100644
index d8e3038940..0000000000
--- a/spree/api/app/controllers/spree/api/v3/store/cart_controller.rb
+++ /dev/null
@@ -1,98 +0,0 @@
-module Spree
- module Api
- module V3
- module Store
- class CartController < Store::BaseController
- include Spree::Api::V3::CartResolvable
- include Spree::Api::V3::OrderLock
-
- before_action :require_authentication!, only: [:associate]
-
- # POST /api/v3/store/cart
- # Creates a new shopping cart (order)
- # Can be created by guests or authenticated customers
- def create
- result = Spree.cart_create_service.call(
- user: current_user,
- store: current_store,
- currency: current_currency,
- locale: current_locale,
- metadata: cart_params[:metadata] || {},
- line_items: cart_params[:line_items] || []
- )
-
- if result.success?
- @cart = result.value
- render_cart(status: :created)
- else
- render_service_error(result.error.to_s)
- end
- end
-
- # GET /api/v3/store/cart
- # Returns current incomplete order (cart)
- # Returns 404 if no cart exists - use POST /cart to create one
- # Authorize via cart_token param or JWT Bearer token
- # Uses find_cart (without bang) intentionally — read-only access, no authorize! needed
- #
- # Auto-advances the checkout state machine so that shipments and
- # payment requirements are up-to-date (temporary until Spree 6 removes
- # the state machine).
- def show
- @cart = find_cart
-
- if @cart && @cart.ship_address_id.present? && @cart.shipments.empty?
- with_order_lock { Spree::Checkout::Advance.call(order: @cart) }
- end
-
- render_cart
- end
-
- # DELETE /api/v3/store/cart
- # Deletes/abandons the current cart
- def destroy
- find_cart!
-
- result = Spree.cart_destroy_service.call(order: @cart)
-
- if result.success?
- head :no_content
- else
- render_service_error(result.error.to_s)
- end
- end
-
- # PATCH /api/v3/store/cart/associate
- # Associates a guest cart with the currently authenticated user
- # Requires: JWT authentication + order token (header or param)
- def associate
- @cart = find_cart_by_token
-
- result = Spree.cart_associate_service.call(guest_order: @cart, user: current_user, guest_only: true)
-
- if result.success?
- render_cart
- else
- render_service_error(result.error.to_s)
- end
- end
-
- private
-
- def cart_params
- params.permit(
- metadata: {},
- line_items: [:variant_id, :quantity, { metadata: {}, options: {} }]
- )
- end
-
- # Find incomplete cart by order token for associate action
- # Only finds guest carts (no user) or carts already owned by current user (idempotent)
- def find_cart_by_token
- current_store.carts.where(user: [nil, current_user]).find_by!(token: cart_token)
- end
- end
- end
- end
- end
-end
diff --git a/spree/api/app/controllers/spree/api/v3/store/cart/coupon_codes_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts/coupon_codes_controller.rb
similarity index 90%
rename from spree/api/app/controllers/spree/api/v3/store/cart/coupon_codes_controller.rb
rename to spree/api/app/controllers/spree/api/v3/store/carts/coupon_codes_controller.rb
index 5d4910a983..f25b85daae 100644
--- a/spree/api/app/controllers/spree/api/v3/store/cart/coupon_codes_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/carts/coupon_codes_controller.rb
@@ -2,14 +2,14 @@ module Spree
module Api
module V3
module Store
- module Cart
+ module Carts
class CouponCodesController < Store::BaseController
include Spree::Api::V3::CartResolvable
include Spree::Api::V3::OrderLock
before_action :find_cart!
- # POST /api/v3/store/cart/coupon_codes
+ # POST /api/v3/store/carts/:cart_id/coupon_codes
# Apply a coupon code to the cart
def create
with_order_lock do
@@ -25,7 +25,7 @@ module Spree
end
end
- # DELETE /api/v3/store/cart/coupon_codes/:id
+ # DELETE /api/v3/store/carts/:cart_id/coupon_codes/:id
# Remove a coupon code from the cart
# :id is the coupon code string (e.g., SAVE10)
def destroy
diff --git a/spree/api/app/controllers/spree/api/v3/store/cart/items_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rb
similarity index 92%
rename from spree/api/app/controllers/spree/api/v3/store/cart/items_controller.rb
rename to spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rb
index f21fde8622..01f85941e7 100644
--- a/spree/api/app/controllers/spree/api/v3/store/cart/items_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rb
@@ -2,14 +2,14 @@ module Spree
module Api
module V3
module Store
- module Cart
+ module Carts
class ItemsController < Store::BaseController
include Spree::Api::V3::CartResolvable
include Spree::Api::V3::OrderLock
before_action :find_cart!
- # POST /api/v3/store/cart/items
+ # POST /api/v3/store/carts/:cart_id/items
def create
with_order_lock do
result = Spree.cart_add_item_service.call(
@@ -28,7 +28,7 @@ module Spree
end
end
- # PATCH /api/v3/store/cart/items/:id
+ # PATCH /api/v3/store/carts/:cart_id/items/:id
def update
with_order_lock do
@line_item = @cart.line_items.find_by_prefix_id!(params[:id])
@@ -56,7 +56,7 @@ module Spree
end
end
- # DELETE /api/v3/store/cart/items/:id
+ # DELETE /api/v3/store/carts/:cart_id/items/:id
def destroy
with_order_lock do
@line_item = @cart.line_items.find_by_prefix_id!(params[:id])
@@ -72,7 +72,6 @@ module Spree
private
-
def variant
@variant ||= current_store.variants.accessible_by(current_ability).find_by_prefix_id!(permitted_params[:variant_id])
end
diff --git a/spree/api/app/controllers/spree/api/v3/store/checkout/payment_methods_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts/payment_methods_controller.rb
similarity index 87%
rename from spree/api/app/controllers/spree/api/v3/store/checkout/payment_methods_controller.rb
rename to spree/api/app/controllers/spree/api/v3/store/carts/payment_methods_controller.rb
index 027b56dfbf..879401b1da 100644
--- a/spree/api/app/controllers/spree/api/v3/store/checkout/payment_methods_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/carts/payment_methods_controller.rb
@@ -2,13 +2,13 @@ module Spree
module Api
module V3
module Store
- module Checkout
+ module Carts
class PaymentMethodsController < Store::BaseController
include Spree::Api::V3::CartResolvable
before_action :find_cart!
- # GET /api/v3/store/checkout/payment_methods
+ # GET /api/v3/store/carts/:cart_id/payment_methods
def index
methods = @cart.collect_frontend_payment_methods
render json: {
diff --git a/spree/api/app/controllers/spree/api/v3/store/checkout/payment_sessions_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts/payment_sessions_controller.rb
similarity index 89%
rename from spree/api/app/controllers/spree/api/v3/store/checkout/payment_sessions_controller.rb
rename to spree/api/app/controllers/spree/api/v3/store/carts/payment_sessions_controller.rb
index 22fac81106..5950bdb504 100644
--- a/spree/api/app/controllers/spree/api/v3/store/checkout/payment_sessions_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/carts/payment_sessions_controller.rb
@@ -2,14 +2,14 @@ module Spree
module Api
module V3
module Store
- module Checkout
+ module Carts
class PaymentSessionsController < Store::BaseController
include Spree::Api::V3::CartResolvable
before_action :find_cart!
before_action :set_payment_session, only: [:show, :update, :complete]
- # POST /api/v3/store/checkout/payment_sessions
+ # POST /api/v3/store/carts/:cart_id/payment_sessions
def create
payment_method = current_store.payment_methods.find_by_prefix_id!(permitted_params[:payment_method_id])
@@ -26,12 +26,12 @@ module Spree
end
end
- # GET /api/v3/store/checkout/payment_sessions/:id
+ # GET /api/v3/store/carts/:cart_id/payment_sessions/:id
def show
render json: serialize_resource(@payment_session)
end
- # PATCH /api/v3/store/checkout/payment_sessions/:id
+ # PATCH /api/v3/store/carts/:cart_id/payment_sessions/:id
def update
@payment_session.payment_method.update_payment_session(
payment_session: @payment_session,
@@ -46,7 +46,7 @@ module Spree
end
end
- # PATCH /api/v3/store/checkout/payment_sessions/:id/complete
+ # PATCH /api/v3/store/carts/:cart_id/payment_sessions/:id/complete
def complete
@payment_session.payment_method.complete_payment_session(
payment_session: @payment_session,
diff --git a/spree/api/app/controllers/spree/api/v3/store/checkout/payments_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts/payments_controller.rb
similarity index 96%
rename from spree/api/app/controllers/spree/api/v3/store/checkout/payments_controller.rb
rename to spree/api/app/controllers/spree/api/v3/store/carts/payments_controller.rb
index 930de60360..9f02a367b0 100644
--- a/spree/api/app/controllers/spree/api/v3/store/checkout/payments_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/carts/payments_controller.rb
@@ -2,11 +2,11 @@ module Spree
module Api
module V3
module Store
- module Checkout
+ module Carts
class PaymentsController < Store::ResourceController
include Spree::Api::V3::CartResolvable
- # POST /api/v3/store/checkout/payments
+ # POST /api/v3/store/carts/:cart_id/payments
# Creates a payment for non-session payment methods (e.g. Check, Cash on Delivery, Bank Transfer)
def create
payment_method = current_store.payment_methods.find_by_prefix_id!(params[:payment_method_id])
diff --git a/spree/api/app/controllers/spree/api/v3/store/checkout/shipments_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts/shipments_controller.rb
similarity index 93%
rename from spree/api/app/controllers/spree/api/v3/store/checkout/shipments_controller.rb
rename to spree/api/app/controllers/spree/api/v3/store/carts/shipments_controller.rb
index 22c0273f16..8665f3da7d 100644
--- a/spree/api/app/controllers/spree/api/v3/store/checkout/shipments_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/carts/shipments_controller.rb
@@ -2,14 +2,14 @@ module Spree
module Api
module V3
module Store
- module Checkout
+ module Carts
class ShipmentsController < Store::BaseController
include Spree::Api::V3::CartResolvable
include Spree::Api::V3::OrderLock
before_action :find_cart!
- # GET /api/v3/store/checkout/shipments
+ # GET /api/v3/store/carts/:cart_id/shipments
def index
shipments = @cart.shipments.includes(shipping_rates: :shipping_method)
render json: {
@@ -18,7 +18,7 @@ module Spree
}
end
- # PATCH /api/v3/store/checkout/shipments/:id
+ # PATCH /api/v3/store/carts/:cart_id/shipments/:id
# Select a shipping rate for a specific shipment
def update
with_order_lock do
diff --git a/spree/api/app/controllers/spree/api/v3/store/checkout/store_credits_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts/store_credits_controller.rb
similarity index 88%
rename from spree/api/app/controllers/spree/api/v3/store/checkout/store_credits_controller.rb
rename to spree/api/app/controllers/spree/api/v3/store/carts/store_credits_controller.rb
index 8be8ae001d..9b0b6d27f1 100644
--- a/spree/api/app/controllers/spree/api/v3/store/checkout/store_credits_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/carts/store_credits_controller.rb
@@ -2,7 +2,7 @@ module Spree
module Api
module V3
module Store
- module Checkout
+ module Carts
class StoreCreditsController < Store::BaseController
include Spree::Api::V3::CartResolvable
include Spree::Api::V3::OrderLock
@@ -10,7 +10,7 @@ module Spree
before_action :require_authentication!
before_action :find_cart!
- # POST /api/v3/store/checkout/store_credits
+ # POST /api/v3/store/carts/:cart_id/store_credits
def create
with_order_lock do
result = Spree.checkout_add_store_credit_service.call(
@@ -26,7 +26,7 @@ module Spree
end
end
- # DELETE /api/v3/store/checkout/store_credits
+ # DELETE /api/v3/store/carts/:cart_id/store_credits
def destroy
with_order_lock do
result = Spree.checkout_remove_store_credit_service.call(order: @cart)
diff --git a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb
index 5fa704af52..98d01ac521 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
@@ -3,18 +3,117 @@ module Spree
module V3
module Store
class CartsController < Store::ResourceController
- prepend_before_action :require_authentication!
+ include Spree::Api::V3::CartResolvable
+ include Spree::Api::V3::OrderLock
- protected
+ skip_before_action :set_resource
+ prepend_before_action :require_authentication!, only: [:index, :associate]
+
+ # GET /api/v3/store/carts/:id
+ # Returns cart by prefixed ID
+ # Auto-advances the checkout state machine so that shipments and
+ # payment requirements are up-to-date (temporary until Spree 6 removes
+ # the state machine).
+ def show
+ @cart = find_cart
+
+ if @cart.ship_address_id.present? && @cart.shipments.empty?
+ ActiveRecord::Base.connected_to(role: :writing) do
+ with_order_lock { Spree::Checkout::Advance.call(order: @cart) }
+ end
+ end
+
+ render_cart
+ end
+
+ # POST /api/v3/store/carts
+ # Creates a new shopping cart (order)
+ # Can be created by guests or authenticated customers
+ def create
+ result = Spree::Carts::Create.call(
+ params: permitted_params.merge(
+ user: current_user,
+ store: current_store,
+ currency: current_currency,
+ locale: current_locale
+ )
+ )
+
+ if result.success?
+ @cart = result.value
+ render_cart(status: :created)
+ else
+ render_service_error(result.error.to_s)
+ end
+ end
- def set_parent
- @parent = current_user
+ # PATCH /api/v3/store/carts/:id
+ # Updates cart info (email, addresses, special instructions).
+ # Auto-advances to the next checkout step when possible.
+ def update
+ find_cart!
+
+ with_order_lock do
+ result = Spree::Carts::Update.call(
+ cart: @cart,
+ params: permitted_params
+ )
+
+ if result.success?
+ render_cart
+ else
+ render_service_error(result.error, code: ERROR_CODES[:validation_error])
+ end
+ end
+ end
+
+ # DELETE /api/v3/store/carts/:id
+ # Deletes/abandons the cart
+ def destroy
+ find_cart!
+
+ result = Spree.cart_destroy_service.call(order: @cart)
+
+ if result.success?
+ head :no_content
+ else
+ render_service_error(result.error.to_s)
+ end
end
- def parent_association
- :carts
+ # PATCH /api/v3/store/carts/:id/associate
+ # Associates a guest cart with the currently authenticated user
+ # Requires: JWT authentication + cart ID in URL
+ def associate
+ @cart = find_cart_for_association
+
+ result = Spree.cart_associate_service.call(guest_order: @cart, user: current_user, guest_only: true)
+
+ if result.success?
+ render_cart
+ else
+ render_service_error(result.error.to_s)
+ end
end
+ # POST /api/v3/store/carts/:id/complete
+ # Completes the checkout — returns Order (not Cart)
+ def complete
+ find_cart!
+
+ with_order_lock do
+ result = Spree.checkout_complete_service.call(order: @cart)
+
+ if result.success?
+ render_order
+ else
+ render_service_error(result.error, code: ERROR_CODES[:cart_already_completed])
+ end
+ end
+ end
+
+ protected
+
def model_class
Spree::Order
end
@@ -23,8 +122,43 @@ module Spree
Spree.api.cart_serializer
end
- def apply_collection_sort(collection)
- collection.order(updated_at: :desc)
+ def scope
+ current_store.carts.where(user: current_user).order(updated_at: :desc)
+ end
+
+ private
+
+ def permitted_params
+ params.permit(
+ :email,
+ :special_instructions,
+ :currency,
+ :locale,
+ :ship_address_id,
+ :bill_address_id,
+ ship_address: address_params,
+ bill_address: address_params,
+ metadata: {},
+ items: item_params
+ )
+ end
+
+ def address_params
+ [
+ :id, :firstname, :lastname, :address1, :address2,
+ :city, :zipcode, :phone, :company,
+ :country_iso, :state_abbr, :state_name, :quick_checkout
+ ]
+ end
+
+ def item_params
+ [:variant_id, :quantity, { metadata: {}, options: {} }]
+ end
+
+ # Find incomplete cart for associate action.
+ # Only finds guest carts (no user) or carts already owned by current user (idempotent).
+ def find_cart_for_association
+ current_store.carts.where(user: [nil, current_user]).find_by_prefix_id!(params[:id])
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/store/checkout_controller.rb b/spree/api/app/controllers/spree/api/v3/store/checkout_controller.rb
deleted file mode 100644
index fce088bb03..0000000000
--- a/spree/api/app/controllers/spree/api/v3/store/checkout_controller.rb
+++ /dev/null
@@ -1,70 +0,0 @@
-module Spree
- module Api
- module V3
- module Store
- class CheckoutController < Store::BaseController
- include Spree::Api::V3::CartResolvable
- include Spree::Api::V3::OrderLock
-
- before_action :find_cart!
-
- # PATCH /api/v3/store/checkout
- # Update checkout info (email, addresses, special instructions).
- # Auto-advances to the next checkout step when possible.
- def update
- with_order_lock do
- result = Spree.checkout_update_service.call(
- order: @cart,
- params: checkout_params
- )
-
- if result.success?
- render_cart
- else
- render_service_error(result.error, code: ERROR_CODES[:validation_error])
- end
- end
- end
-
- # POST /api/v3/store/checkout/complete
- # Complete the checkout — returns Order (not Cart)
- def complete
- with_order_lock do
- result = Spree.checkout_complete_service.call(order: @cart)
-
- if result.success?
- render_order
- else
- render_service_error(result.error, code: ERROR_CODES[:order_already_completed])
- end
- end
- end
-
- private
-
- def checkout_params
- params.permit(
- :email,
- :special_instructions,
- :currency,
- :locale,
- :ship_address_id,
- :bill_address_id,
- ship_address: address_params,
- bill_address: address_params,
- metadata: {}
- )
- end
-
- def address_params
- [
- :id, :firstname, :lastname, :address1, :address2,
- :city, :zipcode, :phone, :company,
- :country_iso, :state_abbr, :state_name, :quick_checkout
- ]
- end
- end
- end
- end
- end
-end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index 09fc0723f8..210ebe5569 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -30,28 +30,23 @@ Spree::Core::Engine.add_routes do
resources :products, only: [:index], controller: 'categories/products'
end
- # Carts (list all active carts for authenticated users)
- resources :carts, only: [:index]
-
- # Cart (pre-purchase, mutable)
- resource :cart, only: [:show, :create, :destroy], controller: 'cart' do
- patch :associate
- resources :items, only: [:create, :update, :destroy], controller: 'cart/items'
- resources :coupon_codes, only: [:create, :destroy], controller: 'cart/coupon_codes'
- end
-
- # Checkout (cart → order transition)
- resource :checkout, only: [:update], controller: 'checkout' do
- post :complete
- resources :shipments, only: [:index, :update], controller: 'checkout/shipments'
- resources :payment_methods, only: [:index], controller: 'checkout/payment_methods'
- resources :payments, only: [:index, :show, :create], controller: 'checkout/payments'
- resources :payment_sessions, only: [:create, :show, :update], controller: 'checkout/payment_sessions' do
+ # Carts
+ resources :carts, only: [:index, :show, :create, :update, :destroy] do
+ member do
+ patch :associate
+ post :complete
+ end
+ resources :items, only: [:create, :update, :destroy], controller: 'carts/items'
+ resources :coupon_codes, only: [:create, :destroy], controller: 'carts/coupon_codes'
+ resources :shipments, only: [:index, :update], controller: 'carts/shipments'
+ resources :payment_methods, only: [:index], controller: 'carts/payment_methods'
+ resources :payments, only: [:index, :show, :create], controller: 'carts/payments'
+ resources :payment_sessions, only: [:create, :show, :update], controller: 'carts/payment_sessions' do
member do
patch :complete
end
end
- resource :store_credits, only: [:create, :destroy], controller: 'checkout/store_credits'
+ resource :store_credits, only: [:create, :destroy], controller: 'carts/store_credits'
end
# Orders (single order lookup, guest-accessible via order token)
diff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rb
index b6983811e4..71f37693d9 100644
--- a/spree/api/lib/spree/api/dependencies.rb
+++ b/spree/api/lib/spree/api/dependencies.rb
@@ -26,7 +26,7 @@ module Spree
# checkout services
storefront_checkout_next_service: -> { Spree::Dependencies.checkout_next_service },
storefront_checkout_advance_service: -> { Spree::Dependencies.checkout_advance_service },
- storefront_checkout_update_service: 'Spree::Checkout::V2Update',
+ storefront_checkout_update_service: -> { Spree::Dependencies.checkout_update_service },
storefront_checkout_complete_service: -> { Spree::Dependencies.checkout_complete_service },
storefront_checkout_add_store_credit_service: -> { Spree::Dependencies.checkout_add_store_credit_service },
storefront_checkout_remove_store_credit_service: -> { Spree::Dependencies.checkout_remove_store_credit_service },
@@ -288,7 +288,7 @@ module Spree
# order services
platform_order_recalculate_service: -> { Spree::Dependencies.cart_recalculate_service },
- platform_order_update_service: 'Spree::Checkout::V2Update',
+ platform_order_update_service: -> { Spree::Dependencies.checkout_update_service },
platform_order_empty_service: -> { Spree::Dependencies.cart_empty_service },
platform_order_destroy_service: -> { Spree::Dependencies.cart_destroy_service },
platform_order_next_service: -> { Spree::Dependencies.checkout_next_service },
diff --git a/spree/api/spec/controllers/concerns/spree/api/v3/idempotent_spec.rb b/spree/api/spec/controllers/concerns/spree/api/v3/idempotent_spec.rb
index 63568a2d05..d0846e1ebc 100644
--- a/spree/api/spec/controllers/concerns/spree/api/v3/idempotent_spec.rb
+++ b/spree/api/spec/controllers/concerns/spree/api/v3/idempotent_spec.rb
@@ -1,7 +1,7 @@
require 'spec_helper'
RSpec.describe Spree::Api::V3::Idempotent, type: :controller do
- describe Spree::Api::V3::Store::CartController do
+ describe Spree::Api::V3::Store::CartsController do
render_views
include_context 'API v3 Store'
@@ -86,10 +86,10 @@ RSpec.describe Spree::Api::V3::Idempotent, type: :controller do
request.headers['x-spree-token'] = cart.token
request.headers['Idempotency-Key'] = idempotency_key
- get :show
+ get :show, params: { id: cart.prefixed_id }
expect(response).to have_http_status(:ok)
- get :show
+ get :show, params: { id: cart.prefixed_id }
expect(response).to have_http_status(:ok)
expect(response.headers['Idempotent-Replayed']).to be_nil
end
diff --git a/spree/api/spec/controllers/spree/api/v3/store/cart/coupon_codes_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts/coupon_codes_controller_spec.rb
similarity index 77%
rename from spree/api/spec/controllers/spree/api/v3/store/cart/coupon_codes_controller_spec.rb
rename to spree/api/spec/controllers/spree/api/v3/store/carts/coupon_codes_controller_spec.rb
index 1f3288260b..cfecdfc652 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/cart/coupon_codes_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/carts/coupon_codes_controller_spec.rb
@@ -1,6 +1,6 @@
require 'spec_helper'
-RSpec.describe Spree::Api::V3::Store::Cart::CouponCodesController, type: :controller do
+RSpec.describe Spree::Api::V3::Store::Carts::CouponCodesController, type: :controller do
render_views
include_context 'API v3 Store'
@@ -17,20 +17,20 @@ RSpec.describe Spree::Api::V3::Store::Cart::CouponCodesController, type: :contro
let!(:promotion) { create(:promotion_with_item_adjustment, code: 'SAVE10', stores: [store]) }
it 'applies the coupon code successfully' do
- post :create, params: { code: 'SAVE10' }
+ post :create, params: { cart_id: order.prefixed_id, code: 'SAVE10' }
expect(response).to have_http_status(:created)
expect(json_response['id']).to start_with('cart_')
end
it 'is case insensitive' do
- post :create, params: { code: 'save10' }
+ post :create, params: { cart_id: order.prefixed_id, code: 'save10' }
expect(response).to have_http_status(:created)
end
it 'returns error for invalid coupon code' do
- post :create, params: { code: 'INVALID' }
+ post :create, params: { cart_id: order.prefixed_id, code: 'INVALID' }
expect(response).to have_http_status(:unprocessable_content)
expect(json_response['error']).to be_present
@@ -40,7 +40,7 @@ RSpec.describe Spree::Api::V3::Store::Cart::CouponCodesController, type: :contro
order.coupon_code = 'SAVE10'
Spree::PromotionHandler::Coupon.new(order).apply
- post :create, params: { code: 'SAVE10' }
+ post :create, params: { cart_id: order.prefixed_id, code: 'SAVE10' }
expect(response).to have_http_status(:unprocessable_content)
end
@@ -53,14 +53,14 @@ RSpec.describe Spree::Api::V3::Store::Cart::CouponCodesController, type: :contro
let!(:coupon_code) { create(:coupon_code, promotion: promotion, code: 'multi1') }
it 'applies the multi-code coupon successfully' do
- post :create, params: { code: 'multi1' }
+ post :create, params: { cart_id: order.prefixed_id, code: 'multi1' }
expect(response).to have_http_status(:created)
expect(json_response['id']).to start_with('cart_')
end
it 'marks the coupon code as used' do
- post :create, params: { code: 'multi1' }
+ post :create, params: { cart_id: order.prefixed_id, code: 'multi1' }
expect(coupon_code.reload.state).to eq('used')
end
@@ -70,7 +70,7 @@ RSpec.describe Spree::Api::V3::Store::Cart::CouponCodesController, type: :contro
let!(:gift_card) { create(:gift_card, store: store, amount: 50, code: 'giftcard123') }
it 'applies the gift card successfully' do
- post :create, params: { code: 'giftcard123' }
+ post :create, params: { cart_id: order.prefixed_id, code: 'giftcard123' }
expect(response).to have_http_status(:created)
expect(json_response['id']).to start_with('cart_')
@@ -79,7 +79,7 @@ RSpec.describe Spree::Api::V3::Store::Cart::CouponCodesController, type: :contro
it 'returns error for expired gift card' do
gift_card.update!(expires_at: 1.day.ago)
- post :create, params: { code: 'giftcard123' }
+ post :create, params: { cart_id: order.prefixed_id, code: 'giftcard123' }
expect(response).to have_http_status(:unprocessable_content)
end
@@ -87,7 +87,7 @@ RSpec.describe Spree::Api::V3::Store::Cart::CouponCodesController, type: :contro
it 'returns error for redeemed gift card' do
gift_card.update!(state: :redeemed, redeemed_at: Time.current, amount_used: gift_card.amount)
- post :create, params: { code: 'giftcard123' }
+ post :create, params: { cart_id: order.prefixed_id, code: 'giftcard123' }
expect(response).to have_http_status(:unprocessable_content)
end
@@ -100,7 +100,7 @@ RSpec.describe Spree::Api::V3::Store::Cart::CouponCodesController, type: :contro
end
it 'returns error' do
- post :create, params: { code: 'EXPIRED' }
+ post :create, params: { cart_id: order.prefixed_id, code: 'EXPIRED' }
expect(response).to have_http_status(:unprocessable_content)
end
@@ -116,7 +116,7 @@ RSpec.describe Spree::Api::V3::Store::Cart::CouponCodesController, type: :contro
end
it 'allows access via spree token' do
- post :create, params: { code: 'GUEST10' }
+ post :create, params: { cart_id: guest_order.prefixed_id, code: 'GUEST10' }
expect(response).to have_http_status(:created)
end
@@ -133,7 +133,7 @@ RSpec.describe Spree::Api::V3::Store::Cart::CouponCodesController, type: :contro
end
it 'removes the coupon code successfully' do
- delete :destroy, params: { id: 'REMOVE10' }
+ delete :destroy, params: { cart_id: order.prefixed_id, id: 'REMOVE10' }
expect(response).to have_http_status(:ok)
expect(order.reload.promotions).not_to include(promotion)
@@ -142,7 +142,7 @@ RSpec.describe Spree::Api::V3::Store::Cart::CouponCodesController, type: :contro
context 'with non-existent coupon code' do
it 'returns error' do
- delete :destroy, params: { id: 'NONEXISTENT' }
+ delete :destroy, params: { cart_id: order.prefixed_id, id: 'NONEXISTENT' }
expect(response).to have_http_status(:unprocessable_content)
end
diff --git a/spree/api/spec/controllers/spree/api/v3/store/cart/items_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts/items_controller_spec.rb
similarity index 73%
rename from spree/api/spec/controllers/spree/api/v3/store/cart/items_controller_spec.rb
rename to spree/api/spec/controllers/spree/api/v3/store/carts/items_controller_spec.rb
index 1d0b17f128..6ddd4e94b5 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/cart/items_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/carts/items_controller_spec.rb
@@ -1,6 +1,6 @@
require 'spec_helper'
-RSpec.describe Spree::Api::V3::Store::Cart::ItemsController, type: :controller do
+RSpec.describe Spree::Api::V3::Store::Carts::ItemsController, type: :controller do
render_views
include_context 'API v3 Store'
@@ -17,7 +17,7 @@ RSpec.describe Spree::Api::V3::Store::Cart::ItemsController, type: :controller d
describe 'POST #create' do
it 'adds a line item and returns updated cart' do
expect do
- post :create, params: { variant_id: variant.prefixed_id, quantity: 2 }
+ post :create, params: { cart_id: order.prefixed_id, variant_id: variant.prefixed_id, quantity: 2 }
end.to change(Spree::LineItem, :count).by(1)
expect(response).to have_http_status(:created)
@@ -26,14 +26,14 @@ RSpec.describe Spree::Api::V3::Store::Cart::ItemsController, type: :controller d
end
it 'defaults quantity to 1' do
- post :create, params: { variant_id: variant.prefixed_id }
+ post :create, params: { cart_id: order.prefixed_id, variant_id: variant.prefixed_id }
expect(response).to have_http_status(:created)
expect(json_response['item_count']).to eq(1)
end
it 'returns updated totals' do
- post :create, params: { variant_id: variant.prefixed_id, quantity: 2 }
+ post :create, params: { cart_id: order.prefixed_id, variant_id: variant.prefixed_id, quantity: 2 }
expect(json_response['item_total'].to_f).to be > 0
end
@@ -41,6 +41,7 @@ RSpec.describe Spree::Api::V3::Store::Cart::ItemsController, type: :controller d
context 'with metadata' do
it 'adds a line item with metadata' do
post :create, params: {
+ cart_id: order.prefixed_id,
variant_id: variant.prefixed_id,
quantity: 1,
metadata: { 'gift_note' => 'Happy Birthday!' }
@@ -59,21 +60,21 @@ RSpec.describe Spree::Api::V3::Store::Cart::ItemsController, type: :controller d
it 'adds line item with valid spree token' do
request.headers['x-spree-token'] = guest_order.token
- post :create, params: { variant_id: variant.prefixed_id, quantity: 1 }
+ post :create, params: { cart_id: guest_order.prefixed_id, variant_id: variant.prefixed_id, quantity: 1 }
expect(response).to have_http_status(:created)
end
- it 'returns not found without spree token' do
- post :create, params: { variant_id: variant.prefixed_id, quantity: 1 }
+ it 'returns forbidden without spree token' do
+ post :create, params: { cart_id: guest_order.prefixed_id, variant_id: variant.prefixed_id, quantity: 1 }
- expect(response).to have_http_status(:not_found)
+ expect(response).to have_http_status(:forbidden)
end
end
context 'validation errors' do
it 'returns error for invalid variant' do
- post :create, params: { variant_id: 'invalid_0', quantity: 1 }
+ post :create, params: { cart_id: order.prefixed_id, variant_id: 'invalid_0', quantity: 1 }
expect(response).to have_http_status(:not_found)
end
@@ -84,7 +85,7 @@ RSpec.describe Spree::Api::V3::Store::Cart::ItemsController, type: :controller d
let!(:line_item) { create(:line_item, order: order, variant: variant, quantity: 1) }
it 'updates line item quantity and returns updated cart' do
- patch :update, params: { id: line_item.prefixed_id, quantity: 5 }
+ patch :update, params: { cart_id: order.prefixed_id, id: line_item.prefixed_id, quantity: 5 }
expect(response).to have_http_status(:ok)
expect(json_response['id']).to start_with('cart_')
@@ -93,7 +94,7 @@ RSpec.describe Spree::Api::V3::Store::Cart::ItemsController, type: :controller d
it 'returns updated totals' do
original_total = order.item_total
- patch :update, params: { id: line_item.prefixed_id, quantity: 5 }
+ patch :update, params: { cart_id: order.prefixed_id, id: line_item.prefixed_id, quantity: 5 }
expect(json_response['item_total'].to_f).to be > original_total
end
@@ -101,6 +102,7 @@ RSpec.describe Spree::Api::V3::Store::Cart::ItemsController, type: :controller d
context 'with metadata' do
it 'updates line item metadata' do
patch :update, params: {
+ cart_id: order.prefixed_id,
id: line_item.prefixed_id,
metadata: { 'gift_note' => 'Happy Birthday!' }
}
@@ -111,6 +113,7 @@ RSpec.describe Spree::Api::V3::Store::Cart::ItemsController, type: :controller d
it 'updates metadata and quantity together' do
patch :update, params: {
+ cart_id: order.prefixed_id,
id: line_item.prefixed_id,
quantity: 3,
metadata: { 'gift_note' => 'Happy Birthday!' }
@@ -125,7 +128,7 @@ RSpec.describe Spree::Api::V3::Store::Cart::ItemsController, type: :controller d
context 'error handling' do
it 'returns not found for non-existent line item' do
- patch :update, params: { id: 'li_nonexistent', quantity: 5 }
+ patch :update, params: { cart_id: order.prefixed_id, id: 'li_nonexistent', quantity: 5 }
expect(response).to have_http_status(:not_found)
end
@@ -137,7 +140,7 @@ RSpec.describe Spree::Api::V3::Store::Cart::ItemsController, type: :controller d
it 'removes line item and returns updated cart' do
expect do
- delete :destroy, params: { id: line_item.prefixed_id }
+ delete :destroy, params: { cart_id: order.prefixed_id, id: line_item.prefixed_id }
end.to change(Spree::LineItem, :count).by(-1)
expect(response).to have_http_status(:ok)
@@ -146,7 +149,7 @@ RSpec.describe Spree::Api::V3::Store::Cart::ItemsController, type: :controller d
context 'error handling' do
it 'returns not found for non-existent line item' do
- delete :destroy, params: { id: 'li_nonexistent' }
+ delete :destroy, params: { cart_id: order.prefixed_id, id: 'li_nonexistent' }
expect(response).to have_http_status(:not_found)
end
diff --git a/spree/api/spec/controllers/spree/api/v3/store/checkout/payment_methods_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts/payment_methods_controller_spec.rb
similarity index 75%
rename from spree/api/spec/controllers/spree/api/v3/store/checkout/payment_methods_controller_spec.rb
rename to spree/api/spec/controllers/spree/api/v3/store/carts/payment_methods_controller_spec.rb
index 182a062ae9..db0cd9fe20 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/checkout/payment_methods_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/carts/payment_methods_controller_spec.rb
@@ -1,6 +1,6 @@
require 'spec_helper'
-RSpec.describe Spree::Api::V3::Store::Checkout::PaymentMethodsController, type: :controller do
+RSpec.describe Spree::Api::V3::Store::Carts::PaymentMethodsController, type: :controller do
render_views
include_context 'API v3 Store'
@@ -16,27 +16,27 @@ RSpec.describe Spree::Api::V3::Store::Checkout::PaymentMethodsController, type:
describe 'GET #index' do
it 'returns available payment methods for the cart' do
- get :index
+ get :index, params: { cart_id: order.prefixed_id }
expect(response).to have_http_status(:ok)
expect(json_response['data'].map { |pm| pm['id'] }).to include(payment_method.prefixed_id)
end
it 'excludes backend-only payment methods' do
- get :index
+ get :index, params: { cart_id: order.prefixed_id }
expect(json_response['data'].map { |pm| pm['id'] }).not_to include(backend_only_pm.prefixed_id)
end
it 'includes session_required in the response' do
- get :index
+ get :index, params: { cart_id: order.prefixed_id }
pm = json_response['data'].find { |p| p['id'] == payment_method.prefixed_id }
expect(pm).to have_key('session_required')
end
it 'includes payment method count in meta' do
- get :index
+ get :index, params: { cart_id: order.prefixed_id }
expect(json_response['meta']['count']).to be_present
end
@@ -48,16 +48,16 @@ RSpec.describe Spree::Api::V3::Store::Checkout::PaymentMethodsController, type:
it 'returns payment methods with valid spree token' do
request.headers['x-spree-token'] = guest_order.token
- get :index
+ get :index, params: { cart_id: guest_order.prefixed_id }
expect(response).to have_http_status(:ok)
expect(json_response['data']).to be_present
end
- it 'returns not found without spree token' do
- get :index
+ it 'returns forbidden without spree token' do
+ get :index, params: { cart_id: guest_order.prefixed_id }
- expect(response).to have_http_status(:not_found)
+ expect(response).to have_http_status(:forbidden)
end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/store/checkout/payment_sessions_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts/payment_sessions_controller_spec.rb
similarity index 74%
rename from spree/api/spec/controllers/spree/api/v3/store/checkout/payment_sessions_controller_spec.rb
rename to spree/api/spec/controllers/spree/api/v3/store/carts/payment_sessions_controller_spec.rb
index bc44e1c8e2..09db54c54a 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/checkout/payment_sessions_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/carts/payment_sessions_controller_spec.rb
@@ -1,6 +1,6 @@
require 'spec_helper'
-RSpec.describe Spree::Api::V3::Store::Checkout::PaymentSessionsController, type: :controller do
+RSpec.describe Spree::Api::V3::Store::Carts::PaymentSessionsController, type: :controller do
render_views
include_context 'API v3 Store'
@@ -22,7 +22,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::PaymentSessionsController, type:
describe 'POST #create' do
it 'creates a payment session' do
- post :create, params: { payment_method_id: payment_method.prefixed_id }
+ post :create, params: { cart_id: order.prefixed_id, payment_method_id: payment_method.prefixed_id }
expect(response).to have_http_status(:created)
expect(json_response['id']).to be_present
@@ -33,6 +33,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::PaymentSessionsController, type:
it 'passes external_data to the gateway' do
post :create, params: {
+ cart_id: order.prefixed_id,
payment_method_id: payment_method.prefixed_id,
external_data: { channel: 'Web' }
}
@@ -48,21 +49,21 @@ RSpec.describe Spree::Api::V3::Store::Checkout::PaymentSessionsController, type:
it 'creates payment session with valid spree token' do
request.headers['x-spree-token'] = guest_order.token
- post :create, params: { payment_method_id: payment_method.prefixed_id }
+ post :create, params: { cart_id: guest_order.prefixed_id, payment_method_id: payment_method.prefixed_id }
expect(response).to have_http_status(:created)
end
- it 'returns not found without spree token' do
- post :create, params: { payment_method_id: payment_method.prefixed_id }
+ it 'returns forbidden without spree token' do
+ post :create, params: { cart_id: guest_order.prefixed_id, payment_method_id: payment_method.prefixed_id }
- expect(response).to have_http_status(:not_found)
+ expect(response).to have_http_status(:forbidden)
end
end
context 'error handling' do
it 'returns not found for non-existent payment method' do
- post :create, params: { payment_method_id: 'pm_invalid' }
+ post :create, params: { cart_id: order.prefixed_id, payment_method_id: 'pm_invalid' }
expect(response).to have_http_status(:not_found)
end
@@ -71,7 +72,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::PaymentSessionsController, type:
describe 'GET #show' do
it 'returns a payment session' do
- get :show, params: { id: payment_session.to_param }
+ get :show, params: { cart_id: order.prefixed_id, id: payment_session.to_param }
expect(response).to have_http_status(:ok)
expect(json_response['id']).to eq(payment_session.prefixed_id)
@@ -82,7 +83,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::PaymentSessionsController, type:
context 'error handling' do
it 'returns not found for non-existent payment session' do
- get :show, params: { id: 'ps_invalid' }
+ get :show, params: { cart_id: order.prefixed_id, id: 'ps_invalid' }
expect(response).to have_http_status(:not_found)
end
@@ -94,7 +95,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::PaymentSessionsController, type:
order: other_order,
payment_method: payment_method)
- get :show, params: { id: other_session.to_param }
+ get :show, params: { cart_id: order.prefixed_id, id: other_session.to_param }
expect(response).to have_http_status(:not_found)
end
@@ -103,7 +104,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::PaymentSessionsController, type:
describe 'PATCH #update' do
it 'updates the payment session' do
- patch :update, params: { id: payment_session.to_param, amount: 50.00 }
+ patch :update, params: { cart_id: order.prefixed_id, 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)
@@ -113,7 +114,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::PaymentSessionsController, type:
describe 'PATCH #complete' do
it 'completes the payment session' do
- patch :complete, params: { id: payment_session.to_param, session_result: 'success' }
+ patch :complete, params: { cart_id: order.prefixed_id, id: payment_session.to_param, session_result: 'success' }
expect(response).to have_http_status(:ok)
expect(json_response['status']).to eq('completed')
diff --git a/spree/api/spec/controllers/spree/api/v3/store/checkout/payments_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts/payments_controller_spec.rb
similarity index 76%
rename from spree/api/spec/controllers/spree/api/v3/store/checkout/payments_controller_spec.rb
rename to spree/api/spec/controllers/spree/api/v3/store/carts/payments_controller_spec.rb
index 5e587f7c04..daff0ae123 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/checkout/payments_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/carts/payments_controller_spec.rb
@@ -1,6 +1,6 @@
require 'spec_helper'
-RSpec.describe Spree::Api::V3::Store::Checkout::PaymentsController, type: :controller do
+RSpec.describe Spree::Api::V3::Store::Carts::PaymentsController, type: :controller do
render_views
include_context 'API v3 Store'
@@ -16,7 +16,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::PaymentsController, type: :contr
describe 'GET #index' do
it 'returns a list of payments for the cart' do
- get :index
+ get :index, params: { cart_id: order.prefixed_id }
expect(response).to have_http_status(:ok)
expect(json_response['data'].size).to eq(1)
@@ -24,7 +24,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::PaymentsController, type: :contr
end
it 'includes payment method information' do
- get :index
+ get :index, params: { cart_id: order.prefixed_id }
expect(json_response['data'].first['payment_method_id']).to eq(payment_method.prefixed_id)
end
@@ -37,23 +37,23 @@ RSpec.describe Spree::Api::V3::Store::Checkout::PaymentsController, type: :contr
it 'returns payments with valid spree token' do
request.headers['x-spree-token'] = guest_order.token
- get :index
+ get :index, params: { cart_id: guest_order.prefixed_id }
expect(response).to have_http_status(:ok)
expect(json_response['data'].size).to eq(1)
end
- it 'returns not found without spree token' do
- get :index
+ it 'returns forbidden without spree token' do
+ get :index, params: { cart_id: guest_order.prefixed_id }
- expect(response).to have_http_status(:not_found)
+ expect(response).to have_http_status(:forbidden)
end
end
end
describe 'GET #show' do
it 'returns a single payment' do
- get :show, params: { id: payment.to_param }
+ get :show, params: { cart_id: order.prefixed_id, id: payment.to_param }
expect(response).to have_http_status(:ok)
expect(json_response['id']).to eq(payment.prefixed_id)
@@ -63,7 +63,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::PaymentsController, type: :contr
context 'error handling' do
it 'returns not found for non-existent payment' do
- get :show, params: { id: 'py_invalid' }
+ get :show, params: { cart_id: order.prefixed_id, id: 'py_invalid' }
expect(response).to have_http_status(:not_found)
end
@@ -73,7 +73,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::PaymentsController, type: :contr
other_order = create(:order_with_line_items, user: other_user, store: store, state: 'payment')
other_payment = create(:payment, order: other_order, payment_method: payment_method, amount: other_order.total)
- get :show, params: { id: other_payment.to_param }
+ get :show, params: { cart_id: order.prefixed_id, id: other_payment.to_param }
expect(response).to have_http_status(:not_found)
end
@@ -84,7 +84,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::PaymentsController, type: :contr
let(:check_payment_method) { create(:check_payment_method, stores: [store]) }
it 'creates a payment with a non-session payment method' do
- post :create, params: { payment_method_id: check_payment_method.prefixed_id }
+ post :create, params: { cart_id: order.prefixed_id, payment_method_id: check_payment_method.prefixed_id }
expect(response).to have_http_status(:created)
expect(json_response['id']).to be_present
@@ -93,7 +93,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::PaymentsController, type: :contr
end
it 'creates a payment with a custom amount' do
- post :create, params: { payment_method_id: check_payment_method.prefixed_id, amount: '50.00' }
+ post :create, params: { cart_id: order.prefixed_id, payment_method_id: check_payment_method.prefixed_id, amount: '50.00' }
expect(response).to have_http_status(:created)
expect(json_response['amount']).to eq('50.0')
@@ -101,6 +101,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::PaymentsController, type: :contr
it 'creates a payment with metadata' do
post :create, params: {
+ cart_id: order.prefixed_id,
payment_method_id: check_payment_method.prefixed_id,
metadata: { purchase_order_number: 'PO-12345' }
}
@@ -113,7 +114,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::PaymentsController, type: :contr
it 'rejects session-required payment methods' do
bogus_method = create(:bogus_payment_method, stores: [store])
- post :create, params: { payment_method_id: bogus_method.prefixed_id }
+ post :create, params: { cart_id: order.prefixed_id, payment_method_id: bogus_method.prefixed_id }
expect(response).to have_http_status(:unprocessable_content)
expect(json_response['error']['code']).to eq('payment_session_required')
@@ -123,14 +124,14 @@ RSpec.describe Spree::Api::V3::Store::Checkout::PaymentsController, type: :contr
unavailable_method = create(:check_payment_method, stores: [store])
allow_any_instance_of(Spree::PaymentMethod::Check).to receive(:available_for_order?).and_return(false)
- post :create, params: { payment_method_id: unavailable_method.prefixed_id }
+ post :create, params: { cart_id: order.prefixed_id, payment_method_id: unavailable_method.prefixed_id }
expect(response).to have_http_status(:unprocessable_content)
expect(json_response['error']['code']).to eq('payment_method_unavailable')
end
it 'returns not found for invalid payment method' do
- post :create, params: { payment_method_id: 'pm_invalid' }
+ post :create, params: { cart_id: order.prefixed_id, payment_method_id: 'pm_invalid' }
expect(response).to have_http_status(:not_found)
end
@@ -142,7 +143,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::PaymentsController, type: :contr
it 'creates a payment with valid spree token' do
request.headers['x-spree-token'] = guest_order.token
- post :create, params: { payment_method_id: check_payment_method.prefixed_id }
+ post :create, params: { cart_id: guest_order.prefixed_id, payment_method_id: check_payment_method.prefixed_id }
expect(response).to have_http_status(:created)
expect(json_response['payment_method_id']).to eq(check_payment_method.prefixed_id)
diff --git a/spree/api/spec/controllers/spree/api/v3/store/checkout/shipments_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts/shipments_controller_spec.rb
similarity index 87%
rename from spree/api/spec/controllers/spree/api/v3/store/checkout/shipments_controller_spec.rb
rename to spree/api/spec/controllers/spree/api/v3/store/carts/shipments_controller_spec.rb
index f07691a054..fef01f314f 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/checkout/shipments_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/carts/shipments_controller_spec.rb
@@ -1,6 +1,6 @@
require 'spec_helper'
-RSpec.describe Spree::Api::V3::Store::Checkout::ShipmentsController, type: :controller do
+RSpec.describe Spree::Api::V3::Store::Carts::ShipmentsController, type: :controller do
render_views
include_context 'API v3 Store'
@@ -21,7 +21,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::ShipmentsController, type: :cont
describe 'GET #index' do
it 'returns a list of shipments for the cart' do
- get :index
+ get :index, params: { cart_id: order.prefixed_id }
expect(response).to have_http_status(:ok)
expect(json_response['data'].size).to eq(order.shipments.count)
@@ -40,16 +40,16 @@ RSpec.describe Spree::Api::V3::Store::Checkout::ShipmentsController, type: :cont
it 'returns shipments with valid spree token' do
request.headers['x-spree-token'] = guest_order.token
- get :index
+ get :index, params: { cart_id: guest_order.prefixed_id }
expect(response).to have_http_status(:ok)
expect(json_response['data']).to be_present
end
- it 'returns not found without spree token' do
- get :index
+ it 'returns forbidden without spree token' do
+ get :index, params: { cart_id: guest_order.prefixed_id }
- expect(response).to have_http_status(:not_found)
+ expect(response).to have_http_status(:forbidden)
end
end
end
@@ -73,6 +73,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::ShipmentsController, type: :cont
expect(order.shipment_total).to eq(5)
patch :update, params: {
+ cart_id: order.prefixed_id,
id: shipment.to_param,
selected_shipping_rate_id: expensive_rate.to_param
}
@@ -91,6 +92,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::ShipmentsController, type: :cont
expect(order.state).to eq('delivery')
patch :update, params: {
+ cart_id: order.prefixed_id,
id: shipment.to_param,
selected_shipping_rate_id: rate.to_param
}
@@ -101,11 +103,11 @@ RSpec.describe Spree::Api::V3::Store::Checkout::ShipmentsController, type: :cont
end
it 'does not fail if advancement is not possible' do
- # Put order in a state where next won't advance (e.g. address)
order.update_column(:state, 'address')
rate = shipment.shipping_rates.first
patch :update, params: {
+ cart_id: order.prefixed_id,
id: shipment.to_param,
selected_shipping_rate_id: rate.to_param
}
@@ -117,6 +119,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::ShipmentsController, type: :cont
context 'error handling' do
it 'returns not found for non-existent shipping rate' do
patch :update, params: {
+ cart_id: order.prefixed_id,
id: shipment.to_param,
selected_shipping_rate_id: 'sr_invalid'
}
diff --git a/spree/api/spec/controllers/spree/api/v3/store/checkout/store_credits_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts/store_credits_controller_spec.rb
similarity index 81%
rename from spree/api/spec/controllers/spree/api/v3/store/checkout/store_credits_controller_spec.rb
rename to spree/api/spec/controllers/spree/api/v3/store/carts/store_credits_controller_spec.rb
index bc4fd9be49..def169e349 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/checkout/store_credits_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/carts/store_credits_controller_spec.rb
@@ -1,6 +1,6 @@
require 'spec_helper'
-RSpec.describe Spree::Api::V3::Store::Checkout::StoreCreditsController, type: :controller do
+RSpec.describe Spree::Api::V3::Store::Carts::StoreCreditsController, type: :controller do
render_views
include_context 'API v3 Store'
@@ -16,7 +16,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::StoreCreditsController, type: :c
describe 'POST #create' do
it 'applies store credit to the cart' do
- post :create, params: { amount: 10 }
+ post :create, params: { cart_id: order.prefixed_id, amount: 10 }
expect(response).to have_http_status(:ok)
expect(json_response['id']).to start_with('cart_')
@@ -30,7 +30,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::StoreCreditsController, type: :c
it 'returns an error' do
jwt = Spree::Api::V3::TestingSupport.generate_jwt(user_without_credit)
request.headers['Authorization'] = "Bearer #{jwt}"
- post :create, params: { amount: 10 }
+ post :create, params: { cart_id: order_without_credit.prefixed_id, amount: 10 }
expect(response).to have_http_status(:unprocessable_content)
expect(json_response['error']).to be_present
@@ -41,7 +41,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::StoreCreditsController, type: :c
it 'requires authentication' do
request.headers['Authorization'] = nil
- post :create, params: { amount: 10 }
+ post :create, params: { cart_id: order.prefixed_id, amount: 10 }
expect(response).to have_http_status(:unauthorized)
end
@@ -52,7 +52,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::StoreCreditsController, type: :c
it 'removes store credit and returns updated cart' do
Spree.checkout_add_store_credit_service.call(order: order, amount: 10)
- delete :destroy
+ delete :destroy, params: { cart_id: order.prefixed_id }
expect(response).to have_http_status(:ok)
expect(json_response['id']).to start_with('cart_')
@@ -62,7 +62,7 @@ RSpec.describe Spree::Api::V3::Store::Checkout::StoreCreditsController, type: :c
it 'requires authentication' do
request.headers['Authorization'] = nil
- delete :destroy
+ delete :destroy, params: { cart_id: order.prefixed_id }
expect(response).to have_http_status(:unauthorized)
end
diff --git a/spree/api/spec/controllers/spree/api/v3/store/cart_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb
similarity index 55%
rename from spree/api/spec/controllers/spree/api/v3/store/cart_controller_spec.rb
rename to spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb
index 77b13004d0..024e41be35 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/cart_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb
@@ -1,6 +1,6 @@
require 'spec_helper'
-RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
+RSpec.describe Spree::Api::V3::Store::CartsController, type: :controller do
render_views
include_context 'API v3 Store'
@@ -9,6 +9,109 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
request.headers['X-Spree-Api-Key'] = api_key.token
end
+ let(:cart) { Spree::Order.last }
+
+ describe 'GET #index' do
+ context 'with JWT authentication' do
+ before do
+ request.headers['Authorization'] = "Bearer #{jwt_token}"
+ end
+
+ let!(:user_cart1) { create(:order, user: user, store: store) }
+ let!(:user_cart2) { create(:order, user: user, store: store) }
+
+ it 'returns the current users carts' do
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data'].size).to eq(2)
+ numbers = json_response['data'].map { |c| c['number'] }
+ expect(numbers).to include(user_cart1.number, user_cart2.number)
+ end
+
+ it 'returns carts ordered by updated_at desc' do
+ user_cart1.update_column(:updated_at, 1.hour.ago)
+ user_cart2.update_column(:updated_at, Time.current)
+
+ get :index
+
+ numbers = json_response['data'].map { |c| c['number'] }
+ expect(numbers).to eq([user_cart2.number, user_cart1.number])
+ end
+
+ it 'returns pagination metadata' do
+ get :index
+
+ expect(json_response['meta']).to include('page', 'count', 'pages')
+ end
+
+ it 'returns cart-prefixed IDs' do
+ get :index
+
+ json_response['data'].each do |cart_json|
+ expect(cart_json['id']).to start_with('cart_')
+ end
+ end
+
+ it 'does not return other users carts' do
+ other_user = create(:user)
+ create(:order, user: other_user, store: store)
+
+ get :index
+
+ numbers = json_response['data'].map { |c| c['number'] }
+ expect(numbers).to match_array([user_cart1.number, user_cart2.number])
+ end
+
+ it 'does not return guest carts' do
+ create(:order, user: nil, store: store)
+
+ get :index
+
+ numbers = json_response['data'].map { |c| c['number'] }
+ expect(numbers).to match_array([user_cart1.number, user_cart2.number])
+ end
+
+ it 'does not return completed orders' do
+ create(:completed_order_with_totals, user: user, store: store)
+
+ get :index
+
+ numbers = json_response['data'].map { |c| c['number'] }
+ expect(numbers).to match_array([user_cart1.number, user_cart2.number])
+ end
+
+ it 'does not return carts from other stores' do
+ other_store = create(:store)
+ create(:order, user: user, store: other_store)
+
+ get :index
+
+ numbers = json_response['data'].map { |c| c['number'] }
+ expect(numbers).to match_array([user_cart1.number, user_cart2.number])
+ end
+ end
+
+ context 'without JWT authentication' do
+ it 'returns unauthorized' do
+ get :index
+
+ expect(response).to have_http_status(:unauthorized)
+ expect(json_response['error']['code']).to eq('authentication_required')
+ end
+ end
+
+ context 'without API key' do
+ before { request.headers['X-Spree-Api-Key'] = nil }
+
+ it 'returns unauthorized' do
+ get :index
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+ end
+ end
+
describe 'POST #create' do
it 'creates a new cart' do
expect do
@@ -29,14 +132,14 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
it 'creates cart associated with current store' do
post :create
- expect(Spree::Order.last.store_id).to eq(store.id)
+ expect(cart.store_id).to eq(store.id)
end
it 'sets locale on the cart' do
post :create
expect(json_response['locale']).to be_present
- expect(Spree::Order.last.locale).to be_present
+ expect(cart.locale).to be_present
end
context 'with metadata' do
@@ -66,7 +169,7 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
post :create
expect(response).to have_http_status(:created)
- expect(Spree::Order.last.user_id).to eq(user.id)
+ expect(cart.user_id).to eq(user.id)
end
end
@@ -84,7 +187,7 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
it 'creates a cart with line items' do
post :create, params: {
- line_items: [
+ items: [
{ variant_id: variant.prefixed_id, quantity: 2 },
{ variant_id: variant2.prefixed_id, quantity: 1 }
]
@@ -99,7 +202,7 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
it 'returns line items in response' do
post :create, params: {
- line_items: [{ variant_id: variant.prefixed_id, quantity: 3 }]
+ items: [{ variant_id: variant.prefixed_id, quantity: 3 }]
}
expect(response).to have_http_status(:created)
@@ -109,21 +212,21 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
it 'defaults quantity to 1 when not specified' do
post :create, params: {
- line_items: [{ variant_id: variant.prefixed_id }]
+ items: [{ variant_id: variant.prefixed_id }]
}
expect(response).to have_http_status(:created)
- expect(Spree::Order.last.line_items.first.quantity).to eq(1)
+ expect(cart.line_items.first.quantity).to eq(1)
end
it 'returns variant_not_found for invalid variant_id' do
post :create, params: {
- line_items: [{ variant_id: 'variant_doesnotexist', quantity: 1 }]
+ items: [{ variant_id: 'variant_doesnotexist', quantity: 1 }]
}
expect(response).to have_http_status(:not_found)
expect(json_response['error']['code']).to eq('variant_not_found')
- expect(json_response['error']['message']).to include('variant_doesnotexist')
+ expect(json_response['error']['message']).to eq('Variant not found')
end
end
@@ -147,7 +250,7 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
before { request.headers['x-spree-token'] = cart.token }
it 'returns the cart' do
- get :show
+ get :show, params: { id: cart.prefixed_id }
expect(response).to have_http_status(:ok)
expect(json_response['number']).to eq(cart.number)
@@ -155,40 +258,36 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
end
it 'returns cart with line items' do
- get :show
+ get :show, params: { id: cart.prefixed_id }
expect(json_response['items']).to be_present
- expect(json_response['items'].size).to eq(cart.line_items.count)
+ expect(json_response['items'].size).to eq(cart.items.count)
end
it 'returns cart token in response' do
- get :show
+ get :show, params: { id: cart.prefixed_id }
expect(json_response['token']).to eq(cart.token)
end
- it 'returns not found for invalid token' do
- request.headers['x-spree-token'] = 'invalid_token'
- get :show
+ it 'returns not found for invalid id' do
+ get :show, params: { id: 'cart_invalid' }
expect(response).to have_http_status(:not_found)
- expect(json_response['error']['code']).to eq('order_not_found')
end
- it 'returns not found for completed order token' do
+ it 'returns not found for completed order' do
completed_order = create(:completed_order_with_totals, store: store)
- request.headers['x-spree-token'] = completed_order.token
- get :show
+ get :show, params: { id: completed_order.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 other store cart' do
other_store = create(:store)
other_cart = create(:order_with_line_items, store: other_store)
request.headers['x-spree-token'] = other_cart.token
- get :show
+ get :show, params: { id: other_cart.prefixed_id }
expect(response).to have_http_status(:not_found)
end
@@ -202,53 +301,27 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
let!(:cart) { create(:order_with_line_items, user: user, store: store) }
it 'returns the users cart' do
- get :show
+ get :show, params: { id: cart.prefixed_id }
expect(response).to have_http_status(:ok)
expect(json_response['number']).to eq(cart.number)
end
- it 'returns the most recent cart when user has multiple' do
- # The let! cart was created first, so create a newer one
- cart # trigger let!
- newer_cart = nil
-
- # Create in a Timecop block to ensure proper timestamps
- Timecop.travel(1.hour.from_now) do
- newer_cart = create(:order_with_line_items, user: user, store: store)
- end
-
- get :show
-
- expect(response).to have_http_status(:ok)
- expect(json_response['number']).to eq(newer_cart.number)
- end
-
- it 'returns not found when user has no cart' do
- cart.update!(state: 'complete', completed_at: Time.current)
-
- get :show
-
- expect(response).to have_http_status(:not_found)
- expect(json_response['error']['code']).to eq('order_not_found')
- end
-
- it 'does not return other users cart' do
- other_user_cart = create(:order_with_line_items, store: store)
- cart.update!(state: 'complete', completed_at: Time.current)
+ it 'returns forbidden when cart belongs to another user' do
+ other_user = create(:user)
+ other_cart = create(:order_with_line_items, user: other_user, store: store)
- get :show
+ get :show, params: { id: other_cart.prefixed_id }
- expect(response).to have_http_status(:not_found)
+ expect(response).to have_http_status(:forbidden)
end
end
context 'without authentication' do
- it 'returns not found without cart_token or JWT' do
- get :show
+ it 'returns not found for nonexistent cart' do
+ get :show, params: { id: 'cart_nonexistent' }
expect(response).to have_http_status(:not_found)
- expect(json_response['error']['code']).to eq('order_not_found')
end
end
@@ -256,7 +329,7 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
before { request.headers['X-Spree-Api-Key'] = nil }
it 'returns unauthorized' do
- get :show
+ get :show, params: { id: 'cart_anything' }
expect(response).to have_http_status(:unauthorized)
expect(json_response['error']['code']).to eq('invalid_token')
@@ -269,7 +342,7 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
before { request.headers['x-spree-token'] = cart.token }
it 'returns expected cart attributes' do
- get :show
+ get :show, params: { id: cart.prefixed_id }
expect(json_response).to include(
'id',
@@ -291,7 +364,7 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
end
it 'returns line item attributes' do
- get :show
+ get :show, params: { id: cart.prefixed_id }
line_item = json_response['items'].first
expect(line_item).to include(
@@ -328,7 +401,7 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
expect(cart.shipments).to be_empty
- get :show
+ get :show, params: { id: cart.prefixed_id }
expect(response).to have_http_status(:ok)
expect(json_response['shipments']).to be_present
@@ -339,7 +412,7 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
cart.shipments.delete_all
cart.reload
- get :show
+ get :show, params: { id: cart.prefixed_id }
expect(response).to have_http_status(:ok)
expect(json_response['shipments']).to be_empty
@@ -347,6 +420,49 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
end
end
+ describe 'PATCH #update' do
+ let(:user) { create(:user_with_addresses) }
+ let!(:order) { create(:order_with_line_items, store: store, user: user) }
+ let(:country) { Spree::Country.find_by(iso: 'US') || create(:country, iso: 'US') }
+ let!(:us_state) { country.states.find_by(abbr: 'NY') || create(:state, country: country, abbr: 'NY', name: 'New York') }
+ let!(:zone) { create(:zone, zone_members: [Spree::ZoneMember.new(zoneable: country)]) }
+ let!(:shipping_method) { create(:shipping_method, zones: [zone]) }
+
+ before do
+ request.headers['Authorization'] = "Bearer #{jwt_token}"
+ end
+
+ it 'accepts ship_address_id to use an existing address' do
+ order.update!(email: '[email protected]')
+ existing_address = user.addresses.first || create(:address, user: user, country: country, state: us_state)
+
+ patch :update, params: { id: order.prefixed_id, ship_address_id: existing_address.prefixed_id }
+
+ expect(response).to have_http_status(:ok)
+ expect(order.reload.ship_address_id).to eq(existing_address.id)
+ end
+
+ it 'auto-advances to payment after address submission' do
+ order.update!(email: '[email protected]')
+ order.next # cart -> address
+ order.reload
+ expect(order.state).to eq('address')
+
+ patch :update, params: {
+ id: order.prefixed_id,
+ ship_address: {
+ firstname: 'John', lastname: 'Doe',
+ address1: '123 Main St', city: 'New York',
+ zipcode: '10001', country_iso: 'US', state_abbr: 'NY',
+ phone: '555-1234'
+ }
+ }
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['current_step']).to eq('payment')
+ end
+ end
+
describe 'PATCH #associate' do
let(:guest_cart) { create(:order_with_line_items, store: store, user: nil, email: '[email protected]') }
@@ -355,9 +471,8 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
request.headers['Authorization'] = "Bearer #{jwt_token}"
end
- it 'associates guest cart with current user via x-spree-token header' do
- request.headers['x-spree-token'] = guest_cart.token
- patch :associate
+ it 'associates guest cart with current user' do
+ patch :associate, params: { id: guest_cart.prefixed_id }
expect(response).to have_http_status(:ok)
expect(guest_cart.reload.user).to eq(user)
@@ -365,8 +480,7 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
end
it 'updates cart email to users email' do
- request.headers['x-spree-token'] = guest_cart.token
- patch :associate
+ patch :associate, params: { id: guest_cart.prefixed_id }
expect(response).to have_http_status(:ok)
expect(guest_cart.reload.email).to eq(user.email)
@@ -377,8 +491,7 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
ship = create(:address, firstname: 'Ship')
user.update!(bill_address: bill, ship_address: ship)
- request.headers['x-spree-token'] = guest_cart.token
- patch :associate
+ patch :associate, params: { id: guest_cart.prefixed_id }
expect(response).to have_http_status(:ok)
guest_cart.reload
@@ -389,47 +502,33 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
it 'allows re-associating cart already owned by current user' do
guest_cart.update!(user: user)
- request.headers['x-spree-token'] = guest_cart.token
- patch :associate
+ patch :associate, params: { id: guest_cart.prefixed_id }
expect(response).to have_http_status(:ok)
expect(guest_cart.reload.user).to eq(user)
end
- it 'returns not found for invalid token' do
- request.headers['x-spree-token'] = 'invalid_token'
- patch :associate
+ it 'returns not found for invalid id' do
+ patch :associate, params: { id: 'cart_invalid' }
expect(response).to have_http_status(:not_found)
- expect(json_response['error']['code']).to eq('order_not_found')
- end
-
- it 'returns not found without order token' do
- patch :associate
-
- expect(response).to have_http_status(:not_found)
- expect(json_response['error']['code']).to eq('order_not_found')
end
it 'returns not found for completed order' do
completed_order = create(:completed_order_with_totals, store: store, user: nil)
- request.headers['x-spree-token'] = completed_order.token
- patch :associate
+ patch :associate, params: { id: completed_order.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 when cart belongs to another user' do
other_user = create(:user)
other_user_cart = create(:order_with_line_items, store: store, user: other_user)
- request.headers['x-spree-token'] = other_user_cart.token
- patch :associate
+ patch :associate, params: { id: other_user_cart.prefixed_id }
expect(response).to have_http_status(:not_found)
- expect(json_response['error']['code']).to eq('order_not_found')
expect(other_user_cart.reload.user).to eq(other_user) # unchanged
end
@@ -437,8 +536,7 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
other_store = create(:store)
other_store_cart = create(:order_with_line_items, store: other_store)
- request.headers['x-spree-token'] = other_store_cart.token
- patch :associate
+ patch :associate, params: { id: other_store_cart.prefixed_id }
expect(response).to have_http_status(:not_found)
end
@@ -446,8 +544,7 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
context 'without JWT authentication' do
it 'returns unauthorized' do
- request.headers['x-spree-token'] = guest_cart.token
- patch :associate
+ patch :associate, params: { id: guest_cart.prefixed_id }
expect(response).to have_http_status(:unauthorized)
expect(json_response['error']['code']).to eq('authentication_required')
@@ -458,11 +555,66 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
before { request.headers['X-Spree-Api-Key'] = nil }
it 'returns unauthorized' do
- request.headers['x-spree-token'] = guest_cart.token
- patch :associate
+ patch :associate, params: { id: guest_cart.prefixed_id }
expect(response).to have_http_status(:unauthorized)
- expect(json_response['error']['code']).to eq('invalid_token')
+ end
+ end
+ end
+
+ describe 'DELETE #destroy' do
+ let(:cart) { create(:order_with_line_items, store: store) }
+
+ context 'with x-spree-token header' do
+ before { request.headers['x-spree-token'] = cart.token }
+
+ it 'deletes the cart' do
+ delete :destroy, params: { id: cart.prefixed_id }
+
+ expect(response).to have_http_status(:no_content)
+ end
+ end
+
+ context 'with JWT authentication' do
+ let!(:user_cart) { create(:order_with_line_items, user: user, store: store) }
+
+ before do
+ request.headers['Authorization'] = "Bearer #{jwt_token}"
+ end
+
+ it 'deletes the users cart' do
+ delete :destroy, params: { id: user_cart.prefixed_id }
+
+ expect(response).to have_http_status(:no_content)
+ end
+ end
+ end
+
+ describe 'POST #complete' do
+ let(:order) { create(:order_with_line_items, user: user, store: store, state: 'confirm') }
+
+ before do
+ request.headers['Authorization'] = "Bearer #{jwt_token}"
+ end
+
+ it 'completes the checkout' do
+ # Set up order so it can be completed
+ create(:payment, order: order, amount: order.total, state: 'checkout')
+ order.shipments.each { |s| s.update_column(:state, 'ready') }
+
+ post :complete, params: { id: order.prefixed_id }
+
+ expect(response).to have_http_status(:ok)
+ expect(order.reload.state).to eq('complete')
+ end
+
+ context 'when order cannot be completed' do
+ let(:incomplete_order) { create(:order_with_line_items, user: user, store: store, state: 'address') }
+
+ it 'returns unprocessable entity' do
+ post :complete, params: { id: incomplete_order.prefixed_id }
+
+ expect(response).to have_http_status(:unprocessable_content)
end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/store/checkout_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/checkout_controller_spec.rb
deleted file mode 100644
index a990f7d0e9..0000000000
--- a/spree/api/spec/controllers/spree/api/v3/store/checkout_controller_spec.rb
+++ /dev/null
@@ -1,50 +0,0 @@
-require 'spec_helper'
-
-RSpec.describe Spree::Api::V3::Store::CheckoutController, type: :controller do
- render_views
-
- include_context 'API v3 Store'
-
- let(:user) { create(:user_with_addresses) }
- let!(:order) { create(:order_with_line_items, store: store, user: user) }
- let(:country) { Spree::Country.find_by(iso: 'US') || create(:country, iso: 'US') }
- let!(:us_state) { country.states.find_by(abbr: 'NY') || create(:state, country: country, abbr: 'NY', name: 'New York') }
- let!(:zone) { create(:zone, zone_members: [Spree::ZoneMember.new(zoneable: country)]) }
- let!(:shipping_method) { create(:shipping_method, zones: [zone]) }
-
- before do
- request.headers['X-Spree-Api-Key'] = api_key.token
- request.headers['Authorization'] = "Bearer #{jwt_token}"
- end
-
- describe 'PATCH #update' do
- it 'accepts ship_address_id to use an existing address' do
- order.update!(email: '[email protected]')
- existing_address = user.addresses.first || create(:address, user: user, country: country, state: us_state)
-
- patch :update, params: { ship_address_id: existing_address.prefixed_id }
-
- expect(response).to have_http_status(:ok)
- expect(order.reload.ship_address_id).to eq(existing_address.id)
- end
-
- it 'auto-advances to payment after address submission' do
- order.update!(email: '[email protected]')
- order.next # cart -> address
- order.reload
- expect(order.state).to eq('address')
-
- patch :update, params: {
- ship_address: {
- firstname: 'John', lastname: 'Doe',
- address1: '123 Main St', city: 'New York',
- zipcode: '10001', country_iso: 'US', state_abbr: 'NY',
- phone: '555-1234'
- }
- }
-
- expect(response).to have_http_status(:ok)
- expect(json_response['current_step']).to eq('payment')
- end
- end
-end
diff --git a/spree/api/spec/integration/spree/api/v3/store/cart_spec.rb b/spree/api/spec/integration/spree/api/v3/store/cart_spec.rb
deleted file mode 100644
index 980ab07b7d..0000000000
--- a/spree/api/spec/integration/spree/api/v3/store/cart_spec.rb
+++ /dev/null
@@ -1,358 +0,0 @@
-# frozen_string_literal: true
-
-require 'swagger_helper'
-
-RSpec.describe 'Cart API', type: :request, swagger_doc: 'api-reference/store.yaml' do
- include_context 'API v3 Store'
-
- path '/api/v3/store/cart' do
- post 'Create a new cart' do
- tags 'Cart'
- consumes 'application/json'
- produces 'application/json'
- security [api_key: []]
- description <<~DESC
- Creates a new shopping cart. Can be created by guests or authenticated customers.
- Returns a `token` that must be used for guest access to the cart.
- DESC
-
- sdk_example <<~JS
- // Create an empty cart
- const cart = await client.cart.create()
-
- // Create a cart with line items
- const cartWithItems = await client.cart.create({
- line_items: [
- { variant_id: 'variant_abc123', quantity: 2 },
- ],
- })
- JS
-
- parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
- parameter name: 'Authorization', in: :header, type: :string, required: false,
- description: 'Bearer JWT token (optional - for authenticated customers)'
- parameter name: :body, in: :body, required: false, schema: {
- type: :object,
- properties: {
- metadata: { type: :object, description: 'Write-only key-value metadata (Stripe-style). Not returned in responses.' },
- line_items: {
- type: :array,
- description: 'Line items to add to the cart on creation',
- items: {
- type: :object,
- properties: {
- variant_id: { type: :string, example: 'variant_abc123', description: 'Prefixed variant ID' },
- quantity: { type: :integer, example: 2, description: 'Quantity (defaults to 1)' },
- metadata: { type: :object, additionalProperties: true, description: 'Arbitrary key-value metadata' }
- },
- required: %w[variant_id]
- }
- }
- }
- }
- parameter name: 'Idempotency-Key', in: :header, type: :string, required: false,
- description: 'Unique key for request idempotency. Duplicate requests with the same key return the cached response.'
-
- response '201', 'cart created (guest)' do
- let(:'x-spree-api-key') { api_key.token }
-
- schema '$ref' => '#/components/schemas/Cart'
-
- run_test! do |response|
- data = JSON.parse(response.body)
- expect(data['id']).to start_with('cart_')
- expect(data['number']).to be_present
- expect(data['current_step']).to eq('address')
- expect(data['completed_steps']).to eq([])
- expect(data['requirements']).to be_an(Array)
- expect(data['token']).to be_present
- end
- end
-
- response '201', 'cart created (authenticated)' do
- let(:'x-spree-api-key') { api_key.token }
- let(:'Authorization') { "Bearer #{jwt_token}" }
-
- schema '$ref' => '#/components/schemas/Cart'
-
- run_test!
- end
-
- response '201', 'cart created with line items' do
- let(:product) { create(:product, stores: [store]) }
- let(:variant) { create(:variant, product: product) }
-
- before { variant.stock_items.first.update!(count_on_hand: 10) }
-
- let(:'x-spree-api-key') { api_key.token }
- let(:body) do
- {
- line_items: [
- { variant_id: variant.prefixed_id, quantity: 3 }
- ]
- }
- end
-
- schema '$ref' => '#/components/schemas/Cart'
-
- run_test! do |response|
- data = JSON.parse(response.body)
- expect(data['items'].size).to eq(1)
- expect(data['items'].first['quantity']).to eq(3)
- expect(data['items'].first['variant_id']).to eq(variant.prefixed_id)
- end
- end
-
- response '201', 'cart created with metadata' do
- let(:'x-spree-api-key') { api_key.token }
- let(:body) { { metadata: { 'source' => 'mobile_app', 'campaign' => 'summer_sale' } } }
-
- schema '$ref' => '#/components/schemas/Cart'
-
- run_test! do |response|
- data = JSON.parse(response.body)
- expect(data['number']).to be_present
- order = Spree::Order.find_by!(number: data['number'])
- expect(order.metadata).to eq({ 'source' => 'mobile_app', 'campaign' => 'summer_sale' })
- end
- end
-
- response '401', 'unauthorized - invalid API key' do
- let(:'x-spree-api-key') { 'invalid' }
-
- schema '$ref' => '#/components/schemas/ErrorResponse'
-
- run_test!
- end
-
- response '400', 'idempotency key too long' do
- let(:'x-spree-api-key') { api_key.token }
- let(:'Idempotency-Key') { 'a' * 256 }
-
- schema '$ref' => '#/components/schemas/ErrorResponse'
-
- run_test! do |response|
- data = JSON.parse(response.body)
- expect(data['error']['code']).to eq('invalid_request')
- end
- end
-
- response '422', 'idempotency key reused with different parameters' do
- let(:'x-spree-api-key') { api_key.token }
- let(:'Idempotency-Key') { 'test-idempotency-key' }
-
- around do |example|
- original_cache = Rails.cache
- Rails.cache = ActiveSupport::Cache::MemoryStore.new
- example.run
- ensure
- Rails.cache = original_cache
- end
-
- before do
- post '/api/v3/store/cart',
- headers: { 'x-spree-api-key' => api_key.token, 'Idempotency-Key' => 'test-idempotency-key' },
- as: :json
- end
-
- schema '$ref' => '#/components/schemas/ErrorResponse'
-
- run_test! do |response|
- data = JSON.parse(response.body)
- expect(data['error']['code']).to eq('idempotency_key_reused')
- end
- end
- end
-
- get 'Get current cart' do
- tags 'Cart'
- produces 'application/json'
- security [api_key: [], bearer_auth: []]
- description <<~DESC
- Returns the current shopping cart (incomplete order).
- Authenticate via JWT token for logged-in users or via x-spree-token header for guests.
- DESC
-
- sdk_example <<~JS
- // Authenticated customer
- const cart = await client.cart.get({
- bearerToken: '<token>',
- })
-
- // Guest with order token
- const guestCart = await client.cart.get({
- orderToken: 'ORDER_TOKEN',
- })
- JS
-
- parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
- parameter name: 'Authorization', in: :header, type: :string, required: false,
- description: 'Bearer JWT token for authenticated customers'
- parameter name: 'x-spree-token', in: :header, type: :string, required: false,
- description: 'Order token for guest checkout'
-
- response '200', 'cart found (guest)' do
- let(:cart) { create(:order_with_line_items, store: store) }
- let(:'x-spree-api-key') { api_key.token }
- let(:'x-spree-token') { cart.token }
-
- schema '$ref' => '#/components/schemas/Cart'
-
- run_test! do |response|
- data = JSON.parse(response.body)
- expect(data['id']).to start_with('cart_')
- expect(data['number']).to eq(cart.number)
- expect(data['token']).to eq(cart.token)
- expect(data['items']).to be_present
- end
- end
-
- response '200', 'cart found (authenticated)' do
- let!(:cart) { create(:order_with_line_items, store: store, user: user) }
- let(:'x-spree-api-key') { api_key.token }
- let(:'Authorization') { "Bearer #{jwt_token}" }
-
- schema '$ref' => '#/components/schemas/Cart'
-
- run_test! do |response|
- data = JSON.parse(response.body)
- expect(data['number']).to eq(cart.number)
- end
- end
-
- response '404', 'no cart found' do
- let(:'x-spree-api-key') { api_key.token }
-
- schema '$ref' => '#/components/schemas/ErrorResponse'
-
- run_test! do |response|
- data = JSON.parse(response.body)
- expect(data['error']['code']).to eq('order_not_found')
- end
- end
- end
-
- delete 'Delete current cart' do
- tags 'Cart'
- produces 'application/json'
- security [api_key: [], bearer_auth: []]
- description 'Deletes/abandons the current shopping cart.'
-
- sdk_example <<~JS
- await client.cart.delete({
- orderToken: 'ORDER_TOKEN',
- })
- JS
-
- parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
- parameter name: 'Authorization', in: :header, type: :string, required: false
- parameter name: 'x-spree-token', in: :header, type: :string, required: false
-
- response '204', 'cart deleted' do
- let!(:cart) { create(:order_with_line_items, store: store, user: user) }
- let(:'x-spree-api-key') { api_key.token }
- let(:'Authorization') { "Bearer #{jwt_token}" }
-
- run_test!
- end
- end
- end
-
- path '/api/v3/store/cart/associate' do
- patch 'Associate guest cart with authenticated user' do
- tags 'Cart'
- produces 'application/json'
- security [api_key: [], bearer_auth: []]
- description <<~DESC
- Associates a guest cart with the currently authenticated user.
- Requires both JWT authentication and an order token.
- The order must not be completed and must not belong to another user.
- DESC
-
- sdk_example <<~JS
- const cart = await client.cart.associate({
- bearerToken: '<token>',
- orderToken: 'GUEST_ORDER_TOKEN',
- })
- JS
-
- parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
- parameter name: 'Authorization', in: :header, type: :string, required: true,
- description: 'Bearer JWT token (required)'
- parameter name: 'x-spree-token', in: :header, type: :string, required: true,
- description: 'Order token for identifying the guest cart'
-
- response '200', 'cart associated successfully' do
- let(:guest_cart) { create(:order_with_line_items, store: store, user: nil) }
- let(:'x-spree-api-key') { api_key.token }
- let(:'Authorization') { "Bearer #{jwt_token}" }
- let(:'x-spree-token') { guest_cart.token }
-
- schema '$ref' => '#/components/schemas/Cart'
-
- run_test! do |response|
- data = JSON.parse(response.body)
- expect(data['id']).to start_with('cart_')
- expect(data['number']).to eq(guest_cart.number)
- expect(guest_cart.reload.user).to eq(user)
- end
- end
-
- response '401', 'unauthorized - JWT required' do
- let(:guest_cart) { create(:order_with_line_items, store: store, user: nil) }
- let(:'x-spree-api-key') { api_key.token }
- let(:'Authorization') { '' }
- let(:'x-spree-token') { guest_cart.token }
-
- schema '$ref' => '#/components/schemas/ErrorResponse'
-
- run_test! do |response|
- data = JSON.parse(response.body)
- expect(data['error']['code']).to eq('authentication_required')
- end
- end
-
- response '404', 'cart belongs to another user' do
- let(:other_user) { create(:user) }
- let(:other_cart) { create(:order_with_line_items, store: store, user: other_user) }
- let(:'x-spree-api-key') { api_key.token }
- let(:'Authorization') { "Bearer #{jwt_token}" }
- let(:'x-spree-token') { other_cart.token }
-
- schema '$ref' => '#/components/schemas/ErrorResponse'
-
- run_test! do |response|
- data = JSON.parse(response.body)
- expect(data['error']['code']).to eq('order_not_found')
- end
- end
-
- response '404', 'cart not found' do
- let(:'x-spree-api-key') { api_key.token }
- let(:'Authorization') { "Bearer #{jwt_token}" }
- let(:'x-spree-token') { 'invalid_token' }
-
- schema '$ref' => '#/components/schemas/ErrorResponse'
-
- run_test! do |response|
- data = JSON.parse(response.body)
- expect(data['error']['code']).to eq('order_not_found')
- end
- end
-
- response '404', 'cart already completed' do
- let(:completed_order) { create(:completed_order_with_totals, store: store, user: nil) }
- let(:'x-spree-api-key') { api_key.token }
- let(:'Authorization') { "Bearer #{jwt_token}" }
- let(:'x-spree-token') { completed_order.token }
-
- schema '$ref' => '#/components/schemas/ErrorResponse'
-
- run_test! do |response|
- data = JSON.parse(response.body)
- expect(data['error']['code']).to eq('order_not_found')
- end
- end
- end
- end
-end
diff --git a/spree/api/spec/integration/spree/api/v3/store/carts_spec.rb b/spree/api/spec/integration/spree/api/v3/store/carts_spec.rb
index 03c43356d8..efddb1943f 100644
--- a/spree/api/spec/integration/spree/api/v3/store/carts_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/store/carts_spec.rb
@@ -9,10 +9,10 @@ RSpec.describe 'Carts API', type: :request, swagger_doc: 'api-reference/store.ya
path '/api/v3/store/carts' do
get 'List active carts' do
- tags 'Cart'
+ tags 'Carts'
produces 'application/json'
security [api_key: [], bearer_auth: []]
- description 'Returns all active (incomplete) carts for the authenticated user. Useful for users who may have multiple carts.'
+ description 'Returns all active (incomplete) carts for the authenticated user.'
sdk_example <<~JS
const carts = await client.carts.list({
@@ -34,7 +34,6 @@ RSpec.describe 'Carts API', type: :request, swagger_doc: 'api-reference/store.ya
run_test! do |response|
data = JSON.parse(response.body)
ids = data['data'].map { |c| c['id'] }
- # All cart IDs should use cart_ prefix
expect(ids).to all(start_with('cart_'))
expect(ids.size).to eq(2)
expect(data['meta']['count']).to eq(2)
@@ -50,5 +49,319 @@ RSpec.describe 'Carts API', type: :request, swagger_doc: 'api-reference/store.ya
run_test!
end
end
+
+ post 'Create a new cart' do
+ tags 'Carts'
+ consumes 'application/json'
+ produces 'application/json'
+ security [api_key: []]
+ description <<~DESC
+ Creates a new shopping cart. Can be created by guests or authenticated customers.
+ Returns a `token` that must be used for guest access to the cart.
+ DESC
+
+ sdk_example <<~JS
+ // Create an empty cart
+ const cart = await client.carts.create()
+
+ // Create a cart with items
+ const cartWithItems = await client.carts.create({
+ items: [
+ { variant_id: 'variant_abc123', quantity: 2 },
+ ],
+ })
+ JS
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: 'Authorization', in: :header, type: :string, required: false,
+ description: 'Bearer JWT token (optional - for authenticated customers)'
+ parameter name: :body, in: :body, required: false, schema: {
+ type: :object,
+ properties: {
+ metadata: { type: :object, description: 'Write-only key-value metadata (Stripe-style).' },
+ items: {
+ type: :array,
+ description: 'Items to add to the cart on creation',
+ items: {
+ type: :object,
+ properties: {
+ variant_id: { type: :string, example: 'variant_abc123', description: 'Prefixed variant ID' },
+ quantity: { type: :integer, example: 2, description: 'Quantity (defaults to 1)' },
+ metadata: { type: :object, additionalProperties: true }
+ },
+ required: %w[variant_id]
+ }
+ }
+ }
+ }
+ parameter name: 'Idempotency-Key', in: :header, type: :string, required: false,
+ description: 'Unique key for request idempotency.'
+
+ response '201', 'cart created' do
+ let(:'x-spree-api-key') { api_key.token }
+
+ schema '$ref' => '#/components/schemas/Cart'
+
+ run_test! do |response|
+ data = JSON.parse(response.body)
+ expect(data['id']).to start_with('cart_')
+ expect(data['number']).to be_present
+ expect(data['current_step']).to eq('address')
+ expect(data['token']).to be_present
+ end
+ end
+ end
+ end
+
+ path '/api/v3/store/carts/{id}' do
+ get 'Get a cart' do
+ tags 'Carts'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ Returns a shopping cart by prefixed ID.
+ Authorize via x-spree-token header (guest) or JWT Bearer token (authenticated user).
+ DESC
+
+ sdk_example <<~JS
+ const cart = await client.carts.get('cart_abc123', {
+ bearerToken: '<token>',
+ })
+ JS
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: 'Authorization', in: :header, type: :string, required: false
+ parameter name: 'x-spree-token', in: :header, type: :string, required: false
+ parameter name: :id, in: :path, type: :string, required: true, description: 'Cart prefixed ID (e.g., cart_abc123)'
+
+ response '200', 'cart found' do
+ let(:cart) { create(:order_with_line_items, store: store) }
+ let(:'x-spree-api-key') { api_key.token }
+ let(:'x-spree-token') { cart.token }
+ let(:id) { cart.prefixed_id }
+
+ schema '$ref' => '#/components/schemas/Cart'
+
+ run_test! do |response|
+ data = JSON.parse(response.body)
+ expect(data['id']).to start_with('cart_')
+ expect(data['number']).to eq(cart.number)
+ end
+ end
+
+ response '404', 'cart not found' do
+ let(:'x-spree-api-key') { api_key.token }
+ let(:id) { 'cart_nonexistent' }
+
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+
+ run_test!
+ end
+ end
+
+ patch 'Update a cart' do
+ tags 'Carts'
+ consumes 'application/json'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description 'Updates cart info (email, addresses, special instructions). When addresses change, the order state is reverted to address to ensure shipments are recalculated.'
+
+ sdk_example <<~JS
+ const cart = await client.carts.update('cart_abc123', {
+ email: '[email protected]',
+ ship_address: {
+ firstname: 'John',
+ lastname: 'Doe',
+ address1: '123 Main St',
+ city: 'New York',
+ zipcode: '10001',
+ country_iso: 'US',
+ state_abbr: 'NY',
+ },
+ }, {
+ bearerToken: '<token>',
+ })
+ JS
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: 'Authorization', in: :header, type: :string, required: false
+ parameter name: 'x-spree-token', in: :header, type: :string, required: false
+ parameter name: 'Idempotency-Key', in: :header, type: :string, required: false
+ parameter name: :id, in: :path, type: :string, required: true, description: 'Cart prefixed ID'
+ parameter name: :body, in: :body, schema: {
+ type: :object,
+ properties: {
+ email: { type: :string, format: 'email', example: '[email protected]' },
+ special_instructions: { type: :string, example: 'Leave at door' },
+ metadata: { type: :object, additionalProperties: true },
+ ship_address_id: { type: :string, description: 'Existing address ID to use as shipping address', example: 'addr_abc123' },
+ bill_address_id: { type: :string, description: 'Existing address ID to use as billing address', example: 'addr_def456' },
+ bill_address: {
+ type: :object,
+ properties: {
+ firstname: { type: :string }, lastname: { type: :string },
+ address1: { type: :string }, address2: { type: :string },
+ city: { type: :string }, zipcode: { type: :string },
+ phone: { type: :string }, company: { type: :string },
+ country_iso: { type: :string }, state_abbr: { type: :string }
+ }
+ },
+ ship_address: {
+ type: :object,
+ properties: {
+ firstname: { type: :string }, lastname: { type: :string },
+ address1: { type: :string }, address2: { type: :string },
+ city: { type: :string }, zipcode: { type: :string },
+ phone: { type: :string }, company: { type: :string },
+ country_iso: { type: :string }, state_abbr: { type: :string }
+ }
+ }
+ }
+ }
+
+ response '200', 'cart updated' do
+ let!(:order) { create(:order_with_line_items, store: store, user: user) }
+ let(:'x-spree-api-key') { api_key.token }
+ let(:'Authorization') { "Bearer #{jwt_token}" }
+ let(:id) { order.prefixed_id }
+ let(:body) { { special_instructions: 'Leave at door' } }
+
+ schema '$ref' => '#/components/schemas/Cart'
+
+ run_test! do |response|
+ data = JSON.parse(response.body)
+ expect(data['id']).to start_with('cart_')
+ expect(data['special_instructions']).to eq('Leave at door')
+ end
+ end
+ end
+
+ delete 'Delete a cart' do
+ tags 'Carts'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description 'Deletes/abandons the cart.'
+
+ sdk_example <<~JS
+ await client.carts.delete('cart_abc123', {
+ bearerToken: '<token>',
+ })
+ JS
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: 'Authorization', in: :header, type: :string, required: false
+ parameter name: 'x-spree-token', in: :header, type: :string, required: false
+ parameter name: :id, in: :path, type: :string, required: true, description: 'Cart prefixed ID'
+
+ response '204', 'cart deleted' do
+ let!(:cart) { create(:order_with_line_items, store: store, user: user) }
+ let(:'x-spree-api-key') { api_key.token }
+ let(:'Authorization') { "Bearer #{jwt_token}" }
+ let(:id) { cart.prefixed_id }
+
+ run_test!
+ end
+ end
+ end
+
+ path '/api/v3/store/carts/{id}/associate' do
+ patch 'Associate guest cart with authenticated user' do
+ tags 'Carts'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ Associates a guest cart with the currently authenticated user.
+ Requires JWT authentication. The cart must not belong to another user.
+ DESC
+
+ sdk_example <<~JS
+ const cart = await client.carts.associate('cart_abc123', {
+ bearerToken: '<token>',
+ })
+ JS
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: 'Authorization', in: :header, type: :string, required: true
+ parameter name: :id, in: :path, type: :string, required: true, description: 'Cart prefixed ID'
+
+ response '200', 'cart associated successfully' do
+ let(:guest_cart) { create(:order_with_line_items, store: store, user: nil) }
+ let(:'x-spree-api-key') { api_key.token }
+ let(:'Authorization') { "Bearer #{jwt_token}" }
+ let(:id) { guest_cart.prefixed_id }
+
+ schema '$ref' => '#/components/schemas/Cart'
+
+ run_test! do |response|
+ data = JSON.parse(response.body)
+ expect(data['id']).to start_with('cart_')
+ expect(guest_cart.reload.user).to eq(user)
+ end
+ end
+
+ response '401', 'unauthorized - JWT required' do
+ let(:guest_cart) { create(:order_with_line_items, store: store, user: nil) }
+ let(:'x-spree-api-key') { api_key.token }
+ let(:'Authorization') { '' }
+ let(:id) { guest_cart.prefixed_id }
+
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+
+ run_test!
+ end
+ end
+ end
+
+ path '/api/v3/store/carts/{id}/complete' do
+ post 'Complete cart' do
+ tags 'Carts'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description 'Completes the cart and finalizes the purchase. Returns an Order (not Cart).'
+
+ sdk_example <<~JS
+ const order = await client.carts.complete('cart_abc123', {
+ bearerToken: '<token>',
+ })
+ JS
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: 'Authorization', in: :header, type: :string, required: false
+ parameter name: 'x-spree-token', in: :header, type: :string, required: false
+ parameter name: :id, in: :path, type: :string, required: true, description: 'Cart prefixed ID'
+
+ response '200', 'cart completed' do
+ let(:completable_order) do
+ order = create(:order_with_line_items, store: store, user: user)
+ Spree.checkout_advance_service.call(order: order)
+ payment_method = create(:check_payment_method, stores: [store])
+ create(:payment, order: order, amount: order.total, payment_method: payment_method, state: 'checkout')
+ order.reload
+ end
+ let!(:_ensure_order) { completable_order }
+ let(:'x-spree-api-key') { api_key.token }
+ let(:'Authorization') { "Bearer #{jwt_token}" }
+ let(:id) { completable_order.prefixed_id }
+
+ schema '$ref' => '#/components/schemas/Order'
+
+ run_test! do |response|
+ data = JSON.parse(response.body)
+ expect(data['id']).to start_with('or_')
+ expect(data['completed_at']).to be_present
+ end
+ end
+
+ response '422', 'cannot complete' do
+ let!(:order) { create(:order_with_line_items, store: store, user: user) }
+ let(:'x-spree-api-key') { api_key.token }
+ let(:'Authorization') { "Bearer #{jwt_token}" }
+ let(:id) { order.prefixed_id }
+
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+
+ run_test!
+ end
+ end
end
end
diff --git a/spree/api/spec/integration/spree/api/v3/store/checkout_spec.rb b/spree/api/spec/integration/spree/api/v3/store/checkout_spec.rb
deleted file mode 100644
index 14bcd23f33..0000000000
--- a/spree/api/spec/integration/spree/api/v3/store/checkout_spec.rb
+++ /dev/null
@@ -1,138 +0,0 @@
-# frozen_string_literal: true
-
-require 'swagger_helper'
-
-RSpec.describe 'Checkout API', type: :request, swagger_doc: 'api-reference/store.yaml' do
- include_context 'API v3 Store'
-
- let(:user) { create(:user_with_addresses) }
- let!(:order) { create(:order_with_line_items, store: store, user: user) }
-
- path '/api/v3/store/checkout' do
- patch 'Update checkout' do
- tags 'Checkout'
- consumes 'application/json'
- produces 'application/json'
- security [api_key: [], bearer_auth: []]
- description 'Updates checkout info (email, addresses, special instructions). When addresses change, the order state is reverted to address to ensure shipments are recalculated.'
-
- sdk_example <<~JS
- const cart = await client.checkout.update({
- email: '[email protected]',
- ship_address: {
- firstname: 'John',
- lastname: 'Doe',
- address1: '123 Main St',
- city: 'New York',
- zipcode: '10001',
- country_iso: 'US',
- state_abbr: 'NY',
- },
- }, {
- bearerToken: '<token>',
- })
- JS
-
- parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
- parameter name: 'Authorization', in: :header, type: :string, required: false
- parameter name: 'x-spree-token', in: :header, type: :string, required: false
- parameter name: 'Idempotency-Key', in: :header, type: :string, required: false,
- description: 'Unique key for request idempotency.'
- parameter name: :body, in: :body, schema: {
- type: :object,
- properties: {
- email: { type: :string, format: 'email', example: '[email protected]' },
- special_instructions: { type: :string, example: 'Leave at door' },
- metadata: { type: :object, additionalProperties: true },
- ship_address_id: { type: :string, description: 'Existing address ID to use as shipping address', example: 'addr_abc123' },
- bill_address_id: { type: :string, description: 'Existing address ID to use as billing address', example: 'addr_def456' },
- bill_address: {
- type: :object,
- properties: {
- firstname: { type: :string }, lastname: { type: :string },
- address1: { type: :string }, address2: { type: :string },
- city: { type: :string }, zipcode: { type: :string },
- phone: { type: :string }, company: { type: :string },
- country_iso: { type: :string }, state_abbr: { type: :string }
- }
- },
- ship_address: {
- type: :object,
- properties: {
- firstname: { type: :string }, lastname: { type: :string },
- address1: { type: :string }, address2: { type: :string },
- city: { type: :string }, zipcode: { type: :string },
- phone: { type: :string }, company: { type: :string },
- country_iso: { type: :string }, state_abbr: { type: :string }
- }
- }
- }
- }
-
- response '200', 'checkout updated' do
- let(:'x-spree-api-key') { api_key.token }
- let(:'Authorization') { "Bearer #{jwt_token}" }
- let(:body) { { special_instructions: 'Leave at door' } }
-
- schema '$ref' => '#/components/schemas/Cart'
-
- run_test! do |response|
- data = JSON.parse(response.body)
- expect(data['id']).to start_with('cart_')
- expect(data['special_instructions']).to eq('Leave at door')
- end
- end
- end
- end
-
- path '/api/v3/store/checkout/complete' do
- post 'Complete checkout' do
- tags 'Checkout'
- produces 'application/json'
- security [api_key: [], bearer_auth: []]
- description 'Completes the checkout and finalizes the purchase. Returns an Order (not Cart).'
-
- sdk_example <<~JS
- const order = await client.checkout.complete({
- bearerToken: '<token>',
- })
- JS
-
- parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
- parameter name: 'Authorization', in: :header, type: :string, required: false
- parameter name: 'x-spree-token', in: :header, type: :string, required: false
- parameter name: 'Idempotency-Key', in: :header, type: :string, required: false
-
- response '200', 'checkout completed' do
- let(:completable_order) do
- order = create(:order_with_line_items, store: store, user: user)
- Spree.checkout_advance_service.call(order: order)
- payment_method = create(:check_payment_method, stores: [store])
- create(:payment, order: order, amount: order.total, payment_method: payment_method, state: 'checkout')
- order.reload
- end
- let!(:_ensure_order) { completable_order }
- let(:'x-spree-api-key') { api_key.token }
- let(:'Authorization') { "Bearer #{jwt_token}" }
-
- schema '$ref' => '#/components/schemas/Order'
-
- run_test! do |response|
- data = JSON.parse(response.body)
- expect(data['id']).to start_with('or_')
- expect(data['completed_at']).to be_present
- end
- end
-
- response '422', 'cannot complete' do
- let(:'x-spree-api-key') { api_key.token }
- let(:'Authorization') { "Bearer #{jwt_token}" }
-
- schema '$ref' => '#/components/schemas/ErrorResponse'
-
- run_test!
- end
- end
- end
-
-end
diff --git a/spree/api/spec/integration/spree/api/v3/store/coupon_codes_spec.rb b/spree/api/spec/integration/spree/api/v3/store/coupon_codes_spec.rb
index 815930db42..5f533ebe80 100644
--- a/spree/api/spec/integration/spree/api/v3/store/coupon_codes_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/store/coupon_codes_spec.rb
@@ -6,10 +6,11 @@ RSpec.describe 'Cart Coupon Codes API', type: :request, swagger_doc: 'api-refere
include_context 'API v3 Store'
let!(:order) { create(:order_with_line_items, store: store, user: user) }
+ let(:cart_id) { order.prefixed_id }
- path '/api/v3/store/cart/coupon_codes' do
+ path '/api/v3/store/carts/{cart_id}/coupon_codes' do
post 'Apply coupon code' do
- tags 'Cart'
+ tags 'Carts'
consumes 'application/json'
produces 'application/json'
security [api_key: [], bearer_auth: []]
@@ -19,7 +20,7 @@ RSpec.describe 'Cart Coupon Codes API', type: :request, swagger_doc: 'api-refere
DESC
sdk_example <<~JS
- const cart = await client.cart.couponCodes.apply('SAVE10', {
+ const cart = await client.carts.couponCodes.apply('cart_abc123', 'SAVE10', {
bearerToken: '<token>',
})
JS
@@ -29,6 +30,7 @@ RSpec.describe 'Cart Coupon Codes API', type: :request, swagger_doc: 'api-refere
description: 'Bearer token for authenticated customers'
parameter name: 'x-spree-token', in: :header, type: :string, required: false,
description: 'Order token for guest access'
+ parameter name: :cart_id, in: :path, type: :string, required: true, description: 'Cart prefixed ID (e.g., cart_abc123)'
parameter name: 'Idempotency-Key', in: :header, type: :string, required: false,
description: 'Unique key for request idempotency.'
parameter name: :body, in: :body, schema: {
@@ -83,15 +85,15 @@ RSpec.describe 'Cart Coupon Codes API', type: :request, swagger_doc: 'api-refere
end
end
- path '/api/v3/store/cart/coupon_codes/{id}' do
+ path '/api/v3/store/carts/{cart_id}/coupon_codes/{id}' do
delete 'Remove coupon code' do
- tags 'Cart'
+ tags 'Carts'
produces 'application/json'
security [api_key: [], bearer_auth: []]
description 'Removes a previously applied coupon code from the cart. The ID is the coupon code string itself.'
sdk_example <<~JS
- const cart = await client.cart.couponCodes.remove('SAVE10', {
+ const cart = await client.carts.couponCodes.remove('cart_abc123', 'SAVE10', {
bearerToken: '<token>',
})
JS
@@ -99,6 +101,7 @@ RSpec.describe 'Cart Coupon Codes API', type: :request, swagger_doc: 'api-refere
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: :cart_id, in: :path, type: :string, required: true, description: 'Cart prefixed ID'
parameter name: :id, in: :path, type: :string, required: true,
description: 'The coupon code string to remove (e.g., SAVE10)'
parameter name: 'x-spree-token', in: :header, type: :string, required: false,
diff --git a/spree/api/spec/integration/spree/api/v3/store/line_items_spec.rb b/spree/api/spec/integration/spree/api/v3/store/line_items_spec.rb
index cb352acbe2..03998e4b22 100644
--- a/spree/api/spec/integration/spree/api/v3/store/line_items_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/store/line_items_spec.rb
@@ -9,17 +9,18 @@ RSpec.describe 'Cart Items API', type: :request, swagger_doc: 'api-reference/sto
let!(:product) { create(:product, stores: [store]) }
let!(:variant) { product.master }
let!(:line_item) { create(:line_item, order: order, variant: variant, quantity: 1) }
+ let(:cart_id) { order.prefixed_id }
- path '/api/v3/store/cart/items' do
+ path '/api/v3/store/carts/{cart_id}/items' do
post 'Add item to cart' do
- tags 'Cart'
+ tags 'Carts'
consumes 'application/json'
produces 'application/json'
security [api_key: [], bearer_auth: []]
description 'Adds a variant to the cart. Creates a new line item or increases quantity if variant already in cart.'
sdk_example <<~JS
- const cart = await client.cart.items.add({
+ const cart = await client.carts.items.create('cart_abc123', {
variant_id: 'variant_abc123',
quantity: 2,
}, {
@@ -32,6 +33,7 @@ RSpec.describe 'Cart Items API', type: :request, swagger_doc: 'api-reference/sto
description: 'Bearer token for authenticated customers'
parameter name: 'x-spree-token', in: :header, type: :string, required: false,
description: 'Order token for guest access'
+ parameter name: :cart_id, in: :path, type: :string, required: true, description: 'Cart prefixed ID (e.g., cart_abc123)'
parameter name: 'Idempotency-Key', in: :header, type: :string, required: false,
description: 'Unique key for request idempotency.'
parameter name: :body, in: :body, schema: {
@@ -86,16 +88,16 @@ RSpec.describe 'Cart Items API', type: :request, swagger_doc: 'api-reference/sto
end
end
- path '/api/v3/store/cart/items/{id}' do
+ path '/api/v3/store/carts/{cart_id}/items/{id}' do
patch 'Update line item quantity' do
- tags 'Cart'
+ tags 'Carts'
consumes 'application/json'
produces 'application/json'
security [api_key: [], bearer_auth: []]
description 'Updates the quantity of a line item in the cart'
sdk_example <<~JS
- const cart = await client.cart.items.update('li_abc123', {
+ const cart = await client.carts.items.update('cart_abc123', 'li_abc123', {
quantity: 5,
}, {
bearerToken: '<token>',
@@ -104,6 +106,7 @@ RSpec.describe 'Cart Items API', type: :request, swagger_doc: 'api-reference/sto
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: 'Authorization', in: :header, type: :string, required: false
+ parameter name: :cart_id, in: :path, type: :string, required: true, description: 'Cart prefixed ID'
parameter name: :id, in: :path, type: :string, required: true, description: 'Line item ID'
parameter name: 'x-spree-token', in: :header, type: :string, required: false
parameter name: :body, in: :body, schema: {
@@ -143,19 +146,20 @@ RSpec.describe 'Cart Items API', type: :request, swagger_doc: 'api-reference/sto
end
delete 'Remove line item from cart' do
- tags 'Cart'
+ tags 'Carts'
produces 'application/json'
security [api_key: [], bearer_auth: []]
description 'Removes a line item from the cart'
sdk_example <<~JS
- const cart = await client.cart.items.remove('li_abc123', {
+ const cart = await client.carts.items.delete('cart_abc123', 'li_abc123', {
bearerToken: '<token>',
})
JS
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: 'Authorization', in: :header, type: :string, required: false
+ parameter name: :cart_id, in: :path, type: :string, required: true, description: 'Cart prefixed ID'
parameter name: :id, in: :path, type: :string, required: true
parameter name: 'x-spree-token', in: :header, type: :string, required: false
diff --git a/spree/api/spec/integration/spree/api/v3/store/payment_methods_spec.rb b/spree/api/spec/integration/spree/api/v3/store/payment_methods_spec.rb
index 613d430af7..7af62db064 100644
--- a/spree/api/spec/integration/spree/api/v3/store/payment_methods_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/store/payment_methods_spec.rb
@@ -2,22 +2,23 @@
require 'swagger_helper'
-RSpec.describe 'Checkout Payment Methods API', type: :request, swagger_doc: 'api-reference/store.yaml' do
+RSpec.describe 'Cart Payment Methods 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!(:payment_method) { create(:credit_card_payment_method, stores: [store], display_on: 'both') }
let!(:backend_only_pm) { create(:credit_card_payment_method, stores: [store], display_on: 'back_end') }
+ let(:cart_id) { order.prefixed_id }
- path '/api/v3/store/checkout/payment_methods' do
+ path '/api/v3/store/carts/{cart_id}/payment_methods' do
get 'List available payment methods' do
- tags 'Checkout'
+ tags 'Carts'
produces 'application/json'
security [api_key: [], bearer_auth: []]
description 'Returns payment methods available for the current cart based on store configuration and order state.'
sdk_example <<~JS
- const methods = await client.checkout.paymentMethods.list({
+ const methods = await client.carts.paymentMethods.list('cart_abc123', {
bearerToken: '<token>',
})
JS
@@ -25,6 +26,7 @@ RSpec.describe 'Checkout Payment Methods API', type: :request, swagger_doc: 'api
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: :cart_id, in: :path, type: :string, required: true, description: 'Cart prefixed ID (e.g., cart_abc123)'
parameter name: 'x-spree-token', in: :header, type: :string, required: false,
description: 'Order token for guest access'
diff --git a/spree/api/spec/integration/spree/api/v3/store/payment_sessions_spec.rb b/spree/api/spec/integration/spree/api/v3/store/payment_sessions_spec.rb
index 4d55422d42..ee703b16b6 100644
--- a/spree/api/spec/integration/spree/api/v3/store/payment_sessions_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/store/payment_sessions_spec.rb
@@ -2,7 +2,7 @@
require 'swagger_helper'
-RSpec.describe 'Checkout Payment Sessions API', type: :request, swagger_doc: 'api-reference/store.yaml' do
+RSpec.describe 'Cart 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') }
@@ -14,17 +14,18 @@ RSpec.describe 'Checkout Payment Sessions API', type: :request, swagger_doc: 'ap
amount: order.total,
external_data: { 'client_secret' => 'secret_123' })
end
+ let(:cart_id) { order.prefixed_id }
- path '/api/v3/store/checkout/payment_sessions' do
+ path '/api/v3/store/carts/{cart_id}/payment_sessions' do
post 'Create payment session' do
- tags 'Checkout'
+ tags 'Carts'
consumes 'application/json'
produces 'application/json'
security [api_key: [], bearer_auth: []]
- description 'Creates a new payment session for the current cart. Delegates to the payment gateway to initialize a provider-specific session (e.g. Stripe PaymentIntent, Adyen session, PayPal order).'
+ description 'Creates a new payment session for the cart. Delegates to the payment gateway to initialize a provider-specific session (e.g. Stripe PaymentIntent, Adyen session, PayPal order).'
sdk_example <<~JS
- const session = await client.checkout.paymentSessions.create({
+ const session = await client.carts.paymentSessions.create('cart_abc123', {
payment_method_id: 'pm_abc123',
}, {
bearerToken: '<token>',
@@ -34,6 +35,7 @@ RSpec.describe 'Checkout Payment Sessions API', type: :request, swagger_doc: 'ap
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: :cart_id, in: :path, type: :string, required: true, description: 'Cart prefixed ID (e.g., cart_abc123)'
parameter name: 'x-spree-token', in: :header, type: :string, required: false,
description: 'Order token for guest access'
parameter name: 'Idempotency-Key', in: :header, type: :string, required: false,
@@ -64,23 +66,24 @@ RSpec.describe 'Checkout Payment Sessions API', type: :request, swagger_doc: 'ap
end
end
- path '/api/v3/store/checkout/payment_sessions/{id}' do
+ path '/api/v3/store/carts/{cart_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: :cart_id, in: :path, type: :string, required: true, description: 'Cart prefixed ID'
parameter name: :id, in: :path, type: :string, required: true,
description: 'Payment session ID'
parameter name: 'x-spree-token', in: :header, type: :string, required: false,
description: 'Order token for guest access'
get 'Get payment session' do
- tags 'Checkout'
+ tags 'Carts'
produces 'application/json'
security [api_key: [], bearer_auth: []]
description 'Returns a single payment session with its current status and provider data.'
sdk_example <<~JS
- const session = await client.checkout.paymentSessions.get('ps_abc123', {
+ const session = await client.carts.paymentSessions.get('cart_abc123', 'ps_abc123', {
bearerToken: '<token>',
})
JS
@@ -110,14 +113,14 @@ RSpec.describe 'Checkout Payment Sessions API', type: :request, swagger_doc: 'ap
end
patch 'Update payment session' do
- tags 'Checkout'
+ tags 'Carts'
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.'
sdk_example <<~JS
- const session = await client.checkout.paymentSessions.update('ps_abc123', {
+ const session = await client.carts.paymentSessions.update('cart_abc123', 'ps_abc123', {
amount: '50.00',
}, {
bearerToken: '<token>',
@@ -148,24 +151,25 @@ RSpec.describe 'Checkout Payment Sessions API', type: :request, swagger_doc: 'ap
end
end
- path '/api/v3/store/checkout/payment_sessions/{id}/complete' do
+ path '/api/v3/store/carts/{cart_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: :cart_id, in: :path, type: :string, required: true, description: 'Cart prefixed ID'
parameter name: :id, in: :path, type: :string, required: true,
description: 'Payment session ID'
parameter name: 'x-spree-token', in: :header, type: :string, required: false,
description: 'Order token for guest access'
patch 'Complete payment session' do
- tags 'Checkout'
+ tags 'Carts'
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.'
sdk_example <<~JS
- const session = await client.checkout.paymentSessions.complete('ps_abc123', {
+ const session = await client.carts.paymentSessions.complete('cart_abc123', 'ps_abc123', {
session_result: 'success',
}, {
bearerToken: '<token>',
diff --git a/spree/api/spec/integration/spree/api/v3/store/payments_spec.rb b/spree/api/spec/integration/spree/api/v3/store/payments_spec.rb
index e9f5e9712b..0a6e3b6272 100644
--- a/spree/api/spec/integration/spree/api/v3/store/payments_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/store/payments_spec.rb
@@ -2,26 +2,28 @@
require 'swagger_helper'
-RSpec.describe 'Checkout Payments API', type: :request, swagger_doc: 'api-reference/store.yaml' do
+RSpec.describe 'Cart Payments 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(:cart_id) { order.prefixed_id }
- path '/api/v3/store/checkout/payments' do
+ path '/api/v3/store/carts/{cart_id}/payments' do
get 'List payments' do
- tags 'Checkout'
+ tags 'Carts'
produces 'application/json'
security [api_key: [], bearer_auth: []]
- description 'Returns all payments for the current cart.'
+ description 'Returns all payments for the cart.'
sdk_example <<~JS
- const payments = await client.checkout.payments.list({
+ const payments = await client.carts.payments.list('cart_abc123', {
bearerToken: '<token>',
})
JS
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: 'Authorization', in: :header, type: :string, required: false
+ parameter name: :cart_id, in: :path, type: :string, required: true, description: 'Cart prefixed ID (e.g., cart_abc123)'
parameter name: 'x-spree-token', in: :header, type: :string, required: false
response '200', 'payments listed' do
@@ -44,14 +46,14 @@ RSpec.describe 'Checkout Payments API', type: :request, swagger_doc: 'api-refere
post 'Create payment' do
let(:check_method) { create(:check_payment_method, stores: [store]) }
- tags 'Checkout'
+ tags 'Carts'
consumes 'application/json'
produces 'application/json'
security [api_key: [], bearer_auth: []]
description 'Creates a payment for a non-session payment method (e.g. Check, Cash on Delivery, Bank Transfer). For payment methods that require a session (e.g. Stripe, PayPal), use the payment sessions endpoint instead.'
sdk_example <<~JS
- const payment = await client.checkout.createPayment({
+ const payment = await client.carts.payments.create('cart_abc123', {
payment_method_id: 'pm_abc123',
}, {
bearerToken: '<token>',
@@ -60,6 +62,7 @@ RSpec.describe 'Checkout Payments API', type: :request, swagger_doc: 'api-refere
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: 'Authorization', in: :header, type: :string, required: false
+ parameter name: :cart_id, in: :path, type: :string, required: true, description: 'Cart prefixed ID'
parameter name: 'x-spree-token', in: :header, type: :string, required: false,
description: 'Order token for guest access'
parameter name: :body, in: :body, schema: {
diff --git a/spree/api/spec/integration/spree/api/v3/store/shipments_spec.rb b/spree/api/spec/integration/spree/api/v3/store/shipments_spec.rb
index b6a41c01ad..9441e64fbb 100644
--- a/spree/api/spec/integration/spree/api/v3/store/shipments_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/store/shipments_spec.rb
@@ -2,27 +2,29 @@
require 'swagger_helper'
-RSpec.describe 'Checkout Shipments API', type: :request, swagger_doc: 'api-reference/store.yaml' do
+RSpec.describe 'Cart Shipments 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: 'delivery') }
let!(:shipment) { order.shipments.first }
+ let(:cart_id) { order.prefixed_id }
- path '/api/v3/store/checkout/shipments' do
+ path '/api/v3/store/carts/{cart_id}/shipments' do
get 'List shipments' do
- tags 'Checkout'
+ tags 'Carts'
produces 'application/json'
security [api_key: [], bearer_auth: []]
- description 'Returns all shipments with shipping rates for the current cart.'
+ description 'Returns all shipments with shipping rates for the cart.'
sdk_example <<~JS
- const shipments = await client.checkout.shipments.list({
+ const shipments = await client.carts.shipments.list('cart_abc123', {
bearerToken: '<token>',
})
JS
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: 'Authorization', in: :header, type: :string, required: false
+ parameter name: :cart_id, in: :path, type: :string, required: true, description: 'Cart prefixed ID (e.g., cart_abc123)'
parameter name: 'x-spree-token', in: :header, type: :string, required: false, description: 'Order token for guest access'
response '200', 'shipments found' do
@@ -38,16 +40,16 @@ RSpec.describe 'Checkout Shipments API', type: :request, swagger_doc: 'api-refer
end
end
- path '/api/v3/store/checkout/shipments/{id}' do
+ path '/api/v3/store/carts/{cart_id}/shipments/{id}' do
patch 'Select shipping rate for shipment' do
- tags 'Checkout'
+ tags 'Carts'
consumes 'application/json'
produces 'application/json'
security [api_key: [], bearer_auth: []]
description 'Selects a shipping rate for a specific shipment and auto-advances checkout.'
sdk_example <<~JS
- const cart = await client.checkout.shipments.update('ship_abc123', {
+ const cart = await client.carts.shipments.update('cart_abc123', 'ship_abc123', {
selected_shipping_rate_id: 'shpr_abc123',
}, {
bearerToken: '<token>',
@@ -56,6 +58,7 @@ RSpec.describe 'Checkout Shipments API', type: :request, swagger_doc: 'api-refer
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: 'Authorization', in: :header, type: :string, required: false
+ parameter name: :cart_id, in: :path, type: :string, required: true, description: 'Cart prefixed ID'
parameter name: :id, in: :path, type: :string, required: true, description: 'Shipment ID'
parameter name: 'x-spree-token', in: :header, type: :string, required: false, description: 'Order token for guest access'
parameter name: :body, in: :body, schema: {
diff --git a/spree/api/spec/integration/spree/api/v3/store/store_credits_spec.rb b/spree/api/spec/integration/spree/api/v3/store/store_credits_spec.rb
index 381c40f97f..6afa4d89e9 100644
--- a/spree/api/spec/integration/spree/api/v3/store/store_credits_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/store/store_credits_spec.rb
@@ -2,28 +2,30 @@
require 'swagger_helper'
-RSpec.describe 'Checkout Store Credits API', type: :request, swagger_doc: 'api-reference/store.yaml' do
+RSpec.describe 'Cart Store Credits API', type: :request, swagger_doc: 'api-reference/store.yaml' do
include_context 'API v3 Store'
let(:user) { create(:user_with_addresses) }
let!(:order) { create(:order_with_line_items, store: store, user: user) }
+ let(:cart_id) { order.prefixed_id }
- path '/api/v3/store/checkout/store_credits' do
+ path '/api/v3/store/carts/{cart_id}/store_credits' do
post 'Apply store credit' do
- tags 'Checkout'
+ tags 'Carts'
consumes 'application/json'
produces 'application/json'
security [api_key: [], bearer_auth: []]
- description 'Applies store credit to the current cart during checkout.'
+ description 'Applies store credit to the cart during checkout.'
sdk_example <<~JS
- const cart = await client.checkout.applyStoreCredit(10.0, {
+ const cart = await client.carts.storeCredits.apply('cart_abc123', 10.0, {
bearerToken: '<token>',
})
JS
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: 'Authorization', in: :header, type: :string, required: true
+ parameter name: :cart_id, in: :path, type: :string, required: true, description: 'Cart prefixed ID (e.g., cart_abc123)'
parameter name: 'x-spree-token', in: :header, type: :string, required: false
parameter name: 'Idempotency-Key', in: :header, type: :string, required: false,
description: 'Unique key for request idempotency.'
@@ -63,19 +65,20 @@ RSpec.describe 'Checkout Store Credits API', type: :request, swagger_doc: 'api-r
end
delete 'Remove store credit' do
- tags 'Checkout'
+ tags 'Carts'
produces 'application/json'
security [api_key: [], bearer_auth: []]
- description 'Removes store credit from the current cart.'
+ description 'Removes store credit from the cart.'
sdk_example <<~JS
- const cart = await client.checkout.removeStoreCredit({
+ const cart = await client.carts.storeCredits.remove('cart_abc123', {
bearerToken: '<token>',
})
JS
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: 'Authorization', in: :header, type: :string, required: true
+ parameter name: :cart_id, in: :path, type: :string, required: true, description: 'Cart prefixed ID'
parameter name: 'x-spree-token', in: :header, type: :string, required: false
response '200', 'store credit removed' do
diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rb
index 1d98a55b3f..07d1946b1f 100644
--- a/spree/core/app/models/spree/order.rb
+++ b/spree/core/app/models/spree/order.rb
@@ -149,6 +149,8 @@ module Spree
end
has_many :shipment_adjustments, through: :shipments, source: :adjustments
+ alias items line_items
+
accepts_nested_attributes_for :line_items
accepts_nested_attributes_for :bill_address
accepts_nested_attributes_for :ship_address
diff --git a/spree/core/app/services/spree/cart/create.rb b/spree/core/app/services/spree/cart/create.rb
index f99b650f92..d52564dd18 100644
--- a/spree/core/app/services/spree/cart/create.rb
+++ b/spree/core/app/services/spree/cart/create.rb
@@ -3,49 +3,22 @@ module Spree
class Create
prepend Spree::ServiceModule::Base
- # @param user [Spree.user_class, nil] the user to associate with the cart
- # @param store [Spree::Store] the store for the cart
- # @param currency [String, nil] ISO currency code, defaults to store's default currency
- # @param locale [String, nil] locale for the cart (e.g. 'en', 'fr'), defaults to Spree::Current.locale
- # @param public_metadata [Hash] public metadata for the order
- # @param private_metadata [Hash] private metadata for the order
- # @param order_params [Hash] additional order attributes
- # @param line_items [Array<Hash>] line items to add, each with :variant_id (prefixed) and :quantity
- # @return [Spree::ServiceModule::Result]
- def call(user:, store:, currency:, locale: nil, metadata: {}, public_metadata: {}, private_metadata: {}, order_params: {}, line_items: [])
+ def call(user:, store:, currency:, public_metadata: {}, private_metadata: {}, order_params: {})
order_params ||= {}
- line_items ||= []
# we cannot create an order without store
return failure(:store_is_required) if store.nil?
- resolved_metadata = metadata.presence || private_metadata
-
default_params = {
user: user,
currency: currency || store.default_currency,
- locale: locale || Spree::Current.locale,
token: Spree::GenerateToken.new.call(Spree::Order),
public_metadata: public_metadata.to_h,
- private_metadata: resolved_metadata.to_h
+ private_metadata: private_metadata.to_h
}
- order = nil
-
- ApplicationRecord.transaction do
- order = store.orders.create!(default_params.merge(order_params))
-
- if line_items.present?
- result = Spree.cart_upsert_items_service.call(order: order, line_items: line_items)
- raise StandardError, result.error.to_s if result.failure?
- end
- end
-
+ order = store.orders.create!(default_params.merge(order_params))
success(order)
- rescue ActiveRecord::RecordNotFound
- raise
- rescue StandardError => e
- failure(order, e.message)
end
end
end
diff --git a/spree/core/app/services/spree/carts/create.rb b/spree/core/app/services/spree/carts/create.rb
new file mode 100644
index 0000000000..2008fbcb10
--- /dev/null
+++ b/spree/core/app/services/spree/carts/create.rb
@@ -0,0 +1,32 @@
+module Spree
+ module Carts
+ class Create
+ prepend Spree::ServiceModule::Base
+
+ def call(params: {})
+ @params = params.to_h.deep_symbolize_keys
+
+ store = @params.delete(:store)
+ return failure(:store_is_required) if store.nil?
+
+ cart = store.carts.create!(
+ user: @params.delete(:user),
+ currency: @params.delete(:currency) || store.default_currency,
+ locale: @params.delete(:locale) || Spree::Current.locale
+ )
+
+ # Delegate all attribute/address/item processing to Carts::Update
+ if @params.present?
+ result = Spree::Carts::Update.call(cart: cart, params: @params)
+ return result if result.failure?
+ end
+
+ success(cart.reload)
+ rescue ActiveRecord::RecordNotFound
+ raise
+ rescue StandardError => e
+ failure(nil, e.message)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/services/spree/carts/update.rb b/spree/core/app/services/spree/carts/update.rb
new file mode 100644
index 0000000000..38285f84a1
--- /dev/null
+++ b/spree/core/app/services/spree/carts/update.rb
@@ -0,0 +1,112 @@
+module Spree
+ module Carts
+ class Update
+ prepend Spree::ServiceModule::Base
+
+ def call(cart:, params:)
+ @cart = cart
+ @params = params.to_h.deep_symbolize_keys
+
+ ApplicationRecord.transaction do
+ assign_cart_attributes
+ assign_address(:ship_address)
+ assign_address(:bill_address)
+
+ cart.save!
+
+ process_items
+ end
+
+ try_advance
+
+ success(cart)
+ rescue ActiveRecord::RecordNotFound
+ raise
+ rescue ActiveRecord::RecordInvalid => e
+ failure(cart, e.record.errors.full_messages.to_sentence)
+ rescue StandardError => e
+ failure(cart, e.message)
+ end
+
+ private
+
+ attr_reader :cart, :params
+
+ def assign_cart_attributes
+ cart.email = params[:email] if params[:email].present?
+ cart.special_instructions = params[:special_instructions] if params.key?(:special_instructions)
+ cart.currency = params[:currency].upcase if params[:currency].present?
+ cart.locale = params[:locale] if params[:locale].present?
+ cart.metadata = cart.metadata.merge(params[:metadata].to_h) if params[:metadata].present?
+ end
+
+ def assign_address(address_type)
+ address_id_param = params[:"#{address_type}_id"]
+ address_params = params[address_type]
+
+ if address_id_param.present?
+ address_id = resolve_address_id(address_id_param)
+ cart.public_send(:"#{address_type}_id=", address_id) if address_id
+ return
+ end
+
+ return unless address_params.is_a?(Hash)
+
+ if address_params[:id].present?
+ address_id = resolve_address_id(address_params[:id])
+ cart.public_send(:"#{address_type}_id=", address_id) if address_id
+ else
+ revert_to_address_state if cart.has_checkout_step?('address')
+ cart.public_send(:"#{address_type}_attributes=", address_params)
+ end
+ end
+
+ def process_items
+ return unless params[:items].is_a?(Array)
+
+ result = Spree::Carts::UpsertItems.call(
+ cart: cart,
+ items: params[:items]
+ )
+
+ raise StandardError, result.error.to_s if result.failure?
+ end
+
+ def resolve_address_id(prefixed_id)
+ return unless cart.user
+
+ decoded = Spree::Address.decode_prefixed_id(prefixed_id)
+ decoded ? cart.user.addresses.find_by(id: decoded)&.id : nil
+ end
+
+ def revert_to_address_state
+ return if ['cart', 'address'].include?(cart.state)
+
+ cart.state = 'address'
+ end
+
+ # Auto-advance as far as the checkout state machine allows.
+ # Loops cart.next until the cart can't progress further (e.g. missing
+ # payment) or reaches confirm/complete. Stops at the first step whose
+ # before_transition guard fails — the `requirements` array in the
+ # serialized response tells the frontend what's still missing.
+ # Failure is swallowed — the update itself already succeeded.
+ def try_advance
+ return if cart.complete? || cart.canceled?
+
+ loop do
+ break unless cart.next
+ break if cart.confirm? || cart.complete?
+ end
+ rescue StandardError => e
+ Rails.error.report(e, context: { order_id: cart.id, state: cart.state }, source: 'spree.checkout')
+ ensure
+ begin
+ cart.reload
+ rescue StandardError # rubocop:disable Lint/SuppressedException
+ # reload failure must not mask the original result
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/app/services/spree/cart/upsert_items.rb b/spree/core/app/services/spree/carts/upsert_items.rb
similarity index 56%
rename from spree/core/app/services/spree/cart/upsert_items.rb
rename to spree/core/app/services/spree/carts/upsert_items.rb
index ece713d0af..63e124e24e 100644
--- a/spree/core/app/services/spree/cart/upsert_items.rb
+++ b/spree/core/app/services/spree/carts/upsert_items.rb
@@ -1,21 +1,17 @@
module Spree
- module Cart
- # Bulk upsert line items on an order.
+ module Carts
+ # Bulk upsert line items on a cart.
#
- # For each entry in +line_items+:
- # - If a line item for the variant already exists → sets its quantity
- # - If no line item exists → creates one with the given quantity
+ # For each entry in +items+:
+ # - If a line item for the variant already exists -> sets its quantity
+ # - If no line item exists -> creates one with the given quantity
#
- # After all items are processed the order is recalculated once.
- #
- # Price calculation and tax adjustments are handled by LineItem model callbacks
- # (copy_price, update_adjustments, update_tax_charge), so we only need to
- # save each item and run a single order recalculation at the end.
+ # After all items are processed the cart is recalculated once.
#
# @example
- # Spree::Cart::UpsertItems.call(
- # order: order,
- # line_items: [
+ # Spree::Carts::UpsertItems.new.call(
+ # cart: cart,
+ # items: [
# { variant_id: "variant_k5nR8xLq", quantity: 2 },
# { variant_id: "variant_m3Rp9wXz", quantity: 1 }
# ]
@@ -24,39 +20,39 @@ module Spree
class UpsertItems
prepend Spree::ServiceModule::Base
- def call(order:, line_items:)
- line_items = Array(line_items)
- return success(order) if line_items.empty?
+ def call(cart:, items:)
+ items = Array(items)
+ return success(cart) if items.empty?
- store = order.store || Spree::Current.store
+ store = cart.store || Spree::Current.store
ApplicationRecord.transaction do
- line_items.each do |item_params|
+ items.each do |item_params|
item_params = item_params.to_h.deep_symbolize_keys
variant = resolve_variant(store, item_params[:variant_id])
next unless variant
quantity = (item_params[:quantity] || 1).to_i
- return failure(variant, "#{variant.name} is not available in #{order.currency}") if variant.amount_in(order.currency).nil?
+ return failure(variant, "#{variant.name} is not available in #{cart.currency}") if variant.amount_in(cart.currency).nil?
- line_item = Spree.line_item_by_variant_finder.new.execute(order: order, variant: variant)
+ line_item = Spree.line_item_by_variant_finder.new.execute(order: cart, variant: variant)
if line_item
line_item.quantity = quantity
line_item.metadata = line_item.metadata.merge(item_params[:metadata].to_h) if item_params[:metadata].present?
else
- line_item = order.line_items.new(quantity: quantity, variant: variant, options: { currency: order.currency })
+ line_item = cart.items.new(quantity: quantity, variant: variant, options: { currency: cart.currency })
line_item.metadata = item_params[:metadata].to_h if item_params[:metadata].present?
end
return failure(line_item) unless line_item.save
end
- order.update_with_updater!
+ cart.update_with_updater!
end
- success(order)
+ success(cart)
end
private
diff --git a/spree/core/app/services/spree/checkout/update.rb b/spree/core/app/services/spree/checkout/update.rb
index d8ecb90631..93f5eff155 100644
--- a/spree/core/app/services/spree/checkout/update.rb
+++ b/spree/core/app/services/spree/checkout/update.rb
@@ -2,110 +2,70 @@ module Spree
module Checkout
class Update
prepend Spree::ServiceModule::Base
-
- def call(order:, params:)
- @order = order
- @params = params.to_h.deep_symbolize_keys
-
- ApplicationRecord.transaction do
- assign_order_attributes
- assign_address(:ship_address)
- assign_address(:bill_address)
-
- order.save!
-
- process_line_items
+ include Spree::Addresses::Helper
+
+ def call(order:, params:, permitted_attributes:, request_env:)
+ # Validate address ownership to prevent IDOR attacks
+ address_ownership_error = validate_address_ownership(order, params)
+ return failure(order, address_ownership_error) if address_ownership_error
+
+ ship_changed = address_with_country_iso_present?(params, 'ship')
+ bill_changed = address_with_country_iso_present?(params, 'bill')
+ params[:order][:ship_address_attributes] = replace_country_iso_with_id(params[:order][:ship_address_attributes]) if ship_changed
+ params[:order][:bill_address_attributes] = replace_country_iso_with_id(params[:order][:bill_address_attributes]) if bill_changed
+
+ # for quick checkouts we cannot revert to previous states
+ # we already have the address and delivery steps completed
+ # however we need to update the shipping address with missing data
+ # as previously we didn't have access to first/last name and street
+ unless params[:do_not_change_state]
+ order.state = 'address' if (ship_changed || bill_changed || quick_checkout_cancelled?(params)) && order.has_checkout_step?('address')
+ order.state = 'delivery' if selected_shipping_rate_present?(params) && order.has_checkout_step?('delivery')
end
- try_advance
+ return success(order) if order.update_from_params(params, permitted_attributes, request_env)
- success(order)
- rescue ActiveRecord::RecordNotFound
- raise
- rescue ActiveRecord::RecordInvalid => e
- failure(order, e.record.errors.full_messages.to_sentence)
- rescue StandardError => e
- failure(order, e.message)
+ failure(order)
end
private
- attr_reader :order, :params
-
- def assign_order_attributes
- order.email = params[:email] if params[:email].present?
- order.special_instructions = params[:special_instructions] if params.key?(:special_instructions)
- order.currency = params[:currency].upcase if params[:currency].present?
- order.locale = params[:locale] if params[:locale].present?
- order.metadata = order.metadata.merge(params[:metadata].to_h) if params[:metadata].present?
- end
+ def validate_address_ownership(order, params)
+ return nil unless params[:order]
- def assign_address(address_type)
- address_id_param = params[:"#{address_type}_id"]
- address_params = params[address_type]
+ %w[bill ship].each do |address_kind|
+ address_id = params[:order].dig("#{address_kind}_address_attributes".to_sym, :id)
+ next unless address_id
- if address_id_param.present?
- address_id = resolve_address_id(address_id_param)
- order.public_send(:"#{address_type}_id=", address_id) if address_id
- return
- end
+ address = Spree::Address.find_by(id: address_id)
+ next unless address
- return unless address_params.is_a?(Hash)
+ # Allow if address has no user (guest address) or belongs to the order's user
+ next if address.user_id.nil?
+ next if order.user_id.present? && address.user_id == order.user_id
- if address_params[:id].present?
- address_id = resolve_address_id(address_params[:id])
- order.public_send(:"#{address_type}_id=", address_id) if address_id
- else
- revert_to_address_state if order.has_checkout_step?('address')
- order.public_send(:"#{address_type}_attributes=", address_params)
+ return Spree.t(:address_not_owned_by_user)
end
- end
-
- def process_line_items
- return unless params[:line_items].is_a?(Array)
- result = Spree.cart_upsert_items_service.call(
- order: order,
- line_items: params[:line_items]
- )
-
- raise StandardError, result.error.to_s if result.failure?
+ nil
end
- def resolve_address_id(prefixed_id)
- return unless order.user
+ def address_with_country_iso_present?(params, address_kind = 'ship')
+ return false unless params.dig(:order, "#{address_kind}_address_attributes".to_sym, :country_iso)
+ return false if params.dig(:order, "#{address_kind}_address_attributes".to_sym, :country_id)
- decoded = Spree::Address.decode_prefixed_id(prefixed_id)
- decoded ? order.user.addresses.find_by(id: decoded)&.id : nil
+ true
end
- def revert_to_address_state
- return if ['cart', 'address'].include?(order.state)
+ def selected_shipping_rate_present?(params)
+ shipments_attributes = params.dig(:order, :shipments_attributes)
+ return false unless shipments_attributes
- order.state = 'address'
+ shipments_attributes.any? { |s| s.dig(:selected_shipping_rate_id) }
end
- # Auto-advance as far as the checkout state machine allows.
- # Loops order.next until the order can't progress further (e.g. missing
- # payment) or reaches confirm/complete. Stops at the first step whose
- # before_transition guard fails — the `requirements` array in the
- # serialized response tells the frontend what's still missing.
- # Failure is swallowed — the update itself already succeeded.
- def try_advance
- return if order.complete? || order.canceled?
-
- loop do
- break unless order.next
- break if order.confirm? || order.complete?
- end
- rescue StandardError => e
- Rails.error.report(e, context: { order_id: order.id, state: order.state }, source: 'spree.checkout')
- ensure
- begin
- order.reload
- rescue StandardError # rubocop:disable Lint/SuppressedException
- # reload failure must not mask the original result
- end
+ def quick_checkout_cancelled?(params)
+ params.dig(:order, :ship_address_id) == 'CLEAR'
end
end
end
diff --git a/spree/core/app/services/spree/checkout/v2_update.rb b/spree/core/app/services/spree/checkout/v2_update.rb
deleted file mode 100644
index 7833f89421..0000000000
--- a/spree/core/app/services/spree/checkout/v2_update.rb
+++ /dev/null
@@ -1,72 +0,0 @@
-module Spree
- module Checkout
- class V2Update
- prepend Spree::ServiceModule::Base
- include Spree::Addresses::Helper
-
- def call(order:, params:, permitted_attributes:, request_env:)
- # Validate address ownership to prevent IDOR attacks
- address_ownership_error = validate_address_ownership(order, params)
- return failure(order, address_ownership_error) if address_ownership_error
-
- ship_changed = address_with_country_iso_present?(params, 'ship')
- bill_changed = address_with_country_iso_present?(params, 'bill')
- params[:order][:ship_address_attributes] = replace_country_iso_with_id(params[:order][:ship_address_attributes]) if ship_changed
- params[:order][:bill_address_attributes] = replace_country_iso_with_id(params[:order][:bill_address_attributes]) if bill_changed
-
- # for quick checkouts we cannot revert to previous states
- # we already have the address and delivery steps completed
- # however we need to update the shipping address with missing data
- # as previously we didn't have access to first/last name and street
- unless params[:do_not_change_state]
- order.state = 'address' if (ship_changed || bill_changed || quick_checkout_cancelled?(params)) && order.has_checkout_step?('address')
- order.state = 'delivery' if selected_shipping_rate_present?(params) && order.has_checkout_step?('delivery')
- end
-
- return success(order) if order.update_from_params(params, permitted_attributes, request_env)
-
- failure(order)
- end
-
- private
-
- def validate_address_ownership(order, params)
- return nil unless params[:order]
-
- %w[bill ship].each do |address_kind|
- address_id = params[:order].dig("#{address_kind}_address_attributes".to_sym, :id)
- next unless address_id
-
- address = Spree::Address.find_by(id: address_id)
- next unless address
-
- # Allow if address has no user (guest address) or belongs to the order's user
- next if address.user_id.nil?
- next if order.user_id.present? && address.user_id == order.user_id
-
- return Spree.t(:address_not_owned_by_user)
- end
-
- nil
- end
-
- def address_with_country_iso_present?(params, address_kind = 'ship')
- return false unless params.dig(:order, "#{address_kind}_address_attributes".to_sym, :country_iso)
- return false if params.dig(:order, "#{address_kind}_address_attributes".to_sym, :country_id)
-
- true
- end
-
- def selected_shipping_rate_present?(params)
- shipments_attributes = params.dig(:order, :shipments_attributes)
- return false unless shipments_attributes
-
- shipments_attributes.any? { |s| s.dig(:selected_shipping_rate_id) }
- end
-
- def quick_checkout_cancelled?(params)
- params.dig(:order, :ship_address_id) == 'CLEAR'
- end
- end
- end
-end
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 5a7f9e1bbb..c837009f81 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -837,6 +837,7 @@ en:
card_type: Brand
card_type_is: Card type is
cart: Cart
+ cart_already_updated: The cart has already been updated.
cart_line_item:
discontinued: "%{li_name} was removed because it was discontinued"
out_of_stock: "%{li_name} was removed because it was sold out"
@@ -1565,8 +1566,6 @@ en:
order: Order
order_adjustments: Order adjustments
order_again: Order again
- order_already_completed: Order already completed
- order_already_updated: The order has already been updated.
order_approved: Order approved
order_canceled: Order canceled
order_details: Order Details
diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rb
index 383879de5b..b8313b7970 100644
--- a/spree/core/lib/spree/core/dependencies.rb
+++ b/spree/core/lib/spree/core/dependencies.rb
@@ -16,7 +16,6 @@ module Spree
cart_remove_item_service: 'Spree::Cart::RemoveItem',
cart_remove_line_item_service: 'Spree::Cart::RemoveLineItem',
cart_set_item_quantity_service: 'Spree::Cart::SetQuantity',
- cart_upsert_items_service: 'Spree::Cart::UpsertItems',
cart_estimate_shipping_rates_service: 'Spree::Cart::EstimateShippingRates',
cart_empty_service: 'Spree::Cart::Empty',
cart_destroy_service: 'Spree::Cart::Destroy',
@@ -42,7 +41,6 @@ module Spree
# order
order_approve_service: 'Spree::Orders::Approve',
order_cancel_service: 'Spree::Orders::Cancel',
- order_update_service: 'Spree::Checkout::Update',
order_updater: 'Spree::OrderUpdater',
# shipment
diff --git a/spree/core/lib/spree/testing_support/factories/order_factory.rb b/spree/core/lib/spree/testing_support/factories/order_factory.rb
index b32890f353..df2556a0f9 100644
--- a/spree/core/lib/spree/testing_support/factories/order_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/order_factory.rb
@@ -22,6 +22,9 @@ FactoryBot.define do
end
end
+ factory :cart, class: Spree::Order do
+ end
+
factory :order_with_totals do
after(:create) do |order, evaluator|
create(:line_item, order: order, price: evaluator.line_items_price)
diff --git a/spree/core/spec/services/spree/cart/create_spec.rb b/spree/core/spec/services/spree/carts/create_spec.rb
similarity index 76%
rename from spree/core/spec/services/spree/cart/create_spec.rb
rename to spree/core/spec/services/spree/carts/create_spec.rb
index 55c2dd6f2e..c7e0936a61 100644
--- a/spree/core/spec/services/spree/cart/create_spec.rb
+++ b/spree/core/spec/services/spree/carts/create_spec.rb
@@ -1,18 +1,17 @@
require 'spec_helper'
module Spree
- describe Cart::Create do
+ describe Carts::Create do
subject { described_class }
let(:user) { create :user }
let(:store) { create :store, default_currency: 'EUR' }
let(:currency) { 'USD' }
- let(:public_metadata) { { prop1: 2 } }
- let(:private_metadata) { { prop2: 'val2' } }
+ let(:metadata) { { prop1: 2 } }
let(:expected) { Order.first }
context 'create an order' do
- let(:execute) { subject.call user: user, store: store, currency: currency, public_metadata: public_metadata, private_metadata: private_metadata }
+ let(:execute) { subject.call params: { user: user, store: store, currency: currency, metadata: metadata } }
let(:value) { execute.value }
it do
@@ -24,8 +23,7 @@ module Spree
end
context 'create an order with store currency' do
- let(:order_params) { { store: store, currency: nil } }
- let(:execute) { subject.call user: user, store: store, currency: currency, order_params: order_params }
+ let(:execute) { subject.call params: { user: user, store: store } }
let(:value) { execute.value }
it do
@@ -40,7 +38,7 @@ module Spree
end
context 'create an order with locale' do
- let(:execute) { subject.call user: user, store: store, currency: currency, locale: 'fr' }
+ let(:execute) { subject.call params: { user: user, store: store, currency: currency, locale: 'fr' } }
let(:value) { execute.value }
before do
@@ -55,7 +53,7 @@ module Spree
end
context 'create an order with default locale from Spree::Current' do
- let(:execute) { subject.call user: user, store: store, currency: currency }
+ let(:execute) { subject.call params: { user: user, store: store, currency: currency } }
let(:value) { execute.value }
before do
@@ -71,7 +69,7 @@ module Spree
context 'returns failure when no store is passed' do
let!(:default_store) { create :store, default: true }
- let(:execute) { subject.call user: user, store: nil, currency: nil }
+ let(:execute) { subject.call params: { user: user, store: nil } }
let(:value) { execute.value }
it do
@@ -91,14 +89,14 @@ module Spree
store.products << variant2.product unless store.products.include?(variant2.product)
end
- let(:line_items) do
+ let(:items) do
[
{ variant_id: variant.prefixed_id, quantity: 1 },
{ variant_id: variant2.prefixed_id, quantity: 2 }
]
end
- let(:execute) { subject.call user: user, store: store, currency: currency, line_items: line_items }
+ let(:execute) { subject.call params: { user: user, store: store, currency: currency, items: items } }
let(:value) { execute.value }
it 'creates order with line items' do
@@ -117,8 +115,8 @@ module Spree
store.products << variant.product unless store.products.include?(variant.product)
end
- let(:line_items) { [{ variant_id: variant.prefixed_id }] }
- let(:execute) { subject.call user: user, store: store, currency: currency, line_items: line_items }
+ let(:items) { [{ variant_id: variant.prefixed_id }] }
+ let(:execute) { subject.call params: { user: user, store: store, currency: currency, items: items } }
it 'defaults quantity to 1' do
expect(execute).to be_success
diff --git a/spree/core/spec/services/spree/carts/update_spec.rb b/spree/core/spec/services/spree/carts/update_spec.rb
new file mode 100644
index 0000000000..47b02f3160
--- /dev/null
+++ b/spree/core/spec/services/spree/carts/update_spec.rb
@@ -0,0 +1,354 @@
+require 'spec_helper'
+
+module Spree
+ RSpec.describe Carts::Update do
+ let(:store) { create(:store, supported_currencies: 'USD,EUR,GBP') }
+ let(:user) { create(:user) }
+ let(:order) { create(:order_with_line_items, user: user, store: store, currency: 'USD') }
+
+ describe '#call' do
+ subject { described_class.call(cart: order, params: params) }
+
+ describe 'updating email' do
+ let(:params) { { email: '[email protected]' } }
+
+ it 'updates the order email' do
+ expect(subject).to be_success
+ expect(order.reload.email).to eq('[email protected]')
+ end
+ end
+
+ describe 'updating special_instructions' do
+ let(:params) { { special_instructions: 'Leave at the door' } }
+
+ it 'updates the special instructions' do
+ expect(subject).to be_success
+ expect(order.reload.special_instructions).to eq('Leave at the door')
+ end
+
+ context 'when clearing special_instructions' do
+ let(:order) { create(:order_with_line_items, user: user, store: store, special_instructions: 'Existing instructions') }
+
+ it 'clears with empty string' do
+ result = described_class.call(cart: order, params: { special_instructions: '' })
+ expect(result).to be_success
+ expect(order.reload.special_instructions).to eq('')
+ end
+
+ it 'clears with nil' do
+ result = described_class.call(cart: order, params: { special_instructions: nil })
+ expect(result).to be_success
+ expect(order.reload.special_instructions).to be_nil
+ end
+ end
+ end
+
+ describe 'updating currency' do
+ context 'with supported currency' do
+ let(:params) { { currency: 'EUR' } }
+
+ it 'updates the currency' do
+ expect(subject).to be_success
+ expect(order.reload.currency).to eq('EUR')
+ end
+
+ it 'is case-insensitive' do
+ result = described_class.call(cart: order, params: { currency: 'eur' })
+ expect(result).to be_success
+ expect(order.reload.currency).to eq('EUR')
+ end
+ end
+
+ context 'with unsupported currency' do
+ let(:params) { { currency: 'JPY' } }
+
+ it 'returns failure' do
+ expect(subject).to be_failure
+ end
+
+ it 'does not change the currency' do
+ subject
+ expect(order.reload.currency).to eq('USD')
+ end
+ end
+ end
+
+ describe 'updating addresses' do
+ let(:country) { Spree::Country.find_by(iso: 'US') || create(:country, iso: 'US') }
+ let!(:state) { country.states.find_by(abbr: 'NY') || create(:state, country: country, abbr: 'NY', name: 'New York') }
+
+ shared_examples 'address update' do |address_type|
+ let(:address_key) { address_type }
+ let(:address_id_key) { :"#{address_type}_id" }
+
+ context 'with new address attributes' do
+ let(:params) do
+ {
+ address_key => {
+ firstname: 'John',
+ lastname: 'Doe',
+ address1: '123 Main St',
+ city: 'New York',
+ zipcode: '10001',
+ country_iso: 'US',
+ state_abbr: 'NY',
+ phone: '555-1234'
+ }
+ }
+ end
+
+ it 'creates a new address' do
+ expect(subject).to be_success
+ address = order.reload.public_send(address_key)
+ expect(address.firstname).to eq('John')
+ expect(address.lastname).to eq('Doe')
+ expect(address.address1).to eq('123 Main St')
+ expect(address.city).to eq('New York')
+ expect(address.zipcode).to eq('10001')
+ expect(address.country.iso).to eq('US')
+ expect(address.state.abbr).to eq('NY')
+ end
+
+ context 'when order has address checkout step and is past address state' do
+ let(:order) { create(:order_with_line_items, user: user, store: store, state: 'delivery') }
+
+ it 'reverts to address then auto-advances to payment' do
+ expect(subject).to be_success
+ expect(order.reload.state).to eq('payment')
+ end
+ end
+
+ context 'when order is in cart state' do
+ let(:order) { create(:order_with_line_items, user: user, store: store, state: 'cart') }
+
+ it 'auto-advances to payment' do
+ expect(subject).to be_success
+ expect(order.reload.state).to eq('payment')
+ end
+ end
+ end
+
+ context 'with existing address by nested id' do
+ let(:existing_address) { create(:address, user: user) }
+ let(:params) { { address_key => { id: existing_address.prefixed_id } } }
+
+ it 'uses the existing address' do
+ expect(subject).to be_success
+ expect(order.reload.public_send(address_id_key)).to eq(existing_address.id)
+ end
+ end
+
+ context 'with top-level address_id parameter' do
+ let(:existing_address) { create(:address, user: user) }
+ let(:params) { { address_id_key => existing_address.prefixed_id } }
+
+ it 'uses the existing address' do
+ expect(subject).to be_success
+ expect(order.reload.public_send(address_id_key)).to eq(existing_address.id)
+ end
+ end
+ end
+
+ describe 'ship_address' do
+ include_examples 'address update', :ship_address
+ end
+
+ describe 'bill_address' do
+ include_examples 'address update', :bill_address
+ end
+ end
+
+ describe 'address ownership' do
+ let(:other_user) { create(:user) }
+ let(:other_users_address) { create(:address, user: other_user) }
+
+ shared_examples 'ignores other users address' do |address_type|
+ context "when using another user's address for #{address_type}" do
+ let(:params) { { address_type => { id: other_users_address.prefixed_id } } }
+
+ it 'ignores the address and keeps original' do
+ original_address_id = order.public_send(:"#{address_type}_id")
+ expect(subject).to be_success
+ expect(order.reload.public_send(:"#{address_type}_id")).to eq(original_address_id)
+ expect(order.public_send(:"#{address_type}_id")).not_to eq(other_users_address.id)
+ end
+ end
+
+ context "when using another user's address via #{address_type}_id" do
+ let(:params) { { :"#{address_type}_id" => other_users_address.prefixed_id } }
+
+ it 'ignores the address and keeps original' do
+ original_address_id = order.public_send(:"#{address_type}_id")
+ expect(subject).to be_success
+ expect(order.reload.public_send(:"#{address_type}_id")).to eq(original_address_id)
+ expect(order.public_send(:"#{address_type}_id")).not_to eq(other_users_address.id)
+ end
+ end
+ end
+
+ include_examples 'ignores other users address', :ship_address
+ include_examples 'ignores other users address', :bill_address
+
+ context 'when order has no user (guest order)' do
+ let(:order) { create(:order_with_line_items, user: nil, store: store) }
+ let(:params) { { ship_address_id: other_users_address.prefixed_id } }
+
+ it 'ignores address_id params and keeps existing address' do
+ original_address_id = order.ship_address_id
+ expect(subject).to be_success
+ expect(order.reload.ship_address_id).to eq(original_address_id)
+ end
+ end
+ end
+
+ describe 'updating metadata' do
+ let(:params) { { metadata: { 'erp_id' => '12345', 'source' => 'mobile' } } }
+
+ it 'merges metadata into the order' do
+ expect(subject).to be_success
+ expect(order.reload.metadata).to include('erp_id' => '12345', 'source' => 'mobile')
+ end
+
+ context 'with existing metadata' do
+ before { order.update!(metadata: { 'existing_key' => 'existing_value' }) }
+
+ let(:params) { { metadata: { 'new_key' => 'new_value' } } }
+
+ it 'merges without removing existing keys' do
+ expect(subject).to be_success
+ expect(order.reload.metadata).to include('existing_key' => 'existing_value', 'new_key' => 'new_value')
+ end
+ end
+ end
+
+ describe 'updating multiple fields' do
+ let(:country) { Spree::Country.find_by(iso: 'US') || create(:country, iso: 'US') }
+ let!(:state) { country.states.find_by(abbr: 'NY') || create(:state, country: country, abbr: 'NY', name: 'New York') }
+
+ let(:params) do
+ {
+ email: '[email protected]',
+ special_instructions: 'Handle with care',
+ ship_address: {
+ firstname: 'John',
+ lastname: 'Doe',
+ address1: '123 Main St',
+ city: 'New York',
+ zipcode: '10001',
+ country_iso: 'US',
+ state_abbr: 'NY'
+ }
+ }
+ end
+
+ it 'updates all fields in a single transaction' do
+ expect(subject).to be_success
+ order.reload
+ expect(order.email).to eq('[email protected]')
+ expect(order.special_instructions).to eq('Handle with care')
+ expect(order.ship_address.firstname).to eq('John')
+ end
+ end
+
+ describe 'setting line items' do
+ let(:variant) { create(:variant) }
+
+ before do
+ variant.stock_items.first.update!(count_on_hand: 10)
+ store.products << variant.product unless store.products.include?(variant.product)
+ end
+
+ context 'with new line_items' do
+ let(:params) do
+ {
+ items: [
+ { variant_id: variant.prefixed_id, quantity: 2 }
+ ]
+ }
+ end
+
+ it 'adds line items to the order' do
+ expect(subject).to be_success
+ order.reload
+ line_item = order.line_items.find_by(variant: variant)
+ expect(line_item).to be_present
+ expect(line_item.quantity).to eq(2)
+ end
+ end
+
+ context 'with existing line item (upsert)' do
+ let!(:existing_line_item) { order.line_items.first }
+ let(:existing_variant) { existing_line_item.variant }
+
+ before do
+ store.products << existing_variant.product unless store.products.include?(existing_variant.product)
+ end
+
+ let(:params) do
+ {
+ items: [
+ { variant_id: existing_variant.prefixed_id, quantity: 7 }
+ ]
+ }
+ end
+
+ it 'sets quantity instead of incrementing' do
+ expect(subject).to be_success
+ expect(existing_line_item.reload.quantity).to eq(7)
+ end
+ end
+
+ context 'with invalid variant_id' do
+ let(:params) do
+ {
+ items: [
+ { variant_id: 'variant_invalid999', quantity: 1 }
+ ]
+ }
+ end
+
+ it 'raises RecordNotFound with variant details' do
+ expect { subject }.to raise_error(ActiveRecord::RecordNotFound) do |error|
+ expect(error.model).to eq('Spree::Variant')
+ expect(error.message).to include('variant_invalid999')
+ end
+ end
+ end
+ end
+
+ describe 'error handling' do
+ context 'with invalid address prefix_id' do
+ let(:params) { { ship_address_id: 'addr_invalid123' } }
+
+ it 'succeeds but does not change the address' do
+ original_address_id = order.ship_address_id
+ expect(subject).to be_success
+ expect(order.reload.ship_address_id).to eq(original_address_id)
+ end
+ end
+
+ context 'when order save fails' do
+ let(:params) { { email: '[email protected]' } }
+
+ before do
+ allow(order).to receive(:save!).and_raise(ActiveRecord::RecordInvalid.new(order))
+ end
+
+ it 'returns failure with error message' do
+ expect(subject).to be_failure
+ end
+ end
+ end
+
+ describe 'parameter normalization' do
+ let(:params) { { 'email' => '[email protected]' } }
+
+ it 'handles string keys' do
+ expect(subject).to be_success
+ expect(order.reload.email).to eq('[email protected]')
+ end
+ end
+
+ end
+ end
+end
diff --git a/spree/core/spec/services/spree/cart/upsert_items_spec.rb b/spree/core/spec/services/spree/carts/upsert_items_spec.rb
similarity index 67%
rename from spree/core/spec/services/spree/cart/upsert_items_spec.rb
rename to spree/core/spec/services/spree/carts/upsert_items_spec.rb
index 6582c62f4c..9004925379 100644
--- a/spree/core/spec/services/spree/cart/upsert_items_spec.rb
+++ b/spree/core/spec/services/spree/carts/upsert_items_spec.rb
@@ -1,10 +1,10 @@
require 'spec_helper'
module Spree
- RSpec.describe Cart::UpsertItems do
+ RSpec.describe Carts::UpsertItems do
let(:store) { create(:store) }
let(:user) { create(:user) }
- let(:order) { create(:order, user: user, store: store) }
+ let(:cart) { create(:cart, user: user, store: store) }
let(:variant) { create(:variant) }
let(:variant2) { create(:variant) }
@@ -16,10 +16,10 @@ module Spree
end
describe '#call' do
- subject { described_class.call(order: order, line_items: line_items) }
+ subject { described_class.call(cart: cart, items: items) }
- context 'with empty line_items' do
- let(:line_items) { [] }
+ context 'with empty items' do
+ let(:items) { [] }
it 'returns success without changes' do
expect(subject).to be_success
@@ -27,7 +27,7 @@ module Spree
end
context 'creating new line items' do
- let(:line_items) do
+ let(:items) do
[
{ variant_id: variant.prefixed_id, quantity: 2 },
{ variant_id: variant2.prefixed_id, quantity: 3 }
@@ -36,16 +36,16 @@ module Spree
it 'creates line items with correct quantities' do
expect(subject).to be_success
- order.reload
- expect(order.line_items.find_by(variant: variant).quantity).to eq(2)
- expect(order.line_items.find_by(variant: variant2).quantity).to eq(3)
+ cart.reload
+ expect(cart.items.find_by(variant: variant).quantity).to eq(2)
+ expect(cart.items.find_by(variant: variant2).quantity).to eq(3)
end
end
context 'upserting existing line items' do
- let!(:existing_line_item) { create(:line_item, order: order, variant: variant, quantity: 5) }
+ let!(:existing_line_item) { create(:line_item, order: cart, variant: variant, quantity: 5) }
- let(:line_items) do
+ let(:items) do
[{ variant_id: variant.prefixed_id, quantity: 2 }]
end
@@ -56,9 +56,9 @@ module Spree
end
context 'mix of new and existing line items' do
- let!(:existing_line_item) { create(:line_item, order: order, variant: variant, quantity: 5) }
+ let!(:existing_line_item) { create(:line_item, order: cart, variant: variant, quantity: 5) }
- let(:line_items) do
+ let(:items) do
[
{ variant_id: variant.prefixed_id, quantity: 1 },
{ variant_id: variant2.prefixed_id, quantity: 4 }
@@ -67,35 +67,35 @@ module Spree
it 'updates existing and creates new' do
expect(subject).to be_success
- order.reload
+ cart.reload
expect(existing_line_item.reload.quantity).to eq(1)
- expect(order.line_items.find_by(variant: variant2).quantity).to eq(4)
+ expect(cart.items.find_by(variant: variant2).quantity).to eq(4)
end
end
context 'with default quantity' do
- let(:line_items) { [{ variant_id: variant.prefixed_id }] }
+ let(:items) { [{ variant_id: variant.prefixed_id }] }
it 'defaults quantity to 1' do
expect(subject).to be_success
- expect(order.line_items.find_by(variant: variant).quantity).to eq(1)
+ expect(cart.items.find_by(variant: variant).quantity).to eq(1)
end
end
context 'with metadata' do
- let(:line_items) do
+ let(:items) do
[{ variant_id: variant.prefixed_id, quantity: 1, metadata: { 'gift' => true } }]
end
it 'sets metadata on new line item' do
expect(subject).to be_success
- expect(order.line_items.find_by(variant: variant).metadata).to include('gift' => true)
+ expect(cart.items.find_by(variant: variant).metadata).to include('gift' => true)
end
context 'merging metadata on existing line item' do
- let!(:existing_line_item) { create(:line_item, order: order, variant: variant, quantity: 1, private_metadata: { 'existing' => 'val' }) }
+ let!(:existing_line_item) { create(:line_item, order: cart, variant: variant, quantity: 1, private_metadata: { 'existing' => 'val' }) }
- let(:line_items) do
+ let(:items) do
[{ variant_id: variant.prefixed_id, quantity: 2, metadata: { 'new_key' => 'new_val' } }]
end
@@ -107,7 +107,7 @@ module Spree
end
context 'with invalid variant_id' do
- let(:line_items) do
+ let(:items) do
[{ variant_id: 'variant_invalid999', quantity: 1 }]
end
@@ -119,8 +119,8 @@ module Spree
end
end
- context 'with nil line_items' do
- let(:line_items) { nil }
+ context 'with nil items' do
+ let(:items) { nil }
it 'returns success without changes' do
expect(subject).to be_success
@@ -128,26 +128,26 @@ module Spree
end
context 'with blank variant_id in entry' do
- let(:line_items) { [{ variant_id: '', quantity: 1 }] }
+ let(:items) { [{ variant_id: '', quantity: 1 }] }
it 'skips the entry and returns success' do
expect(subject).to be_success
- expect(order.line_items.count).to eq(0)
+ expect(cart.items.count).to eq(0)
end
end
context 'with nil variant_id in entry' do
- let(:line_items) { [{ variant_id: nil, quantity: 1 }] }
+ let(:items) { [{ variant_id: nil, quantity: 1 }] }
it 'skips the entry and returns success' do
expect(subject).to be_success
- expect(order.line_items.count).to eq(0)
+ expect(cart.items.count).to eq(0)
end
end
- context 'with variant not available in order currency' do
- let(:order) { create(:order, user: user, store: store, currency: 'GBP') }
- let(:line_items) { [{ variant_id: variant.prefixed_id, quantity: 1 }] }
+ context 'with variant not available in cart currency' do
+ let(:cart) { create(:cart, user: user, store: store, currency: 'GBP') }
+ let(:items) { [{ variant_id: variant.prefixed_id, quantity: 1 }] }
it 'returns failure with message' do
expect(subject).to be_failure
@@ -164,7 +164,7 @@ module Spree
other_store.products << other_variant.product
end
- let(:line_items) { [{ variant_id: other_variant.prefixed_id, quantity: 1 }] }
+ let(:items) { [{ variant_id: other_variant.prefixed_id, quantity: 1 }] }
it 'raises RecordNotFound with variant details' do
expect { subject }.to raise_error(ActiveRecord::RecordNotFound) do |error|
@@ -175,18 +175,18 @@ module Spree
end
context 'with string keys in params' do
- let(:line_items) do
+ let(:items) do
[{ 'variant_id' => variant.prefixed_id, 'quantity' => 3 }]
end
it 'handles string keys' do
expect(subject).to be_success
- expect(order.line_items.find_by(variant: variant).quantity).to eq(3)
+ expect(cart.items.find_by(variant: variant).quantity).to eq(3)
end
end
- context 'with duplicate variant in line_items array' do
- let(:line_items) do
+ context 'with duplicate variant in items array' do
+ let(:items) do
[
{ variant_id: variant.prefixed_id, quantity: 2 },
{ variant_id: variant.prefixed_id, quantity: 5 }
@@ -195,39 +195,39 @@ module Spree
it 'last entry wins' do
expect(subject).to be_success
- expect(order.line_items.where(variant: variant).count).to eq(1)
- expect(order.line_items.find_by(variant: variant).quantity).to eq(5)
+ expect(cart.items.where(variant: variant).count).to eq(1)
+ expect(cart.items.find_by(variant: variant).quantity).to eq(5)
end
end
context 'sets correct price from variant' do
- let(:line_items) { [{ variant_id: variant.prefixed_id, quantity: 1 }] }
+ let(:items) { [{ variant_id: variant.prefixed_id, quantity: 1 }] }
it 'line item price matches variant price' do
expect(subject).to be_success
- line_item = order.line_items.find_by(variant: variant)
+ line_item = cart.items.find_by(variant: variant)
expect(line_item.price).to eq(variant.price)
end
end
- context 'recalculates order totals' do
- let(:line_items) do
+ context 'recalculates cart totals' do
+ let(:items) do
[
{ variant_id: variant.prefixed_id, quantity: 2 },
{ variant_id: variant2.prefixed_id, quantity: 1 }
]
end
- it 'updates order item_total' do
+ it 'updates cart item_total' do
expect(subject).to be_success
- order.reload
+ cart.reload
expected_total = (variant.price * 2) + variant2.price
- expect(order.item_total).to eq(expected_total)
+ expect(cart.item_total).to eq(expected_total)
end
end
context 'rolls back on failure mid-batch' do
- let(:line_items) do
+ let(:items) do
[
{ variant_id: variant.prefixed_id, quantity: 1 },
{ variant_id: 'variant_doesnotexist', quantity: 1 }
@@ -236,14 +236,14 @@ module Spree
it 'does not persist partial changes' do
expect { subject }.to raise_error(ActiveRecord::RecordNotFound)
- expect(order.reload.line_items.find_by(variant: variant)).to be_nil
+ expect(cart.reload.items.find_by(variant: variant)).to be_nil
end
end
context 'does not touch unrelated existing line items' do
- let!(:unrelated_line_item) { create(:line_item, order: order, variant: variant, quantity: 3) }
+ let!(:unrelated_line_item) { create(:line_item, order: cart, variant: variant, quantity: 3) }
- let(:line_items) do
+ let(:items) do
[{ variant_id: variant2.prefixed_id, quantity: 1 }]
end
diff --git a/spree/core/spec/services/spree/checkout/update_spec.rb b/spree/core/spec/services/spree/checkout/update_spec.rb
index 95a3883856..52be391475 100644
--- a/spree/core/spec/services/spree/checkout/update_spec.rb
+++ b/spree/core/spec/services/spree/checkout/update_spec.rb
@@ -1,354 +1,347 @@
require 'spec_helper'
-module Spree
- RSpec.describe Checkout::Update do
- let(:store) { create(:store, supported_currencies: 'USD,EUR,GBP') }
- let(:user) { create(:user) }
- let(:order) { create(:order_with_line_items, user: user, store: store, currency: 'USD') }
+describe Spree::Checkout::Update, type: :service do
+ describe '#transform_address_params' do
+ let!(:state) { create(:state) }
+ let!(:country) { state.country }
+ let!(:replace_country) { described_class.new }
+ let!(:address) do
+ {
+ firstname: 'John',
+ lastname: 'Doe',
+ address1: '7735 Old Georgetown Road',
+ city: 'Bethesda',
+ phone: '3014445002',
+ zipcode: '20814',
+ state_id: state.id,
+ country_iso: country.iso
+ }
+ end
- describe '#call' do
- subject { described_class.call(order: order, params: params) }
+ context 'with ship_address order params' do
+ let(:order_params) do
+ ActionController::Parameters.new(
+ order: {
+ ship_address_attributes: address
+ }
+ )
+ end
+ let(:result) { replace_country.send(:replace_country_iso_with_id, order_params[:order][:ship_address_attributes]) }
- describe 'updating email' do
- let(:params) { { email: '[email protected]' } }
+ before { result }
- it 'updates the order email' do
- expect(subject).to be_success
- expect(order.reload.email).to eq('[email protected]')
- end
+ it 'will return hash contain country_id' do
+ expect(result[:country_id]).to eq country.id
end
- describe 'updating special_instructions' do
- let(:params) { { special_instructions: 'Leave at the door' } }
+ it 'will return hash without country_iso' do
+ expect(result).not_to include(:country_iso)
+ end
+ end
- it 'updates the special instructions' do
- expect(subject).to be_success
- expect(order.reload.special_instructions).to eq('Leave at the door')
- end
+ context 'with bill_address order params' do
+ let(:order_params) do
+ ActionController::Parameters.new(
+ order: {
+ bill_address_attributes: address
+ }
+ )
+ end
+ let(:result) { replace_country.send(:replace_country_iso_with_id, order_params[:order][:bill_address_attributes]) }
- context 'when clearing special_instructions' do
- let(:order) { create(:order_with_line_items, user: user, store: store, special_instructions: 'Existing instructions') }
+ before { result }
- it 'clears with empty string' do
- result = described_class.call(order: order, params: { special_instructions: '' })
- expect(result).to be_success
- expect(order.reload.special_instructions).to eq('')
- end
+ it 'will return hash contain country_id' do
+ expect(result[:country_id]).to eq country.id
+ end
- it 'clears with nil' do
- result = described_class.call(order: order, params: { special_instructions: nil })
- expect(result).to be_success
- expect(order.reload.special_instructions).to be_nil
- end
- end
+ it 'will return hash without country_iso' do
+ expect(result).not_to include(:country_iso)
end
+ end
+ end
+
+ describe 'update address' do
+ let(:user) { create(:user_with_addresses) }
+ let(:order) { create(:order_with_line_items, user: user, bill_address: user.bill_address, ship_address: user.ship_address, state: order_state) }
+ let(:state) { create(:state) }
+ let(:country) { state.country }
+ let(:update_service) { described_class.call(order: order, params: order_params, permitted_attributes: permitted_attributes, request_env: nil) }
+ let(:order_params) { ActionController::Parameters.new(order: {
+ ship_address_id: ship_address_id,
+ bill_address_id: bill_address_id,
+ ship_address_attributes: address_attributes
+ }) }
+ let(:permitted_attributes) do
+ Spree::PermittedAttributes.checkout_attributes + [
+ bill_address_attributes: Spree::PermittedAttributes.address_attributes,
+ ship_address_attributes: Spree::PermittedAttributes.address_attributes
+ ]
+ end
- describe 'updating currency' do
- context 'with supported currency' do
- let(:params) { { currency: 'EUR' } }
+ context 'at cart state' do
+ let(:order_state) { 'cart' }
+ let(:ship_address_id) { nil }
+ let(:bill_address_id) { nil }
+ let(:address_attributes) do
+ {
+ firstname: 'John',
+ lastname: 'Doe',
+ address1: '7735 Old Georgetown Road',
+ city: 'Bethesda',
+ phone: '3014445002',
+ zipcode: '20814',
+ state_id: state.id,
+ country_iso: country.iso
+ }
+ end
- it 'updates the currency' do
- expect(subject).to be_success
- expect(order.reload.currency).to eq('EUR')
- end
+ it 'should set order back to address state' do
+ expect(order.state).not_to eq 'address'
+ expect(order.ship_address.state.id).not_to eq state.id
- it 'is case-insensitive' do
- result = described_class.call(order: order, params: { currency: 'eur' })
- expect(result).to be_success
- expect(order.reload.currency).to eq('EUR')
- end
- end
+ update_service
- context 'with unsupported currency' do
- let(:params) { { currency: 'JPY' } }
+ expect(order.state).to eq 'address'
+ expect(order.ship_address.state.id).to eq state.id
+ end
- it 'returns failure' do
- expect(subject).to be_failure
- end
+ it 'should not set order back to address state if do_not_change_state is true' do
+ expect(order.state).not_to eq 'address'
+ order_params[:do_not_change_state] = true
+ update_service
- it 'does not change the currency' do
- subject
- expect(order.reload.currency).to eq('USD')
- end
- end
+ expect(order.state).not_to eq 'address'
end
- describe 'updating addresses' do
- let(:country) { Spree::Country.find_by(iso: 'US') || create(:country, iso: 'US') }
- let!(:state) { country.states.find_by(abbr: 'NY') || create(:state, country: country, abbr: 'NY', name: 'New York') }
-
- shared_examples 'address update' do |address_type|
- let(:address_key) { address_type }
- let(:address_id_key) { :"#{address_type}_id" }
-
- context 'with new address attributes' do
- let(:params) do
- {
- address_key => {
- firstname: 'John',
- lastname: 'Doe',
- address1: '123 Main St',
- city: 'New York',
- zipcode: '10001',
- country_iso: 'US',
- state_abbr: 'NY',
- phone: '555-1234'
- }
- }
- end
-
- it 'creates a new address' do
- expect(subject).to be_success
- address = order.reload.public_send(address_key)
- expect(address.firstname).to eq('John')
- expect(address.lastname).to eq('Doe')
- expect(address.address1).to eq('123 Main St')
- expect(address.city).to eq('New York')
- expect(address.zipcode).to eq('10001')
- expect(address.country.iso).to eq('US')
- expect(address.state.abbr).to eq('NY')
- end
-
- context 'when order has address checkout step and is past address state' do
- let(:order) { create(:order_with_line_items, user: user, store: store, state: 'delivery') }
-
- it 'reverts to address then auto-advances to payment' do
- expect(subject).to be_success
- expect(order.reload.state).to eq('payment')
- end
- end
-
- context 'when order is in cart state' do
- let(:order) { create(:order_with_line_items, user: user, store: store, state: 'cart') }
-
- it 'auto-advances to payment' do
- expect(subject).to be_success
- expect(order.reload.state).to eq('payment')
- end
- end
- end
-
- context 'with existing address by nested id' do
- let(:existing_address) { create(:address, user: user) }
- let(:params) { { address_key => { id: existing_address.prefixed_id } } }
-
- it 'uses the existing address' do
- expect(subject).to be_success
- expect(order.reload.public_send(address_id_key)).to eq(existing_address.id)
- end
- end
-
- context 'with top-level address_id parameter' do
- let(:existing_address) { create(:address, user: user) }
- let(:params) { { address_id_key => existing_address.prefixed_id } }
-
- it 'uses the existing address' do
- expect(subject).to be_success
- expect(order.reload.public_send(address_id_key)).to eq(existing_address.id)
- end
- end
- end
+ it 'should set order back to address state if quick checkout cancelled' do
+ expect(order.state).not_to eq 'address'
+ order_params[:order][:ship_address_id] = 'CLEAR'
+ update_service
- describe 'ship_address' do
- include_examples 'address update', :ship_address
- end
+ expect(order.state).to eq 'address'
+ end
+ end
- describe 'bill_address' do
- include_examples 'address update', :bill_address
+ context 'at address state' do
+ let(:order_state) { 'address' }
+ let(:ship_address_id) { order.ship_address_id }
+ let(:bill_address_id) { order.bill_address_id }
+ let(:address_attributes) { nil }
+ let(:address) { create(:address, user: user) }
+
+ shared_examples 'user default addresses did not change' do
+ it 'does not change user default addresses' do
+ update_service
+
+ expect(user.reload.bill_address_id).not_to eq order.reload.bill_address
+ expect(user.reload.bill_address_id).not_to eq order.reload.ship_address
+ expect(user.reload.ship_address_id).not_to eq order.reload.bill_address
+ expect(user.reload.ship_address_id).not_to eq order.reload.ship_address
end
end
- describe 'address ownership' do
- let(:other_user) { create(:user) }
- let(:other_users_address) { create(:address, user: other_user) }
-
- shared_examples 'ignores other users address' do |address_type|
- context "when using another user's address for #{address_type}" do
- let(:params) { { address_type => { id: other_users_address.prefixed_id } } }
-
- it 'ignores the address and keeps original' do
- original_address_id = order.public_send(:"#{address_type}_id")
- expect(subject).to be_success
- expect(order.reload.public_send(:"#{address_type}_id")).to eq(original_address_id)
- expect(order.public_send(:"#{address_type}_id")).not_to eq(other_users_address.id)
- end
- end
-
- context "when using another user's address via #{address_type}_id" do
- let(:params) { { :"#{address_type}_id" => other_users_address.prefixed_id } }
-
- it 'ignores the address and keeps original' do
- original_address_id = order.public_send(:"#{address_type}_id")
- expect(subject).to be_success
- expect(order.reload.public_send(:"#{address_type}_id")).to eq(original_address_id)
- expect(order.public_send(:"#{address_type}_id")).not_to eq(other_users_address.id)
- end
- end
+ shared_examples 'checkout is in address step' do
+ it 'keeps checkout in address step' do
+ update_service
+
+ expect(order.reload.state).to eq 'address'
end
+ end
- include_examples 'ignores other users address', :ship_address
- include_examples 'ignores other users address', :bill_address
+ context 'when address did not change' do
+ it_behaves_like 'user default addresses did not change'
+ it_behaves_like 'checkout is in address step'
- context 'when order has no user (guest order)' do
- let(:order) { create(:order_with_line_items, user: nil, store: store) }
- let(:params) { { ship_address_id: other_users_address.prefixed_id } }
+ it 'does not change order addresses' do
+ expect(update_service).to be_success
- it 'ignores address_id params and keeps existing address' do
- original_address_id = order.ship_address_id
- expect(subject).to be_success
- expect(order.reload.ship_address_id).to eq(original_address_id)
- end
+ expect(order.reload.bill_address_id).to eq user.bill_address_id
+ expect(order.reload.ship_address_id).to eq user.ship_address_id
end
end
- describe 'updating metadata' do
- let(:params) { { metadata: { 'erp_id' => '12345', 'source' => 'mobile' } } }
+ context 'when ship address changed' do
+ let(:ship_address_id) { address.id }
- it 'merges metadata into the order' do
- expect(subject).to be_success
- expect(order.reload.metadata).to include('erp_id' => '12345', 'source' => 'mobile')
+ it_behaves_like 'user default addresses did not change'
+ it_behaves_like 'checkout is in address step'
+
+ it 'should update order ship address' do
+ expect(update_service).to be_success
+ expect(order.reload.bill_address_id).to eq user.bill_address_id
+ expect(order.reload.ship_address_id).to eq address.id
end
+ end
- context 'with existing metadata' do
- before { order.update!(metadata: { 'existing_key' => 'existing_value' }) }
+ context 'when bill address changed' do
+ let(:bill_address_id) { address.id }
- let(:params) { { metadata: { 'new_key' => 'new_value' } } }
+ it_behaves_like 'user default addresses did not change'
+ it_behaves_like 'checkout is in address step'
- it 'merges without removing existing keys' do
- expect(subject).to be_success
- expect(order.reload.metadata).to include('existing_key' => 'existing_value', 'new_key' => 'new_value')
- end
+ it 'should update order bill address' do
+ expect(update_service).to be_success
+ expect(order.reload.bill_address_id).to eq address.id
+ expect(order.reload.ship_address_id).to eq user.ship_address_id
end
end
- describe 'updating multiple fields' do
- let(:country) { Spree::Country.find_by(iso: 'US') || create(:country, iso: 'US') }
- let!(:state) { country.states.find_by(abbr: 'NY') || create(:state, country: country, abbr: 'NY', name: 'New York') }
+ context 'when ship and bill address changed' do
+ let(:ship_address_id) { address.id }
+ let(:bill_address_id) { address.id }
- let(:params) do
- {
- email: '[email protected]',
- special_instructions: 'Handle with care',
- ship_address: {
- firstname: 'John',
- lastname: 'Doe',
- address1: '123 Main St',
- city: 'New York',
- zipcode: '10001',
- country_iso: 'US',
- state_abbr: 'NY'
- }
- }
- end
+ it_behaves_like 'user default addresses did not change'
+ it_behaves_like 'checkout is in address step'
- it 'updates all fields in a single transaction' do
- expect(subject).to be_success
- order.reload
- expect(order.email).to eq('[email protected]')
- expect(order.special_instructions).to eq('Handle with care')
- expect(order.ship_address.firstname).to eq('John')
+ it 'should update both order addresses' do
+ expect(update_service).to be_success
+ expect(order.reload.bill_address_id).to eq address.id
+ expect(order.reload.ship_address_id).to eq address.id
end
end
+ end
+ end
- describe 'setting line items' do
- let(:variant) { create(:variant) }
+ describe 'address ownership validation' do
+ let(:user) { create(:user_with_addresses) }
+ let(:other_user) { create(:user_with_addresses) }
+ let(:order) { create(:order_with_line_items, user: user, state: 'address') }
+ let(:permitted_attributes) do
+ Spree::PermittedAttributes.checkout_attributes + [
+ bill_address_attributes: Spree::PermittedAttributes.address_attributes,
+ ship_address_attributes: Spree::PermittedAttributes.address_attributes
+ ]
+ end
- before do
- variant.stock_items.first.update!(count_on_hand: 10)
- store.products << variant.product unless store.products.include?(variant.product)
- end
+ context 'when bill_address_attributes contains id of another user address' do
+ let(:other_user_address) { other_user.bill_address }
+ let(:order_params) do
+ ActionController::Parameters.new(
+ order: {
+ bill_address_attributes: { id: other_user_address.id }
+ }
+ )
+ end
- context 'with new line_items' do
- let(:params) do
- {
- line_items: [
- { variant_id: variant.prefixed_id, quantity: 2 }
- ]
- }
- end
-
- it 'adds line items to the order' do
- expect(subject).to be_success
- order.reload
- line_item = order.line_items.find_by(variant: variant)
- expect(line_item).to be_present
- expect(line_item.quantity).to eq(2)
- end
- end
+ it 'returns failure' do
+ result = described_class.call(order: order, params: order_params, permitted_attributes: permitted_attributes, request_env: nil)
+ expect(result).to be_failure
+ end
- context 'with existing line item (upsert)' do
- let!(:existing_line_item) { order.line_items.first }
- let(:existing_variant) { existing_line_item.variant }
+ it 'does not associate the other user address with the order' do
+ described_class.call(order: order, params: order_params, permitted_attributes: permitted_attributes, request_env: nil)
+ expect(order.reload.bill_address_id).not_to eq other_user_address.id
+ end
+ end
- before do
- store.products << existing_variant.product unless store.products.include?(existing_variant.product)
- end
+ context 'when ship_address_attributes contains id of another user address' do
+ let(:other_user_address) { other_user.ship_address }
+ let(:order_params) do
+ ActionController::Parameters.new(
+ order: {
+ ship_address_attributes: { id: other_user_address.id }
+ }
+ )
+ end
- let(:params) do
- {
- line_items: [
- { variant_id: existing_variant.prefixed_id, quantity: 7 }
- ]
- }
- end
+ it 'returns failure' do
+ result = described_class.call(order: order, params: order_params, permitted_attributes: permitted_attributes, request_env: nil)
+ expect(result).to be_failure
+ end
- it 'sets quantity instead of incrementing' do
- expect(subject).to be_success
- expect(existing_line_item.reload.quantity).to eq(7)
- end
- end
+ it 'does not associate the other user address with the order' do
+ described_class.call(order: order, params: order_params, permitted_attributes: permitted_attributes, request_env: nil)
+ expect(order.reload.ship_address_id).not_to eq other_user_address.id
+ end
+ end
- context 'with invalid variant_id' do
- let(:params) do
- {
- line_items: [
- { variant_id: 'variant_invalid999', quantity: 1 }
- ]
- }
- end
-
- it 'raises RecordNotFound with variant details' do
- expect { subject }.to raise_error(ActiveRecord::RecordNotFound) do |error|
- expect(error.model).to eq('Spree::Variant')
- expect(error.message).to include('variant_invalid999')
- end
- end
- end
+ context 'when address_attributes contains id of the same user address' do
+ let(:user_address) { create(:address, user: user) }
+ let(:order_params) do
+ ActionController::Parameters.new(
+ order: {
+ bill_address_attributes: { id: user_address.id }
+ }
+ )
end
- describe 'error handling' do
- context 'with invalid address prefix_id' do
- let(:params) { { ship_address_id: 'addr_invalid123' } }
+ it 'returns success' do
+ result = described_class.call(order: order, params: order_params, permitted_attributes: permitted_attributes, request_env: nil)
+ expect(result).to be_success
+ end
+ end
- it 'succeeds but does not change the address' do
- original_address_id = order.ship_address_id
- expect(subject).to be_success
- expect(order.reload.ship_address_id).to eq(original_address_id)
- end
- end
+ context 'when address_attributes contains id of address with no user' do
+ let(:guest_address) { create(:address, user: nil) }
+ let(:order_params) do
+ ActionController::Parameters.new(
+ order: {
+ bill_address_attributes: { id: guest_address.id }
+ }
+ )
+ end
- context 'when order save fails' do
- let(:params) { { email: '[email protected]' } }
+ it 'returns success' do
+ result = described_class.call(order: order, params: order_params, permitted_attributes: permitted_attributes, request_env: nil)
+ expect(result).to be_success
+ end
+ end
- before do
- allow(order).to receive(:save!).and_raise(ActiveRecord::RecordInvalid.new(order))
- end
+ context 'when address_attributes does not contain id' do
+ let(:state) { create(:state) }
+ let(:country) { state.country }
+ let(:order_params) do
+ ActionController::Parameters.new(
+ order: {
+ bill_address_attributes: {
+ firstname: 'John',
+ lastname: 'Doe',
+ address1: '123 Main St',
+ city: 'Anytown',
+ zipcode: '12345',
+ country_iso: country.iso,
+ state_id: state.id,
+ phone: '555-1234'
+ }
+ }
+ )
+ end
- it 'returns failure with error message' do
- expect(subject).to be_failure
- end
- end
+ it 'returns success' do
+ result = described_class.call(order: order, params: order_params, permitted_attributes: permitted_attributes, request_env: nil)
+ expect(result).to be_success
end
+ end
+ end
+
+ describe 'update selected shipping rate' do
+ let(:update_service) { described_class.new }
+ let(:order) { create(:order_with_line_items) }
+ let(:order_params) do
+ ActionController::Parameters.new(
+ order: {
+ shipments_attributes: [
+ {
+ id: order.shipments.first.id,
+ selected_shipping_rate_id: order.shipments.first.shipping_rates.first.id
+ }
+ ]
+ }
+ )
+ end
+ let(:permitted_attributes) do
+ Spree::PermittedAttributes.checkout_attributes + [
+ shipments_attributes: Spree::PermittedAttributes.shipment_attributes
+ ]
+ end
- describe 'parameter normalization' do
- let(:params) { { 'email' => '[email protected]' } }
+ it 'should set order back to delivery state' do
+ expect(order.state).not_to eq 'delivery'
- it 'handles string keys' do
- expect(subject).to be_success
- expect(order.reload.email).to eq('[email protected]')
- end
- end
+ update_service.send(:call, order: order, params: order_params, permitted_attributes: permitted_attributes, request_env: nil)
+ expect(order.state).to eq 'delivery'
end
end
end
diff --git a/spree/core/spec/services/spree/checkout/v2_update_spec.rb b/spree/core/spec/services/spree/checkout/v2_update_spec.rb
deleted file mode 100644
index 2827ba73da..0000000000
--- a/spree/core/spec/services/spree/checkout/v2_update_spec.rb
+++ /dev/null
@@ -1,347 +0,0 @@
-require 'spec_helper'
-
-describe Spree::Checkout::V2Update, type: :service do
- describe '#transform_address_params' do
- let!(:state) { create(:state) }
- let!(:country) { state.country }
- let!(:replace_country) { described_class.new }
- let!(:address) do
- {
- firstname: 'John',
- lastname: 'Doe',
- address1: '7735 Old Georgetown Road',
- city: 'Bethesda',
- phone: '3014445002',
- zipcode: '20814',
- state_id: state.id,
- country_iso: country.iso
- }
- end
-
- context 'with ship_address order params' do
- let(:order_params) do
- ActionController::Parameters.new(
- order: {
- ship_address_attributes: address
- }
- )
- end
- let(:result) { replace_country.send(:replace_country_iso_with_id, order_params[:order][:ship_address_attributes]) }
-
- before { result }
-
- it 'will return hash contain country_id' do
- expect(result[:country_id]).to eq country.id
- end
-
- it 'will return hash without country_iso' do
- expect(result).not_to include(:country_iso)
- end
- end
-
- context 'with bill_address order params' do
- let(:order_params) do
- ActionController::Parameters.new(
- order: {
- bill_address_attributes: address
- }
- )
- end
- let(:result) { replace_country.send(:replace_country_iso_with_id, order_params[:order][:bill_address_attributes]) }
-
- before { result }
-
- it 'will return hash contain country_id' do
- expect(result[:country_id]).to eq country.id
- end
-
- it 'will return hash without country_iso' do
- expect(result).not_to include(:country_iso)
- end
- end
- end
-
- describe 'update address' do
- let(:user) { create(:user_with_addresses) }
- let(:order) { create(:order_with_line_items, user: user, bill_address: user.bill_address, ship_address: user.ship_address, state: order_state) }
- let(:state) { create(:state) }
- let(:country) { state.country }
- let(:update_service) { described_class.call(order: order, params: order_params, permitted_attributes: permitted_attributes, request_env: nil) }
- let(:order_params) { ActionController::Parameters.new(order: {
- ship_address_id: ship_address_id,
- bill_address_id: bill_address_id,
- ship_address_attributes: address_attributes
- }) }
- let(:permitted_attributes) do
- Spree::PermittedAttributes.checkout_attributes + [
- bill_address_attributes: Spree::PermittedAttributes.address_attributes,
- ship_address_attributes: Spree::PermittedAttributes.address_attributes
- ]
- end
-
- context 'at cart state' do
- let(:order_state) { 'cart' }
- let(:ship_address_id) { nil }
- let(:bill_address_id) { nil }
- let(:address_attributes) do
- {
- firstname: 'John',
- lastname: 'Doe',
- address1: '7735 Old Georgetown Road',
- city: 'Bethesda',
- phone: '3014445002',
- zipcode: '20814',
- state_id: state.id,
- country_iso: country.iso
- }
- end
-
- it 'should set order back to address state' do
- expect(order.state).not_to eq 'address'
- expect(order.ship_address.state.id).not_to eq state.id
-
- update_service
-
- expect(order.state).to eq 'address'
- expect(order.ship_address.state.id).to eq state.id
- end
-
- it 'should not set order back to address state if do_not_change_state is true' do
- expect(order.state).not_to eq 'address'
- order_params[:do_not_change_state] = true
- update_service
-
- expect(order.state).not_to eq 'address'
- end
-
- it 'should set order back to address state if quick checkout cancelled' do
- expect(order.state).not_to eq 'address'
- order_params[:order][:ship_address_id] = 'CLEAR'
- update_service
-
- expect(order.state).to eq 'address'
- end
- end
-
- context 'at address state' do
- let(:order_state) { 'address' }
- let(:ship_address_id) { order.ship_address_id }
- let(:bill_address_id) { order.bill_address_id }
- let(:address_attributes) { nil }
- let(:address) { create(:address, user: user) }
-
- shared_examples 'user default addresses did not change' do
- it 'does not change user default addresses' do
- update_service
-
- expect(user.reload.bill_address_id).not_to eq order.reload.bill_address
- expect(user.reload.bill_address_id).not_to eq order.reload.ship_address
- expect(user.reload.ship_address_id).not_to eq order.reload.bill_address
- expect(user.reload.ship_address_id).not_to eq order.reload.ship_address
- end
- end
-
- shared_examples 'checkout is in address step' do
- it 'keeps checkout in address step' do
- update_service
-
- expect(order.reload.state).to eq 'address'
- end
- end
-
- context 'when address did not change' do
- it_behaves_like 'user default addresses did not change'
- it_behaves_like 'checkout is in address step'
-
- it 'does not change order addresses' do
- expect(update_service).to be_success
-
- expect(order.reload.bill_address_id).to eq user.bill_address_id
- expect(order.reload.ship_address_id).to eq user.ship_address_id
- end
- end
-
- context 'when ship address changed' do
- let(:ship_address_id) { address.id }
-
- it_behaves_like 'user default addresses did not change'
- it_behaves_like 'checkout is in address step'
-
- it 'should update order ship address' do
- expect(update_service).to be_success
- expect(order.reload.bill_address_id).to eq user.bill_address_id
- expect(order.reload.ship_address_id).to eq address.id
- end
- end
-
- context 'when bill address changed' do
- let(:bill_address_id) { address.id }
-
- it_behaves_like 'user default addresses did not change'
- it_behaves_like 'checkout is in address step'
-
- it 'should update order bill address' do
- expect(update_service).to be_success
- expect(order.reload.bill_address_id).to eq address.id
- expect(order.reload.ship_address_id).to eq user.ship_address_id
- end
- end
-
- context 'when ship and bill address changed' do
- let(:ship_address_id) { address.id }
- let(:bill_address_id) { address.id }
-
- it_behaves_like 'user default addresses did not change'
- it_behaves_like 'checkout is in address step'
-
- it 'should update both order addresses' do
- expect(update_service).to be_success
- expect(order.reload.bill_address_id).to eq address.id
- expect(order.reload.ship_address_id).to eq address.id
- end
- end
- end
- end
-
- describe 'address ownership validation' do
- let(:user) { create(:user_with_addresses) }
- let(:other_user) { create(:user_with_addresses) }
- let(:order) { create(:order_with_line_items, user: user, state: 'address') }
- let(:permitted_attributes) do
- Spree::PermittedAttributes.checkout_attributes + [
- bill_address_attributes: Spree::PermittedAttributes.address_attributes,
- ship_address_attributes: Spree::PermittedAttributes.address_attributes
- ]
- end
-
- context 'when bill_address_attributes contains id of another user address' do
- let(:other_user_address) { other_user.bill_address }
- let(:order_params) do
- ActionController::Parameters.new(
- order: {
- bill_address_attributes: { id: other_user_address.id }
- }
- )
- end
-
- it 'returns failure' do
- result = described_class.call(order: order, params: order_params, permitted_attributes: permitted_attributes, request_env: nil)
- expect(result).to be_failure
- end
-
- it 'does not associate the other user address with the order' do
- described_class.call(order: order, params: order_params, permitted_attributes: permitted_attributes, request_env: nil)
- expect(order.reload.bill_address_id).not_to eq other_user_address.id
- end
- end
-
- context 'when ship_address_attributes contains id of another user address' do
- let(:other_user_address) { other_user.ship_address }
- let(:order_params) do
- ActionController::Parameters.new(
- order: {
- ship_address_attributes: { id: other_user_address.id }
- }
- )
- end
-
- it 'returns failure' do
- result = described_class.call(order: order, params: order_params, permitted_attributes: permitted_attributes, request_env: nil)
- expect(result).to be_failure
- end
-
- it 'does not associate the other user address with the order' do
- described_class.call(order: order, params: order_params, permitted_attributes: permitted_attributes, request_env: nil)
- expect(order.reload.ship_address_id).not_to eq other_user_address.id
- end
- end
-
- context 'when address_attributes contains id of the same user address' do
- let(:user_address) { create(:address, user: user) }
- let(:order_params) do
- ActionController::Parameters.new(
- order: {
- bill_address_attributes: { id: user_address.id }
- }
- )
- end
-
- it 'returns success' do
- result = described_class.call(order: order, params: order_params, permitted_attributes: permitted_attributes, request_env: nil)
- expect(result).to be_success
- end
- end
-
- context 'when address_attributes contains id of address with no user' do
- let(:guest_address) { create(:address, user: nil) }
- let(:order_params) do
- ActionController::Parameters.new(
- order: {
- bill_address_attributes: { id: guest_address.id }
- }
- )
- end
-
- it 'returns success' do
- result = described_class.call(order: order, params: order_params, permitted_attributes: permitted_attributes, request_env: nil)
- expect(result).to be_success
- end
- end
-
- context 'when address_attributes does not contain id' do
- let(:state) { create(:state) }
- let(:country) { state.country }
- let(:order_params) do
- ActionController::Parameters.new(
- order: {
- bill_address_attributes: {
- firstname: 'John',
- lastname: 'Doe',
- address1: '123 Main St',
- city: 'Anytown',
- zipcode: '12345',
- country_iso: country.iso,
- state_id: state.id,
- phone: '555-1234'
- }
- }
- )
- end
-
- it 'returns success' do
- result = described_class.call(order: order, params: order_params, permitted_attributes: permitted_attributes, request_env: nil)
- expect(result).to be_success
- end
- end
- end
-
- describe 'update selected shipping rate' do
- let(:update_service) { described_class.new }
- let(:order) { create(:order_with_line_items) }
- let(:order_params) do
- ActionController::Parameters.new(
- order: {
- shipments_attributes: [
- {
- id: order.shipments.first.id,
- selected_shipping_rate_id: order.shipments.first.shipping_rates.first.id
- }
- ]
- }
- )
- end
- let(:permitted_attributes) do
- Spree::PermittedAttributes.checkout_attributes + [
- shipments_attributes: Spree::PermittedAttributes.shipment_attributes
- ]
- end
-
- it 'should set order back to delivery state' do
- expect(order.state).not_to eq 'delivery'
-
- update_service.send(:call, order: order, params: order_params, permitted_attributes: permitted_attributes, request_env: nil)
-
- expect(order.state).to eq 'delivery'
- end
- end
-end