# ShoppingCartApi Cart Item Operations
Overview
ShoppingCartApi.addToCartenables Apex integrations to add one or more web products to a shopper's cart using the managed package contract.ShoppingCartApi.updateCartItemenables Apex integrations to update an existing cart item (quantity, fields, or addons) in a shopper's cart, enforcing validation and security rules.- Both APIs orchestrate shopping cart resolution, field validation, and delegate services while shielding callers from internal implementation details.
When to Use
- Add products to an existing cart when you already have the cart Id.
- Build a new cart for a buyer by supplying their contact and requested products.
- Update an existing cart item (e.g., change quantity, update custom fields, or manage addons) in a cart.
- Populate or update carts from custom flows, schedulable jobs, or integration layers where Lightning controllers are not available.
Entry Points
- Add to Cart:
- Method:
ShoppingCartApi.addToCart(request) - Request type:
ShoppingCartApi.AddToCartRequest - Response type:
ShoppingCartApi.AddToCartResult - Throws:
ShoppingCartApi.ApiExceptionwhen validation fails or the add-to-cart operation cannot complete.
- Method:
- Update Cart Item:
- Method:
ShoppingCartApi.updateCartItem(request) - Request type:
ShoppingCartApi.UpdateCartItemRequest - Response type:
ShoppingCartApi.UpdateCartItemResult - Throws:
ShoppingCartApi.ApiExceptionwhen validation fails or the update operation cannot complete.
- Method:
Request DTOs
ShoppingCartApi.AddToCartRequest
contactId(Id, required) – shopper contact Id. Determines the buyer and associated account context.shoppingCartId(Id, optional) – existing cart to reuse. Leave null to let the API select the current contact's active cart or create a cart.items(List<ShoppingCartApi.AddToCartItem>, required) – ordered collection of products to add.
ShoppingCartApi.AddToCartItem
webProductId(Id, required) – web product to add.quantity(Decimal, required) – quantity for the line item.fields(Map<String, Object>, optional) – additional field values to persist on the cart item. Keys must be field API names.
ShoppingCartApi.UpdateCartItemRequest
shoppingCartId(Id, required) – the cart containing the item to update.shoppingCartItemId(Id, required) – the cart item to update.quantity(Decimal, optional) – new quantity for the cart item. Must be a positive integer if provided.fields(Map<String, Object>, optional) – additional field values to update on the cart item. Keys must be field API names. Prohibited fields: Price/parent/product references, see below.addons(List, optional) – list of addon Ids to associate with the cart item. Only valid addon Ids are accepted.
Fields Map Handling
- Provide any extra cart item data through
AddToCartItem.fields(for add) orUpdateCartItemRequest.fields(for update). - Each value is converted to
StringwithString.valueOfbefore being sent downstream. Pre-format values for picklists, numbers, or booleans accordingly. - Leave the map empty when no custom data is required.
- For updates, certain fields are prohibited from being set (e.g., price, parent, product references). Attempting to update these will result in an error.
Result DTOs
ShoppingCartApi.AddToCartResult
shoppingCartId– Id of the cart that now contains the items. If a new cart is opened, this Id reflects the created cart.shoppingCartItemIds– ordered list of newly created cart item Ids.
ShoppingCartApi.UpdateCartItemResult
shoppingCartId– Id of the cart containing the updated item.shoppingCartItemId– Id of the updated cart item.
Ordering Guarantee
- The
shoppingCartItemIdslist preserves the order ofAddToCartRequest.items. Indexnin the result corresponds to the item supplied at indexnin the request.
All-or-Nothing Behavior
- Both add and update operations execute within a savepoint and roll back all changes if any part of the process fails.
- No cart items are created or updated when an exception is raised. The caller receives an
ApiExceptiondescribing the issue.
Validation Rules
Add to Cart
- Request must not be null.
contactIdis required.itemslist must contain at least one entry.- Item entries cannot be null.
- Each item must include
webProductIdandquantityvalues. - When
shoppingCartIdis supplied, it must reference an existing cart. - A price book must be resolvable either from the cart or storefront context; otherwise the request fails.
Update Cart Item
- Request must not be null.
shoppingCartItemIdis required.shoppingCartIdis required and must match the item's cart.- The cart item must exist and belong to the current user.
- Only allowed fields may be updated (see prohibited fields below).
- If
quantityis provided, it must be a positive integer. - If
addonsare provided, all must be valid and allowed for the item.
Error Behavior
- Failures raise
ShoppingCartApi.ApiExceptionwith a descriptive message. Notable cases:Shopping cart not foundShopping cart item not foundPrice book could not be resolvedUnexpected add to cart result sizeCart item creation failedProhibited field update attemptedInvalid quantityInvalid or unauthorized addonAttempt to de-reference a null objecterrors from downstream services are surfaced with their original message
- Handle the exception to notify callers or retry with corrected data.
Usage Examples
Add to Cart
// Build the request
ShoppingCartApi.AddToCartRequest request = new ShoppingCartApi.AddToCartRequest();
request.contactId = contactId;
request.shoppingCartId = existingCartId; // optional
request.items = new List<ShoppingCartApi.AddToCartItem>();
ShoppingCartApi.AddToCartItem primaryItem = new ShoppingCartApi.AddToCartItem();
primaryItem.webProductId = primaryWebProductId;
primaryItem.quantity = 2;
primaryItem.fields = new Map<String, Object>{
'OC_Custom_Text__c' => 'Preferred engraving',
'OC_Custom_Number__c' => 25
};
request.items.add(primaryItem);
ShoppingCartApi.AddToCartItem accessoryItem = new ShoppingCartApi.AddToCartItem();
accessoryItem.webProductId = accessoryWebProductId;
accessoryItem.quantity = 1;
request.items.add(accessoryItem);
// Execute and process the result
try {
ShoppingCartApi.AddToCartResult result = ShoppingCartApi.addToCart(request);
Id cartId = result.shoppingCartId;
List<Id> createdItemIds = result.shoppingCartItemIds;
// Implement post-processing such as logging or additional updates
// using the ordered list of cart item Ids.
} catch (ShoppingCartApi.ApiException apiEx) {
// Surface the error to callers or map to integration error handling logic.
}
Update Cart Item
// Build the request
ShoppingCartApi.UpdateCartItemRequest updateRequest = new ShoppingCartApi.UpdateCartItemRequest();
updateRequest.shoppingCartId = cartId;
updateRequest.shoppingCartItemId = cartItemId;
updateRequest.quantity = 3; // optional, only if changing quantity
updateRequest.fields = new Map<String, Object>{
'OC_Custom_Text__c' => 'Updated engraving',
'OC_Custom_Flag__c' => true
};
updateRequest.addons = new List<Id>{ addonId1, addonId2 }; // optional
// Execute and process the result
try {
ShoppingCartApi.UpdateCartItemResult updateResult = ShoppingCartApi.updateCartItem(updateRequest);
Id updatedCartId = updateResult.shoppingCartId;
Id updatedItemId = updateResult.shoppingCartItemId;
// Implement post-processing such as logging or additional updates
} catch (ShoppingCartApi.ApiException apiEx) {
// Surface the error to callers or map to integration error handling logic.
}
Summary
- Use
ShoppingCartApi.addToCartfor atomic, ordered insertions of web products into a cart from Apex integrations. - Use
ShoppingCartApi.updateCartItemto update quantity, fields, or addons for an existing cart item, with full validation and security. - Validate request data before invoking the API and handle
ApiExceptionto maintain a resilient integration.