How to create a cart

A cart is created the moment the first product is added to it. This is the same with both WooCommerce on WordPress normally and CoCart decoupled from WordPress.

Once that cart is created. A series of cookies are created to store information about the cart. These cookies are designed mostly for WooCommerce JS which we don’t use with CoCart.

The one cookie that identifies the cart in session is wp_cocart_session_' . COOKIEHASH

This stores the customers unique ID, cart expiration, when the cart will expire, cookie hash and the cart hash (generated by the contents and total of the cart).

It is then used to identify the cart to combine additional items the customer may add and store the customers information in session until they are ready to purchase their order.

All this runs in the background and works fine with no problems if you are authenticating as the registered customer as the cart is always identified by the user ID given to a registered customer before the session of the cart is loaded.

For guest customers, it’s a little different and for some, the use of cookies is not optional. So the framework does not know how to read the cart in session.

To help identify and load the cart in session for a guest customer. A cart key is returned.

The cart key is the unique customer ID generated at the time the cart was created so you will need to capture it once the first item is added to the cart.

Not doing so will just lead to several carts being created in session with individual products with no way of getting the cart back.

How to capture the cart key?

There are two ways you can capture the cart key. The first is via the cart response (varies depending on the version of the API your using in CoCart).

The second is via the returned headers in the response. You will need to look for X-CoCart-API

For example the value it returns could be 9e18904482b4faf8762361836a83b93d

Once you have captured the cart key, you will then need to use this cart key for all future API requests with CoCart.

CoCart.get("cart?cart_key=9e18904482b4faf8762361836a83b93d")
.then((response) => {
  // Successful request
  console.log("Response Status:", response.status);
  console.log("Response Headers:", response.headers);
  console.log("Response Data:", response.data);
})
.catch((error) => {
  // Invalid request, for 4xx and 5xx statuses
  console.log("Response Status:", error.response.status);
  console.log("Response Headers:", error.response.headers);
  console.log("Response Data:", error.response.data);
})
.finally(() => {
  // Always executed.
});

Example shows getting the cart in API v2 of CoCart using CoCart JS library.

And that is it.