Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Add cart associate endpoint for guest-to-user order claiming

Damian Legawiec20ea897deb69
diff --git a/api/app/controllers/spree/api/v3/store/cart_controller.rb b/api/app/controllers/spree/api/v3/store/cart_controller.rb
index 32f4f92775..4daa7cc394 100644
--- a/api/app/controllers/spree/api/v3/store/cart_controller.rb
+++ b/api/app/controllers/spree/api/v3/store/cart_controller.rb
@@ -3,6 +3,10 @@ module Spree
module V3
module Store
class CartController < Store::BaseController
+ include Spree::Api::V3::OrderConcern
+
+ before_action :require_authentication!, only: [:associate]
+
# GET /api/v3/store/cart
# Returns current incomplete order (cart)
# Returns 404 if no cart exists - use POST /orders to create one
@@ -22,6 +26,46 @@ module Spree
render json: serialize_resource(@cart)
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
+
+ if @cart.nil?
+ render_error(
+ code: ERROR_CODES[:record_not_found],
+ message: 'Cart not found. Provide a valid order token.',
+ status: :not_found
+ )
+ return
+ end
+
+ if @cart.completed?
+ render_error(
+ code: ERROR_CODES[:order_already_completed],
+ message: 'Cannot associate a completed order',
+ status: :unprocessable_entity
+ )
+ return
+ end
+
+ # Check if cart already belongs to a different user
+ if @cart.user.present? && @cart.user != current_user
+ render_error(
+ code: ERROR_CODES[:access_denied],
+ message: 'This cart belongs to another user',
+ status: :forbidden
+ )
+ return
+ end
+
+ # Associate the cart with the current user
+ @cart.associate_user!(current_user)
+
+ render json: serialize_resource(@cart)
+ end
+
protected
def serializer_class
@@ -30,6 +74,14 @@ module Spree
private
+ # Find cart by order token only (for associate action)
+ def find_cart_by_token
+ token = order_token
+ return nil unless token.present?
+
+ current_store.orders.find_by(token: token)
+ end
+
def find_cart
# Try order_token first (guest checkout)
if params[:order_token].present?
diff --git a/api/config/routes.rb b/api/config/routes.rb
index ea26f6ebc9..d0c68aeac1 100644
--- a/api/config/routes.rb
+++ b/api/config/routes.rb
@@ -27,6 +27,7 @@ Spree::Core::Engine.add_routes do
# Cart - alias for current incomplete order (creates if none exists)
get 'cart', to: 'cart#show'
+ patch 'cart/associate', to: 'cart#associate'
# Orders - all orders (complete and incomplete)
resources :orders do
diff --git a/api/spec/controllers/spree/api/v3/store/cart_controller_spec.rb b/api/spec/controllers/spree/api/v3/store/cart_controller_spec.rb
index 3cc49771aa..5ea792dd31 100644
--- a/api/spec/controllers/spree/api/v3/store/cart_controller_spec.rb
+++ b/api/spec/controllers/spree/api/v3/store/cart_controller_spec.rb
@@ -165,4 +165,124 @@ RSpec.describe Spree::Api::V3::Store::CartController, type: :controller do
end
end
end
+
+ describe 'PATCH #associate' do
+ let(:guest_cart) { create(:order_with_line_items, store: store, user: nil, email: '[email protected]') }
+
+ context 'with JWT authentication' do
+ before do
+ request.headers['Authorization'] = "Bearer #{jwt_token}"
+ end
+
+ it 'associates guest cart with current user via order_token param' do
+ patch :associate, params: { order_token: guest_cart.token }
+
+ expect(response).to have_http_status(:ok)
+ expect(guest_cart.reload.user).to eq(user)
+ expect(json_response['number']).to eq(guest_cart.number)
+ end
+
+ it 'associates guest cart with current user via x-spree-order-token header' do
+ request.headers['x-spree-order-token'] = guest_cart.token
+
+ patch :associate
+
+ expect(response).to have_http_status(:ok)
+ expect(guest_cart.reload.user).to eq(user)
+ end
+
+ it 'updates cart email to users email' do
+ patch :associate, params: { order_token: guest_cart.token }
+
+ expect(response).to have_http_status(:ok)
+ expect(guest_cart.reload.email).to eq(user.email)
+ end
+
+ it 'sets user addresses on cart when user has addresses' do
+ bill = create(:address, firstname: 'Bill')
+ ship = create(:address, firstname: 'Ship')
+ user.update!(bill_address: bill, ship_address: ship)
+
+ patch :associate, params: { order_token: guest_cart.token }
+
+ expect(response).to have_http_status(:ok)
+ guest_cart.reload
+ expect(guest_cart.bill_address).to be_present
+ expect(guest_cart.ship_address).to be_present
+ end
+
+ it 'allows re-associating cart already owned by current user' do
+ guest_cart.update!(user: user)
+
+ patch :associate, params: { order_token: guest_cart.token }
+
+ expect(response).to have_http_status(:ok)
+ expect(guest_cart.reload.user).to eq(user)
+ end
+
+ it 'returns not found for invalid token' do
+ patch :associate, params: { order_token: 'invalid_token' }
+
+ expect(response).to have_http_status(:not_found)
+ expect(json_response['error']['code']).to eq('record_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('record_not_found')
+ expect(json_response['error']['message']).to include('order token')
+ end
+
+ it 'returns error for completed order' do
+ completed_order = create(:completed_order_with_totals, store: store, user: nil)
+
+ patch :associate, params: { order_token: completed_order.token }
+
+ expect(response).to have_http_status(:unprocessable_entity)
+ expect(json_response['error']['code']).to eq('order_already_completed')
+ end
+
+ it 'returns forbidden when cart belongs to another user' do
+ other_user = create(:user)
+ other_user_cart = create(:order_with_line_items, store: store, user: other_user)
+
+ patch :associate, params: { order_token: other_user_cart.token }
+
+ expect(response).to have_http_status(:forbidden)
+ expect(json_response['error']['code']).to eq('access_denied')
+ expect(other_user_cart.reload.user).to eq(other_user) # unchanged
+ end
+
+ it 'returns not found for cart from other store' do
+ other_store = create(:store)
+ other_store_cart = create(:order_with_line_items, store: other_store)
+
+ patch :associate, params: { order_token: other_store_cart.token }
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ context 'without JWT authentication' do
+ it 'returns unauthorized' do
+ patch :associate, params: { order_token: guest_cart.token }
+
+ 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
+ patch :associate, params: { order_token: guest_cart.token }
+
+ expect(response).to have_http_status(:unauthorized)
+ expect(json_response['error']['code']).to eq('invalid_token')
+ end
+ end
+ end
end
diff --git a/sdk/src/client.ts b/sdk/src/client.ts
index ed658ca71b..13cc7bb662 100644
--- a/sdk/src/client.ts
+++ b/sdk/src/client.ts
@@ -121,6 +121,10 @@ export class SpreeClient {
requestHeaders['Authorization'] = `Bearer ${token}`;
}
+ if (orderToken) {
+ requestHeaders['x-spree-order-token'] = orderToken;
+ }
+
if (locale) {
requestHeaders['x-spree-locale'] = locale;
}
@@ -346,6 +350,14 @@ export class SpreeClient {
*/
create: (options?: RequestOptions): Promise<StoreOrder & { token: string }> =>
this.request<StoreOrder & { token: string }>('POST', '/orders', options),
+
+ /**
+ * Associate a guest cart with the currently authenticated user
+ * Requires both JWT token (for authentication) and orderToken (to identify the cart)
+ * @param options - Must include both `token` (JWT) and `orderToken` (guest cart token)
+ */
+ associate: (options: RequestOptions): Promise<StoreOrder & { token: string }> =>
+ this.request<StoreOrder & { token: string }>('PATCH', '/cart/associate', options),
};
// ============================================