Cart API
The Cart API enables you to build seamless shopping experiences by managing customer shopping carts. Handle cart operations including adding items, updating quantities, checking product availability, and managing back-in-stock notifications.
Overview​
The Cart API provides comprehensive shopping cart management:
- Cart Operations: Add, update, and remove items from customer carts
- Bulk Operations: Perform batch updates for multiple cart items
- Product Availability: Check stock and subscription status before adding to cart
- Back-in-Stock Notifications: Subscribe customers to alerts when products restock
- Checkout Flow: Complete cart and send checkout links via SMS
- Multi-Store Support: Each cart is scoped to a specific store
Unlike other VesuvioPay APIs, cart operations primarily require customer authentication (JWT tokens) rather than API keys, reflecting that carts belong to authenticated customers.
Use Cases​
Shopping Cart Integration​
Build a custom shopping experience by integrating cart operations into your e-commerce frontend:
// Add item to cart
await vesuvioPay.cart.addItem(storeId, {
externalProductId: 'prod_123',
externalVariantId: 'var_456',
quantity: 2
});
// Update item quantity
await vesuvioPay.cart.updateItem(storeId, {
cartItemId: 'item_id',
quantity: 5
});
// Remove item
await vesuvioPay.cart.removeItem(storeId, cartItemId);
Product Availability Checking​
Verify product availability before displaying "Add to Cart" buttons:
// Check if product is available (API key only)
const availability = await vesuvioPay.cart.checkAvailability(storeId, {
externalProductId: 'prod_123',
externalVariantId: 'var_456',
quantity: 1
});
if (availability.isAvailable) {
// Show add to cart button
} else {
// Show "Out of Stock" or subscription option
}
Bulk Cart Management​
Efficiently manage multiple cart items with bulk operations:
// Add multiple items at once
await vesuvioPay.cart.bulkAddItems(storeId, {
items: [
{ externalProductId: 'prod_1', externalVariantId: 'var_1', quantity: 2 },
{ externalProductId: 'prod_2', externalVariantId: 'var_2', quantity: 1 }
]
});
// Update multiple items
await vesuvioPay.cart.bulkUpdateItems(storeId, {
items: [
{ cartItemId: 'item_1', quantity: 5 },
{ cartItemId: 'item_2', quantity: 3 }
]
});
Back-in-Stock Notifications​
Enable customers to subscribe for notifications when out-of-stock products become available:
// Subscribe to back-in-stock alerts
await vesuvioPay.cart.subscribeBackInStock(storeId, {
externalProductId: 'prod_123',
externalVariantId: 'var_456'
});
// Unsubscribe when no longer interested
await vesuvioPay.cart.unsubscribeBackInStock(storeId, {
externalProductId: 'prod_123',
externalVariantId: 'var_456'
});
Checkout Flow​
Complete the cart flow and send checkout links:
// Finish cart and send SMS checkout link
const checkoutUrl = await vesuvioPay.cart.finishCartFlow(storeId);
// Customer receives SMS with payment link
Authentication​
Dual Authentication Model​
The Cart API uses different authentication methods depending on the operation:
Most cart operations require customer authentication via JWT tokens. These endpoints are marked with the CustomerWithVerifiedPhone policy.
Include the JWT token in the Authorization header:
Authorization: Bearer customer_jwt_token
Product availability checking uses Public API Keys and doesn't require customer authentication:
X-API-Key: your_public_api_key
Some endpoints accept an optional API key alongside customer JWT for additional validation. When provided, the API key's store must match the store ID in the request.
Authentication by Endpoint​
- Get Cart: Customer JWT (optional API key)
- Add/Update/Remove Items: Customer JWT (optional API key)
- Bulk Operations: Customer JWT (optional API key)
- Check Availability: Public API key only
- Check Availability with Subscription: Customer JWT (optional API key)
- Back-in-Stock Subscribe/Unsubscribe: Customer JWT (optional API key)
- Finish Cart Flow: Customer JWT (optional API key)
Key Concepts​
Store-Scoped Carts​
Each customer can have separate carts for different stores:
- Carts are isolated by store ID
- One customer can shop from multiple stores simultaneously
- Cart operations always specify the target store ID
Cart Items​
Cart items represent products added to the cart:
- Linked to specific product variants (by external ID)
- Include quantity and pricing information
- Automatically validated against inventory levels
- Show product availability and subscription status
External Product IDs​
Cart operations primarily use external product and variant IDs:
- Matches IDs from your e-commerce platform
- Simplifies integration with existing systems
- Enables seamless product linking
Product Availability​
Availability checking provides detailed information:
- isAvailable: Whether the requested quantity is in stock
- availableQuantity: Current stock level
- trackInventory: Whether inventory is tracked
- subscriptionStatus: Customer's notification subscription status
Bulk Operations​
Bulk endpoints optimize performance for multi-item operations:
- Process multiple items in a single request
- Return partial success results
- Reduce API calls and network latency
- Ideal for "Quick Buy" or cart restoration features
Cart Persistence​
Carts are automatically persisted:
- Survive across customer sessions
- Retained until checkout or manual clearing
- Synchronized across devices for authenticated customers
Checkout Integration​
The finish cart flow endpoint:
- Validates cart contents and inventory
- Generates secure checkout URL
- Sends SMS link to customer's verified phone
- Prepares cart for payment processing
Response Format​
Cart operations return standardized responses:
{
"success": true,
"data": {
"storeId": "store_guid",
"items": [
{
"id": "cart_item_id",
"productId": "product_guid",
"variantId": "variant_guid",
"externalProductId": "prod_123",
"externalVariantId": "var_456",
"quantity": 2,
"price": 29.99,
"product": {
"name": "Premium T-Shirt",
"imageUrl": "https://..."
}
}
],
"totalItems": 2,
"subtotal": 59.98
}
}
Availability checks return detailed status:
{
"success": true,
"data": {
"isAvailable": true,
"availableQuantity": 50,
"requestedQuantity": 2,
"trackInventory": true,
"isSubscribed": false,
"product": {
"name": "Premium T-Shirt",
"price": 29.99
}
}
}
Error Handling​
Common error scenarios:
- 404 Not Found: Cart, product, or variant not found
- 400 Bad Request: Invalid quantity or missing required fields
- 409 Conflict: Insufficient inventory for requested quantity
- 401 Unauthorized: Missing or invalid customer token
- 403 Forbidden: API key doesn't match store ID
Cart-specific errors include:
- Insufficient Inventory: Requested quantity exceeds available stock
- Product Unavailable: Product is out of stock or discontinued
- Invalid Cart Item: Cart item doesn't exist or doesn't belong to customer
See the Error Handling guide for detailed error response formats.
Best Practices​
Real-Time Availability​
Check availability before critical operations:
// Before adding to cart
const availability = await vesuvioPay.cart.checkAvailability(storeId, {
externalProductId: productId,
externalVariantId: variantId,
quantity: desiredQuantity
});
if (availability.isAvailable) {
await vesuvioPay.cart.addItem(storeId, { ... });
} else {
// Offer back-in-stock subscription
showBackInStockOption();
}
Optimistic Updates​
Update UI optimistically while API calls are in flight:
// Update UI immediately
updateCartUI({ quantity: newQuantity });
try {
// Confirm with API
await vesuvioPay.cart.updateItem(storeId, { quantity: newQuantity });
} catch (error) {
// Revert UI on failure
revertCartUI();
}
Bulk Operations for Performance​
Use bulk endpoints when managing multiple items:
// Good: Single bulk request
await vesuvioPay.cart.bulkAddItems(storeId, { items });
// Avoid: Multiple individual requests
for (const item of items) {
await vesuvioPay.cart.addItem(storeId, item); // Slower
}
Handle Partial Failures​
Bulk operations may partially succeed:
const result = await vesuvioPay.cart.bulkAddItems(storeId, { items });
if (result.partialSuccess) {
// Show which items succeeded and which failed
showPartialSuccessMessage(result);
}
Clear Empty Carts​
Clean up abandoned carts to maintain data hygiene:
// Clear cart when checkout is complete
await vesuvioPay.cart.clearCart(storeId);
Cart Event Webhooks​
Subscribe to cart events for analytics and automation:
cart.created: New cart initializedcart.item_added: Item added to cartcart.item_updated: Item quantity changedcart.item_removed: Item removed from cartcart.cleared: Cart emptiedcart.abandoned: Cart inactive for threshold periodcart.checkout_started: Customer began checkout
See the Webhooks API for setup instructions.
Rate Limiting​
Cart operations are subject to rate limiting. Consider:
- Debouncing quantity updates in UI
- Using bulk operations to reduce request count
- Caching availability checks with short TTL
See the Rate Limiting documentation for details.
Next Steps​
- Review specific endpoint documentation in the API reference below
- Integrate with Products API for product catalog
- Connect with Orders API for checkout completion
- Set up webhooks for cart event notifications
Interactive API Reference​
Detailed endpoint documentation is auto-generated from our OpenAPI specification. See the interactive API reference below for complete request/response schemas, authentication requirements, and the ability to test endpoints directly.