Last updated: Apr 06 2018

Area: Episerver Commerce Applies to versions: 10 and higher

Shopping carts

Introduction

The shopping cart (or basket) is where the shopping and ordering process starts. This document outlines the main components of a shopping cart in Episerver Commerce, using the abstraction APIs.

The cart APIs are built around the  IOrderRepository interface, which lets you load, update, save and eventually delete carts. The cart objects are represented by the ICart interface, which extends the IOrderGroup interface.

A main reason to prefer IOrderRepository over the concrete classes is that it is implementation-independent. Whether your underlying implementation is the legacy cart mode, or the new serializable one, IOrderRepository works the same. The providers do all the work "under the hood," so you don't have to think about it.

Load/create a cart

Each cart is identified by its name, customer id, and market. IOrderRepository has multiple overloads/extensions to create or load a cart. If a parameter is missing from the method call, the default value is used. For example, if you use overload without an MarketId parameter, the current market is used.

To load a cart, use the Load() method:

var  cart = orderRepository.Load<ICart>(customerId, "Default");

This loads the existing cart, and returns null if no cart exists.

To create a cart, use the .Create() method:

var  cart = orderRepository.Create<ICart>(customerId, "Default");

It's good practice to use the extension method .LoadOrCreate, which creates a cart (if none exists) or loads an existing cart:

var cart = orderRepository.LoadOrCreateCart<ICart>(_customerContext.CurrentContactId, name)

Add items to a cart

To add an item to a cart, you must first create an ILineItem. IOrderGroup has an extension method called CreateLineItem, which takes the SKU's code, and returns an ILineItem instance. A good practice is to check if the cart has an existing line item with the same SKU. If yes, increase the quantity. Otherwise, create a new line item and add it to a cart.

var lineItem = cart.GetAllLineItems().FirstOrDefault(x => x.Code == code && 
!x.IsGift);

            if (lineItem == null)
            {
                lineItem = cart.CreateLineItem(code, _orderGroupFactory);
                lineItem.DisplayName = entryContent.DisplayName;
                lineItem.Quantity = quantity;
                cart.AddLineItem(lineItem, _orderGroupFactory);
            }
            else
            {
                var shipment = cart.GetFirstShipment();
                cart.UpdateLineItemQuantity(shipment, lineItem, lineItem.Quantity + 
quantity);
            }

Remove items from a cart

To remove an item from a cart, remove it from the shipment. Normally, a cart has only one shipment, so removing the first shipment is enough.

var lineItem = cart.GetAllLineItems().FirstOrDefault(x => x.Code == code && !x.IsGift);

            if (lineItem != null)
            {
                var shipment = cart.GetFirstShipment();
                shipment.LineItems.Remove(lineItem);
            }

Validate a cart

Before a customer can place an order, a cart must be validated to make sure it has enough quantity, that the prices are correct and up-to-date, and that any promotions are applied correctly.

public Dictionary<ILineItem, List<ValidationIssue>> ValidateCart(ICart cart)
        {
            if (cart.Name.Equals(DefaultWishListName))
            {
                return new Dictionary<ILineItem, List<ValidationIssue>>();
            }

            var validationIssues = new Dictionary<ILineItem, List<ValidationIssue>>();
            cart.ValidateOrRemoveLineItems((item, issue) => 
validationIssues.AddValidationIssues(item, issue), _lineItemValidator);
            
cart.UpdatePlacedPriceOrRemoveLineItems(CustomerContext.Current.GetContactById(cart.Custom
erId), (item, issue) => validationIssues.AddValidationIssues(item, issue), 
_placedPriceProcessor);
            cart.UpdateInventoryOrRemoveLineItems((item, issue) => 
validationIssues.AddValidationIssues(item, issue), _inventoryProcessor);

            cart.ApplyDiscounts(_promotionEngine, new PromotionEngineSettings());

            // Try to validate gift items inventory and don't catch validation issues.
            cart.UpdateInventoryOrRemoveLineItems((item, issue) =>
            {}, _inventoryProcessor);

            return validationIssues;
        }

Save a cart

To save a cart, call IOrderRepository.Save on an instance of ICart orderRepository.Save(cart);.

Comments