Overview
ShoppingCartApi.addToCart enables Apex integrations to add one or more web products to a shopper's cart using the managed package contract.
ShoppingCartApi.updateCartItem enables 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.ApiException when validation fails or the add-to-cart operation cannot complete.
- Update Cart Item:
- Method:
ShoppingCartApi.updateCartItem(request)
- Request type:
ShoppingCartApi.UpdateCartItemRequest
- Response type:
ShoppingCartApi.UpdateCartItemResult
- Throws:
ShoppingCartApi.ApiException when validation fails or the update operation cannot complete.
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.
isReadOnly (Boolean, optional) – when true, the item (and any generated child rows such as grouped options or addons) becomes read-only in the storefront UI and downstream APIs.
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.
isReadOnly (Boolean, optional) – set to true to lock the item or false to unlock it. Omit to leave the current state unchanged.
Fields Map Handling
- Provide any extra cart item data through
AddToCartItem.fields (for add) or UpdateCartItemRequest.fields (for update).
- Each value is converted to
String with String.valueOf before 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.
- The dedicated
isReadOnly flag should be used instead of injecting Read_Only__c through the field map; the API translates it to the correct field and cascades the state to generated child items.
Read-Only Behavior
isReadOnly maps to the managed field Read_Only__c on Shopping_Cart_Item__c.
- Add operations lock both the new parent item and any child lines created by the service (grouped options, auto-addons, shipment children).
- Update operations can lock or unlock an existing cart line; a locked item cannot be edited via UI or API until it is explicitly unlocked.
- Attempting to modify a locked item without unlocking first results in the service error
"This shopping cart item can no longer be edited."
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
shoppingCartItemIds list preserves the order of AddToCartRequest.items. Index n in the result corresponds to the item supplied at index n in 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
ApiException describing the issue.
Validation Rules
Add to Cart
- Request must not be null.
contactId is required.
items list must contain at least one entry.
- Item entries cannot be null.
- Each item must include
webProductId and quantity values.
- When
shoppingCartId is 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.
shoppingCartItemId is required.
shoppingCartId is 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
quantity is provided, it must be a positive integer.
- If
addons are provided, all must be valid and allowed for the item.
Error Behavior
- Failures raise
ShoppingCartApi.ApiException with a descriptive message. Notable cases:
Shopping cart not found
Shopping cart item not found
Price book could not be resolved
Unexpected add to cart result size
Cart item creation failed
Prohibited field update attempted
Invalid quantity
Invalid or unauthorized addon
Attempt to de-reference a null object errors 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
};
primaryItem.isReadOnly = true; // lock this line once it is created
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
updateRequest.isReadOnly = true; // lock the item after the update
// 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.addToCart for atomic, ordered insertions of web products into a cart from Apex integrations.
- Use
ShoppingCartApi.updateCartItem to update quantity, fields, or addons for an existing cart item, with full validation and security.
- Validate request data before invoking the API and handle
ApiException to maintain a resilient integration.