Creating and Maintaining a Cart Session
Manipulating the Cart with GraphQL Storefront
The BigCommerce GraphQL Storefront API exposes a number of queries and mutations for managing a user’s cart session, meaning your storefront can manage this critical aspect of the ecommerce experience with the same API strategy as your other core BC interactions. In this module, we’ll explore the key operations for tracking and managing a customer’s cart.
Creating a Cart
All mutations related to managing a cart exist in the top-level cart field in the GraphQL schema. To create a cart, use the cart.createCart mutation.
Note that the input argument and its lineItems field are required; you cannot initialize a cart without at least one line item. lineItems expects an array of CartItemInput objects, so you are free to initialize the cart with multiple line items.
You can see that the entityId of the newly created cart is being queried in the response. This unique identifier string will be important for maintaining continuity in subsequent queries or mutations.
Note that the separate field id also exists on the cart response object, but entityId is the value you will want to use to identify the cart in future GraphQL requests.
Anatomy of the Cart Object
The cart data queried in the above createCart mutation examples is of the Cart type. Review the API reference for full details. The following are key fields:
lineItems- An object with sub-fields further dividing cart line items intophysicalItems,digitalItems,giftCertificatesandcustomItems. Each of these is, in turn, a list of line item objects.lineItemsalso contains thetotalQuantityfield.baseAmount- The subtotal of the cart, before coupons or cart-level promotional discounts are applied. (If products have a sale price set or customer-specific pricing applies, these are already taken into account inbaseAmount. If item-level discounts are applied, this is also already accounted for.)amount- The grand total of the cart after coupons and cart-level promotional discounts are applied.discountedAmount- The total amount of cart-level promotional discounts. This is the amount of the discounts, not the discounted cart total. If item-level discounts are applied, their totals will not be reflected here.discounts- A list containing the discount amount (sum of coupon and promotional discounts) for each cart line item. Each is associated with a line item byentityId.currencyCode- The currency code that applies to the entire cart.metafields- A cursor list of any metafields that have been attached to the cart.
The types CartPhysicalItem and CartDigitalItem, which populate lineItems.physicalItems and lineItems.digitalItems respectively, share these common key fields:
entityId- The unique ID of the line item.productEntityId,sku,name,url,imageUrl- Basic product information fields.quantity- The line item quantity.originalPrice- The default price of the product, before a sale price or customer pricing takes effect.listPrice- The “final” price of an item before promotional or coupon discounts. This price takes a product’s sale price or customer pricing into effect.extendedListPrice- ThelistPricemultiplied by the item quantity.salePrice- In addition to product sale price and customer pricing, this line item price also accounts for promotional discounts applied at the item level, but not coupons. (Note that cart-level promotional discounts don’t affect an item’ssalePrice.)extendedSalePrice- ThesalesPricemultiplied by the item quantity. The cartbaseAmountshould equal the sum of all items’extendedSalePrice.discountedAmount- The total amount of item-level promotional discounts. Cart-level promotional discounts will not be reflected in this field.couponAmount- The amount of any coupon discounts applied to the line item.discounts- A list containing each separate promotional or coupon discount applied to the line item. In this case, cart-level promotional discounts are distributed among the line items and reflected in this array.
The type associated with items in lineItems.customItems- CartCustomItem - shares the fields entityId, sku, name, quantity, listPrice, and extendedListPrice. The type associated with lineItems.giftCertificates - CartGiftCertificate - shares the entityId and name fields, and it also contains an amount field with the amount of the gift certificate.
The site.cart query can be used to query the same Cart object.
A Note on Coupons
Some fields we’ve examined on a cart and its line items deal with coupon discounts, but you may notice when reviewing the API reference for createCart and other cart mutations that they do not include a way to apply a coupon code in the first place.
This is an example of the distinction between dealing with a “cart” and a “checkout.” Both affect the same underlying BigCommerce data and use the same ID to identify the cart/checkout, but the mutations are in separate namespaces in the GraphQL schema. The checkout mutations deal not only with coupons, but also key checkout information like shipping consignments and billing address information.
Despite a coupon code being applied with a checkout mutation, cart queries using the same entityId will reflect the applied coupon discount.
Tracking the Cart In Your Own Storefront
The recommended best practice for cart operations is to track a customer’s cart ID with a session management strategy in your own front-end application. Where a customer context is present in the request that creates a cart (such as from a Customer Access Token), that cart will accessible by subsequent requests with the same customer context.
A standard approach for tracking a user’s cart ID across requests would be to store it in a cookie. The entityId associated with a cart is a randomized string, from which other cart IDs cannot be guessed, so it is often acceptable to store it in plaintext.
In the next lab exercise, you’ll practice storing and using a cart ID in plaintext in a cookie, as described above.
If you want to avoid a plaintext solution while still using cookies for session information, consider utilizing a JSON web token. We’ll discuss this technique in more detail when we address customer authentication.