NAV
Node.js cURL jQuery PHP WP API

Introduction

GitHub Mark Logo Edit on GitHub

Welcome to the documentation site for CoCart, an open-source WordPress plugin that brings the power of WooCommerce's shopping cart via the REST API. If you haven't already, checkout the features CoCart support.

CoCart helps you manage shopping carts in any modern framework of your choosing. No local storing required. A powerful RESTful API that offers an integration to build your headless store with ease.

What is a REST API?

REST is an acronym for Representational State Transfer — an almost meaningless description of the most-used web service technology! REST is a way for two computer systems to communicate over HTTP in a similar way to web browsers and servers.

CoCart is a REST API designed in mind for those who want to create a headless e-commerce site powered by WooCommerce. Read what does headless mean?

CoCart allows developers to provide a shopping cart in their app that stores the customers items, coupons applied, shipping methods available and much more. Carts can be created, read, updated, and deleted using the requests available that return a response in JSON format and standard HTTP verbs which are understood by most HTTP clients.

API Versions

The current WordPress REST API integration for CoCart is version v2.

The following table shows API versions present in each major version of CoCart:

API Version CoCart Version WC Version WP Version PHP Version Documentation
v1 2.0.x or later 4.3.x or later 5.2 or later 7.0 or later cocart-api-v1 docs
v2 3.0.x or later 4.8.x or later 5.4 or later 7.3 or later Currently Viewing

Prior to WooCommerce v3.6, CoCart shared WooCommerce's REST API. You can find the documentation about cart support for /wc-api-v2 API separately.

API Version WC Version WP Version Documentation
Legacy wc-api-v2 3.0.x or later 4.4 or later wc-api-v2 docs

Requirements

To use the latest version of the CoCart you must be using:

Request/Response Format

The default response format is in JSON. Requests with a message-body use plain JSON to set or update resource attributes. Successful requests will return a 200 OK HTTP status.

Some general information about response:

Body Types

There are different types of body types when making a request. Make sure when using either of these body types that you have the correct Content-Type for the header.

Body Type Content-Type
form-data  application/json
raw  application/json
x-www-form-urlencoded application/x-www-form-urlencoded

Using raw works best if you are passing an object of data for a variation or cart_item_data when testing the API using any of the tools available.

Errors

Occasionally you might encounter errors when accessing the REST API. Here are the possible types:

Error Code Error Type
400 Bad Request Invalid request, e.g. using an unsupported HTTP method
401 Unauthorized Authentication or permission error, e.g. incorrect login
403 Forbidden Not allowed to process this action or have permission.
404 Not Found Requests to resources that don't exist or are missing
405 Method Not Allowed A request method is not supported for the requested resource.
500 Internal Server Error Server error

WP REST API error example

{
  "code": "rest_no_route",
  "message": "No route was found matching the URL and request method",
  "data": {
    "status": 404
  }
}

CoCart error example

{
  "code": "cocart_clear_cart_failed",
  "message": "Clearing the cart failed!",
  "data": {
    "status": 500
  }
}

Errors return both an appropriate HTTP status code and response object which contains a code, message and data attribute.

Parameters

Almost all endpoints accept optional parameters which can be passed as a HTTP query string parameter, e.g. POST /cocart/v2/item?item_key=270edd69788dce200a3b395a6da6fdb7&quantity=2. All parameters are documented along each endpoint.

Getting Started

GitHub Mark Logo Edit on GitHub

This section is intended to help you get started with WordPress, WooCommerce and CoCart.

Setting up WordPress

One of the first things you might want to do is to set up a WordPress site on your personal computer.

I hands-down recommend using a tool called LocalWP. It’s a desktop application that allows you to create new WordPress sites on your computer with the click of a few buttons. It takes care of configuring PHP, MySQL and basic configuration of WordPress to connect to the database. It provides one-click support for enabling XDebug, allows access to your WordPress site using WP-CLI, and more. And, it’s free.

There are some alternatives for quickly spinning up a local environment:

When setting up your WordPress environment, please check that you have the server requirements for CoCart.

Setting up WooCommerce

Once you have your WordPress environment setup. The next step is to install WooCommerce and setup your store. Add products, configure shipping, taxes, payment gateway etc.

A more detailed guide for setting up WooCommerce can be found at WooCommerce.com documentation.

Automatic installation

Automatic installation is the easiest option as WordPress handles the file transfers itself and you don’t need to leave your web browser. To do an automatic install of WooCommerce, log in to your WordPress dashboard, navigate to the Plugins menu and click Add New.

In the search field type “WooCommerce” and click Search Plugins. Once you’ve found the plugin you can view details about it such as the point release, rating and description. Most importantly of course, you can install it by simply clicking “Install Now”.

Setting up CoCart

Once you have your WooCommerce store setup. The next step is to install CoCart. Once installed you can the use the API.

Automatic installation

Automatic installation is the easiest option as WordPress handles the file transfers itself and you don’t need to leave your web browser. To do an automatic install of CoCart, log in to your WordPress dashboard, navigate to the Plugins menu and click Add New.

In the search field type “CoCart” and click Search Plugins. Once you’ve found the plugin you can view details about it such as the point release, rating and description. Most importantly of course, you can install it by simply clicking “Install Now”.

For the most stable and performance experience, it’s recommended that you use the most recent version of the plugin. You can get the latest releases here.

Of course, as new features are in development, feel free to check out the latest develop branch or check out any other release.

GitHub - Download / Clone Plugin

CoCart is available on GitHub: https://github.com/co-cart/co-cart

You can download the latest release or clone the plugin from GitHub.

Add the downloaded/cloned plugin to your WordPress plugin directory. On a typical WordPress install, this is located at /wp-content/plugins.

This section will list recommended plugins that will help with your development in creating a headless store.

Error Responses

GitHub Mark Logo Edit on GitHub

You might encounter an error when using CoCart. These error responses explain what might have happened.

Code Error Status Error Response
401 cocart_cannot_read_cart Cannot read cart!
404 cocart_customer_missing Customer ID is required!
404 cocart_cart_key_missing Cart Key is required!
404 cocart_cart_in_session_not_valid Cart in session is not valid!
404 cocart_clear_cart_failed Clearing the cart failed!
404 cocart_product_id_required Product ID number is required!
405 cocart_product_id_not_numeric Product ID must be numeric!
405 cocart_quantity_not_numeric Quantity must be numeric!
404 cocart_product_does_not_exist Warning: This product does not exist!
403 cocart_product_sold_individually You cannot add another "%s" to your cart. %s is the product name
403 cocart_cannot_be_purchased Sorry, this product cannot be purchased.
404 cocart_product_out_of_stock You cannot add "%s" to the cart because the product is out of stock. %s is the product name
403 cocart_not_enough_in_stock You cannot add a quantity of %1$s for "%2$s" to the cart because there is not enough stock. - only %3$s remaining! %1$s: quantity requested, %2$s: product name, %3$s: stock remaining.
403 cocart_not_enough_stock_remaining You cannot add that amount to the cart — we have %1$s in stock and you already have %2$s in your cart.
403 cocart_not_ok_to_add_item This item can not be added to the cart.
403 cocart_cannot_add_to_cart You cannot add "%s" to your cart. %s is the product name
403 cocart_can_not_remove_item Unable to remove item from cart.
403 cocart_can_not_restore_item Unable to restore item to the cart.
403 cocart_can_not_update_item Unable to update item quantity in cart.
404 cocart_cart_item_key_required Cart item key is required!
404 cocart_no_items No items in cart.
404 cocart_item_not_in_cart Item specified does not exist in cart.
403 cocart_cannot_add_product_type_to_cart You cannot add "%1$s" to your cart as it is an "%2$s" product. %1$s: product name, %2$s: product type
400 cocart_invalid_variation_data Invalid value posted for %1$s. Allowed values: %2$s %1$s: Attribute name, %2$s: Allowed values
400 cocart_missing_variation_data Missing variation data for variable product. %s is a required field. %s: Attribute name.
400 cocart_missing_variation_data Missing variation data for variable product. %s are required fields. %s: Attribute name.
400 cocart_no_variation_found No matching variation found.
403 cocart_cart_invalid_parent_product This product cannot be added to the cart.
404 cocart_product_failed_validation Product did not pass validation!
403 cocart_product_sold_individually You cannot add another "%s" to your cart.
403 cocart_can_not_increase_quantity You can only have 1 %s in your cart. %s is the product name

Breaking changes

GitHub Mark Logo Edit on GitHub

New major versions typically involve some backwards incompatible changes. If you use custom integrations with the API, you should also expect things to change when switching between API versions.

CoCart 3.0

CoCart 3.0 focuses on bringing a new flow experience to help development for headless ecommerce be better than ever before. There are a few changes.

One of the biggest changes is to return the cart updated in most of the API endpoints available.

Knowledge Base

GitHub Mark Logo Edit on GitHub

Cart returns empty after adding items. Why?

As a guest customer, this is normally because the framework your using does not support cookies so it is unable to read the required cookie to load the cart on the next API request.

Read this guide on how to create a cart and keep using the same one.

I added several products but only 1 item returns in cart. Why?

As a guest customer, this is possibly because you did not store the cart key after the first item was added and set it on future API requests. So all your seeing is the last item added to the cart.

Read this guide on how to create a cart and keep using the same one.

Can I create and update a cart without cookies?

Yes you can. Read this guide on how to create a cart and update it without cookies.

Where can I find the cart key?

The cart key (if not manually set), can be found via a few methods. See cart key section for more details.

Why am I not seeing the X-COCART-API header returning?

If this header is not returning then you need to enable CORS so that the header is exposed. Either enable CORS support via the filter or simply install CoCart CORS plugin for quick activation.

Where can I find a cart item key?

Each item added to the cart has it's on cart item key and you will find it under the property labelled "key". Use it to update, remove or restore an item in/from the cart.

{
  "19ca14e7ea6328a42e0eb13d585e4c22":{
    "key":"19ca14e7ea6328a42e0eb13d585e4c22", // This is the cart item key.
    "product_id":36,
    "variation_id":0,
    ...
}

As admininstator can I create and update a customers cart?

Unfortunately, no. This is because when you authenticate as the admin, you are logged in not the customer. Even if you specified the customers user ID as the cart key. It will not take affect.

How can I view debug logs recorded ?

If you have WP_DEBUG set to true in your wp-config.php file then you should be able to view all the logs recorded by CoCart under WooCommerce -> System Status -> Logs in your WordPress dashboard.

URL Example: https://example.com/wp-admin/admin.php?page=wc-status&tab=logs

You can also change how the logs are presented.

How can I use CoCart on a multi-site network?

Using CoCart on any site on the network is just the same as you would on a single site. The only difference is the domain/sub-domain of the site.

Does CoCart work with the Dokan plugin?

Yes. The only feature you wont be able to use are coupons. This is because Dokan disables the use of coupons. All other features are compatible.

Authentication

GitHub Mark Logo Edit on GitHub

The WordPress REST API incorporates a method called nonces to deal with CSRF issues. This ensures that all activities on the website remain segregated. This is because the WordPress REST API just like the WooCommerce REST API is designed for the back-end.

CoCart however, is designed for the front-end so for any CoCart requests made, the cookie authentication is disabled allowing the ability to authenticate in any code language without fault.

REST API authentication methods:

Basic Authentication

What is the Basic Authentication method?

If you use the Basic Authentication method (which you may find the easiest to use for your customers to login with), please make sure that you have SSL enabled when making requests with any of the CoCart API routes. Check out the example adding an item to the cart as a registered customer.

Adding an item to the cart as a customer.

curl -X POST https://example.com/wp-json/cocart/v2/cart/add-item \
  -u username:password \
  -H "Content-Type: application/json" \
  -d '{
    "id": "32",
    "quantity": "1"
  }'
// import CoCartAPI from "@cocart/cocart-rest-api"; // Supports ESM
const CoCartAPI = require("@cocart/cocart-rest-api").default;

const CoCart = new CoCartAPI({
  url: "https://example.com",
  consumerKey: 'sebtest123',
  consumerSecret: 'happycoding24'
});

var data = {
  "id": "32",
  "quantity": "1"
};

CoCart.post("cart/add-item", data)
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart/add-item",
  headers: {
      "Authorization": "Basic " + btoa('username:password'),
  },
  method: "POST",
  data: JSON.stringify({
    "id": "32",
    "quantity": "1"
  }),
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

$args = json_encode( array(
  'id' => "32",
  'quantity' => "1"
) );

$headers = array(
  'Accept: application/json',
  'User-Agent: CoCart API/v2',
  'Authorization: Basic ' . base64_encode($username . ':' . $password)
);

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart/add-item",
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $args,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => $headers
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$args = array(
  'headers' => array(
    'Authorization' => 'Basic ' . base64_encode( 'username:password' ),
    'Content-Type' => 'application/json; charset=utf-8',
  ),
  'body' => wp_json_encode( [
    'id' => "32",
    'quantity' => "1"
  ] ),
  'timeout' => 30
);

$response = wp_remote_post( 'https://example.com/wp-json/cocart/v2/cart/add-item', $args );
$body = wp_remote_retrieve_body( $response );
{
  "404dcc91b2aeaa7caa47487d1483e48a":{
    "key":"404dcc91b2aeaa7caa47487d1483e48a",
    "product_id":32,
    "variation_id":0,
    "variation":[],
    "quantity":1,
    "line_tax_data":{
      "subtotal":[],
      "total":[]
    },
    "line_subtotal":18,
    "line_subtotal_tax":0,
    "line_total":18,
    "line_tax":0,
    "data":{}
  }
}

Authentication issues?

If the authentication header is not passing or authentication is not working you, adding a Rewrite rule to your .htaccess file might help.

.htaccess Rewrite rule

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
</IfModule>

JWT Authentication

JWT is a simple web token authentication method for WP REST API. To know more about JSON Web Tokens, please visit https://jwt.io.

It's important that you follow the installation and configurations exactly for this method to work. See instructions.

Steps to follow

  1. Download and Install JWT Authentication plugin from WordPress.org.
  2. Configure the Secret Key.
  3. Get your token.

There are other JWT authentication plugins available but this one appears to be the most commonly used.

$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart/add-item",
  headers: {
      "Authorization": "Bearer " + token,
  },
  method: "POST",
  data: JSON.stringify({
    "id": "32",
    "quantity": "1"
  }),
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

$args = json_encode( array(
  'id' => "32",
  'quantity' => "1"
) );

$headers = array(
  'Accept: application/json',
  'User-Agent: CoCart API/v2',
  'Authorization: Bearer ' . $token
);

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart/add-item",
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $args,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => $headers
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$args = array(
  'headers' => array(
    'Authorization' => 'Bearer ' . $token,
    'Content-Type' => 'application/json; charset=utf-8',
  ),
  'body' => wp_json_encode( [
    'id' => "32",
    'quantity' => "1"
  ] ),
  'timeout' => 30
);

$response = wp_remote_post( 'https://example.com/wp-json/cocart/v2/cart/add-item', $args );
$body = wp_remote_retrieve_body( $response );

WooCommerce API Keys

Though this method is designed for the backend with WooCommerce REST API, with some custom coding you can make it work for the frontend with CoCart. Checkout my guide on how to authenticate with WooCommerce.

Cart Key

GitHub Mark Logo Edit on GitHub

What is a Cart Key?

A cart key is what identifies the cart stored in session along with it's cart data and expiration. This is normally stored in a cookie and is used to load the cart in session if the cart still exists.

If used via the global parameter it will help identify a guest customers cart.

Accessing the Cart Key

If cookies don't work for you due to the limitations of the framework your using to build with, then don't worry. The cart key created for the customer is returned in the cart response and via the returned headers once the first API request has been made. This is helpful for supporting guest customers.

Look for X-CoCart-API and you will see the value of the cart key returned. You can then use this to set the cart_key parameter with any of the CoCart API routes to load this cart.

Creating a Cart Key

If you are creating a cart key of your own, it cannot be longer than 42 characters as that is the limit for storing the key in the database.

Cookie

GitHub Mark Logo Edit on GitHub

CoCart only creates and uses only one cookie per session/customer/device. The cookie name starts with wp_cocart_session_ followed by the WordPress COOKIEHASH. The cookie name can be changed using this filter.

If left enabled, this cookie will be used to identity the customers cart. The cookie is read on the server and returns the cart stored in the cookie.

The cookie stores 5 key values.

Once a customer has added the first item to the cart, a cookie is generated that stores the cart key (a.k.a the customers ID) and cart expiration.

This cookie is used in order to load the cart again in session for that individual customer. No parameters are required to pass as it is all done in the background.

This is the default behaviour for WooCommerce on the frontend and works fine in any framework that supports the use of creating and reading cookies.

If the framework your using is not able to read cookies, then there are a few things you can do.

  1. Look for a cookie support add-on for your framework. React for example has one called react-cookies.
  2. Read the cart key value in the returned header response X-CoCart-API. Once you have that value you can use it to set the cart_key parameter on all API requests. This will use the Cart Key method.

The cookie for CoCart and therefore the cart key is supplied through response headers, so called Set-Cookie-headers.

Cookies received via Set-Cookie-headers is stored in the browser for the domain upon which holds the API, meaning you can encounter problems reading the cookie values from your frontend.

If using a package like axios, make sure to supply the correct config parameters that enables cookies in requests to the server. As an example, axios has a config parameter called withAuthorization. With the flag set to true, cookies previous set will be sent in the request.

P.S. Our official JS library already has this setup for you.

If you need to change the SameSite attribute a filter is available that was introduced in v2.9.1

If you want to know more about SameSite attribute. Checkout this article.

Index

GitHub Mark Logo Edit on GitHub

By default, the API provides information about all available endpoints on the site. Authentication is not required to access the API index.

HTTP request

GET
/wp-json/cocart/v2
curl -X GET https://example.com/wp-json/cocart/v2 \
  -H "Content-Type: application/json"
CoCart.get("")
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2",
  method: "GET",
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2",
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v2' );
$body = wp_remote_retrieve_body( $response );

JSON response example:

{
    "namespace": "cocart/v2",
    "routes": {
        "/cocart/v2": {
            "namespace": "cocart/v2",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": {
                        "namespace": {
                            "required": false,
                            "default": "cocart/v2"
                        },
                        "context": {
                            "required": false,
                            "default": "view"
                        }
                    }
                }
            ],
            "_links": {
                "self": [
                    {
                        "href": "https://example.com/wp-json/cocart/v2"
                    }
                ]
            }
        },
        "/cocart/v2/get-cart": {
            "namespace": "cocart/v2",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": {
                        "cart_key": {
                            "required": false,
                            "description": "Unique identifier for the cart/customer.",
                            "type": "string"
                        },
                        "thumb": {
                            "required": false,
                            "default": false,
                            "description": "Returns the URL of the product image thumbnail.",
                            "type": "boolean"
                        }
                    }
                }
            ],
            "_links": {
                "self": [
                    {
                        "href": "https://example.com/wp-json/cocart/v2/get-cart"
                    }
                ]
            }
        },
        "/cocart/v2/get-cart/(?P<id>[\\w]+)": {
            "namespace": "cocart/v2",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": {
                        "cart_key": {
                            "required": false,
                            "description": "Unique identifier for the cart/customer.",
                            "type": "string"
                        },
                        "thumb": {
                            "required": false,
                            "default": false,
                            "description": "Returns the URL of the product image thumbnail.",
                            "type": "boolean"
                        }
                    }
                }
            ]
        },
        "/cocart/v2/get-cart/customer/(?P<id>[\\d]+)": {
            "namespace": "cocart/v2",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": {
                        "cart_key": {
                            "required": false,
                            "description": "Unique identifier for the cart/customer.",
                            "type": "string"
                        },
                        "thumb": {
                            "required": false,
                            "default": false,
                            "description": "Returns the URL of the product image thumbnail.",
                            "type": "boolean"
                        }
                    }
                }
            ]
        },
        "/cocart/v2/add-item": {
            "namespace": "cocart/v2",
            "methods": [
                "POST"
            ],
            "endpoints": [
                {
                    "methods": [
                        "POST"
                    ],
                    "args": {
                        "product_id": {
                            "required": false,
                            "description": "Unique identifier for the product.",
                            "type": "string"
                        },
                        "quantity": {
                            "required": true,
                            "default": 1,
                            "description": "The quantity amount of the item to add to cart.",
                            "type": "float"
                        },
                        "variation_id": {
                            "required": false,
                            "description": "Unique identifier for the variation.",
                            "type": "integer"
                        },
                        "variation": {
                            "required": false,
                            "description": "The variation attributes that identity the variation of the item.",
                            "type": "array"
                        },
                        "cart_item_data": {
                            "required": false,
                            "description": "Additional item data passed to make item unique.",
                            "type": "array"
                        },
                        "return_cart": {
                            "required": false,
                            "default": false,
                            "description": "Returns the cart once item is added.",
                            "type": "boolean"
                        }
                    }
                }
            ],
            "_links": {
                "self": [
                    {
                        "href": "https://example.com/wp-json/cocart/v2/add-item"
                    }
                ]
            }
        },
        "/cocart/v2/clear": {
            "namespace": "cocart/v2",
            "methods": [
                "POST"
            ],
            "endpoints": [
                {
                    "methods": [
                        "POST"
                    ],
                    "args": []
                }
            ],
            "_links": {
                "self": [
                    {
                        "href": "https://example.com/wp-json/cocart/v2/clear"
                    }
                ]
            }
        },
        "/cocart/v2/calculate": {
            "namespace": "cocart/v2",
            "methods": [
                "POST"
            ],
            "endpoints": [
                {
                    "methods": [
                        "POST"
                    ],
                    "args": {
                        "return": {
                            "required": false,
                            "default": false,
                            "description": "Returns the cart totals once calculated.",
                            "type": "boolean"
                        }
                    }
                }
            ],
            "_links": {
                "self": [
                    {
                        "href": "https://example.com/wp-json/cocart/v2/calculate"
                    }
                ]
            }
        },
        "/cocart/v2/count-items": {
            "namespace": "cocart/v2",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": {
                        "return": {
                            "required": false,
                            "default": "numeric"
                        }
                    }
                }
            ],
            "_links": {
                "self": [
                    {
                        "href": "https://example.com/wp-json/cocart/v2/count-items"
                    }
                ]
            }
        },
        "/cocart/v2/item": {
            "namespace": "cocart/v2",
            "methods": [
                "GET",
                "POST",
                "DELETE"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": {
                        "cart_item_key": {
                            "required": false,
                            "description": "Unique identifier for the item in the cart.",
                            "type": "string"
                        },
                        "return_cart": {
                            "required": false,
                            "default": false,
                            "description": "Returns the whole cart to reduce API requests.",
                            "type": "boolean"
                        }
                    }
                },
                {
                    "methods": [
                        "POST"
                    ],
                    "args": {
                        "cart_item_key": {
                            "required": false,
                            "description": "Unique identifier for the item in the cart.",
                            "type": "string"
                        },
                        "return_cart": {
                            "required": false,
                            "default": false,
                            "description": "Returns the whole cart to reduce API requests.",
                            "type": "boolean"
                        },
                        "quantity": {
                            "required": false,
                            "default": 1,
                            "type": "float"
                        }
                    }
                },
                {
                    "methods": [
                        "DELETE"
                    ],
                    "args": {
                        "cart_item_key": {
                            "required": false,
                            "description": "Unique identifier for the item in the cart.",
                            "type": "string"
                        },
                        "return_cart": {
                            "required": false,
                            "default": false,
                            "description": "Returns the whole cart to reduce API requests.",
                            "type": "boolean"
                        }
                    }
                }
            ],
            "_links": {
                "self": [
                    {
                        "href": "https://example.com/wp-json/cocart/v2/item"
                    }
                ]
            }
        },
        "/cocart/v2/logout": {
            "namespace": "cocart/v2",
            "methods": [
                "POST"
            ],
            "endpoints": [
                {
                    "methods": [
                        "POST"
                    ],
                    "args": []
                }
            ],
            "_links": {
                "self": [
                    {
                        "href": "https://example.com/wp-json/cocart/v2/logout"
                    }
                ]
            }
        },
        "/cocart/v2/totals": {
            "namespace": "cocart/v2",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": {
                        "html": {
                            "required": false,
                            "default": false,
                            "description": "Returns the totals pre-formatted.",
                            "type": "boolean"
                        }
                    }
                }
            ],
            "_links": {
                "self": [
                    {
                        "href": "https://example.com/wp-json/cocart/v2/totals"
                    }
                ]
            }
        }
    },
    "_links": {
        "up": [
            {
                "href": "https://example.com/wp-json/"
            }
        ]
    }
}

Store

GitHub Mark Logo Edit on GitHub

This API helps you get the store details.

HTTP request

GET
/wp-json/cocart/v2/store
curl -X GET https://example.com/wp-json/cocart/v2/store \
  -H "Content-Type: application/json"
CoCart.get("store")
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/store",
  method: "GET",
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/store",
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v2/store' );
$body = wp_remote_retrieve_body( $response );
{
    "version": "3.0.0",
    "title": "My Awesome Swag Store",
    "description": "Collect my new swag for 2021. Forget about 2020.",
    "home_url": "https://example.com",
    "language": "en-US",
    "gmt_offset": 2,
    "timezone_string": "Europe/Paris",
    "store_address": {
        "address": "Somewhere",
        "address_2": "warm",
        "city": "TimeCity",
        "country": "FR",
        "postcode": "11400"
    },
    "routes": {
        "cart": "https://example.com/wp-json/cocart/v2/cart",
        "cart-add-item": "https://example.com/wp-json/cocart/v2/cart/add-item",
        "cart-add-items": "https://example.com/wp-json/cocart/v2/cart/add-items",
        "cart-item": "https://example.com/wp-json/cocart/v2/cart/item",
        "cart-items": "https://example.com/wp-json/cocart/v2/cart/items",
        "cart-items-count": "https://example.com/wp-json/cocart/v2/cart/items/count",
        "cart-calculate": "https://example.com/wp-json/cocart/v2/cart/calculate",
        "cart-clear": "https://example.com/wp-json/cocart/v2/cart/clear",
        "cart-totals": "https://example.com/wp-json/cocart/v2/cart/totals",
        "login": "https://example.com/wp-json/cocart/v2/login",
        "logout": "https://example.com/wp-json/cocart/v2/logout"
    },
    "_links": {
        "help": [
            {
                "href": "https://docs.cocart.xyz/"
            }
        ]
    }
}

Products

In order to access your products, you need to have the CoCart Products add-on.

It's a public API that provides access to non-sensitive product information, categories, tags, attributes and even reviews from your store without the need to authenticate.

Supports other products types created by WooCommerce extensions such as Subscriptions and more.

Get CoCart Products

The following table shows API versions present in each major version of CoCart Products:

API Version CoCart Version WC Version WP Version Documentation
v1 2.0.x or later 4.0.x or later 5.2 or later view api documentation

Cart

GitHub Mark Logo Edit on GitHub

The cart API is powerful and allows you to view the customers cart in full detail ready to use the data made available to build and display the cart you want.

Most individual endpoints will return the cart response by default so you always have the updated cart once the request has been made.

Get Cart

This API returns the customers cart contents and much more.

Parameters

Parameter Type Description
cart_key string Unique identifier for the cart. ? optional

Properties

Property Type Description
thumb bool Set as false to remove the product thumbnail for each item. optional, default is true
default bool Return the default cart data if set to true. optional

HTTP request

GET
/wp-json/cocart/v2/cart

CoCart's cart response, providing everything you need.

curl -X GET https://example.com/wp-json/cocart/v2/cart \
  -H "Content-Type: application/json"
CoCart.get("cart")
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart",
  method: "GET",
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart",
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$args = array(
  'headers' => array(
    'Content-Type' => 'application/json; charset=utf-8',
  ),
  'timeout' => 30
);

$response = wp_remote_get( 'https://example.com/wp-json/cocart/v2/cart', $args );
$body = wp_remote_retrieve_body( $response );
{
  "cart_hash": "0b95eb807ead335612a3165e2466ac5c",
  "cart_key": "7894",
  "currency": {
    "currency_code": "USD",
    "currency_symbol": "$",
    "currency_minor_unit": 2,
    "currency_decimal_separator": ".",
    "currency_thousand_separator": ",",
    "currency_prefix": "$",
    "currency_suffix": ""
  },
  "customer": {
    "billing_address": {
      "billing_first_name": "Stephanie C",
      "billing_last_name": "Crawford",
      "billing_company": "",
      "billing_country": "US",
      "billing_address_1": "2243 Dogwood Lane",
      "billing_address_2": "",
      "billing_postcode": "85716",
      "billing_city": "Tucson",
      "billing_state": "AZ",
      "billing_phone": "520-784-8063",
      "billing_email": "x3l7r39mmp@temporary-mail.net"
    },
    "shipping_address": {
      "shipping_first_name": "Stephanie C",
      "shipping_last_name": "Crawford",
      "shipping_company": "",
      "shipping_country": "US",
      "shipping_address_1": "2243 Dogwood Lane",
      "shipping_address_2": "",
      "shipping_postcode": "85716",
      "shipping_city": "Tucson",
      "shipping_state": "AZ"
    }
  },
  "items": [
    {
      "item_key": "1ad001efb8a576ded17c71534502f4a5",
      "id": 73,
      "name": "Beanie",
      "title": "Beanie",
      "price": "18.00",
      "quantity": {
        "value": 1,
        "min_purchase": 1,
        "max_purchase": -1
      },
      "tax_data": {
        "subtotal": [],
        "total": []
      },
      "totals": {
        "subtotal": 18,
        "subtotal_tax": 0,
        "total": 18,
        "tax": 0
      },
      "slug": "beanie",
      "meta": {
        "product_type": "simple",
        "sku": "woo-beanie",
        "dimensions": {
          "length": "",
          "width": "",
          "height": "",
          "unit": "cm"
        },
        "weight": 0,
        "variation": []
      },
      "cart_item_data": [],
      "featured_image": "https://example.com/wp-content/uploads/2021/02/beanie-2-324x324.jpg"
    },
  ],
  "item_count": 1,
  "items_weight": 0,
  "coupons": [],
  "needs_payment": true,
  "needs_shipping": true,
  "shipping": {
    "total_packages": 1,
    "show_package_details": false,
    "has_calculated_shipping": false,
    "packages": {
      "default": {
        "package_name": "Shipping",
        "rates": {
          "flat_rate:1": {
            "key": "flat_rate:1",
            "method_id": "flat_rate",
            "instance_id": 1,
            "label": "Flat rate",
            "cost": "20.00",
            "html": "Flat rate: £20.00",
            "taxes": [],
            "chosen_method": true
          }
        },
        "package_details": "",
        "index": 0,
        "chosen_method": "flat_rate:1",
        "formatted_destination": "2243 Dogwood Lane, 85716 Tucson"
      }
    }
  },
  "fees": [],
  "taxes": [],
  "totals": {
    "subtotal": "1800",
    "subtotal_tax": "0",
    "fee_total": "0",
    "fee_tax": "0",
    "discount_total": "0",
    "discount_tax": "0",
    "shipping_total": "2000",
    "shipping_tax": "0",
    "total": "3800",
    "total_tax": "0"
  },
  "removed_items": [],
  "cross_sells": [],
  "notices": []
}

Default cart response, unfiltered and raw data.

curl -X GET https://example.com/wp-json/cocart/v2/cart \
  -H "Content-Type: application/json" \
  -d '{
    "default": true,
  }'
CoCart.get("cart", {
  default: true
})
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart",
  method: "GET",
  data: JSON.stringify({
    default: true
  }),
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

$args = array(
  'default' => true,
);

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart",
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_POSTFIELDS => $args,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$args = array(
  'headers' => array(
    'Content-Type' => 'application/json; charset=utf-8',
  ),
  'body' => wp_json_encode( [
    'default' => true,
  ] ),
  'timeout' => 30
);

$response = wp_remote_get( 'https://example.com/wp-json/cocart/v2/cart', $args );
$body = wp_remote_retrieve_body( $response );
{
  "7647966b7343c29048673252e490f736": {
    "key": "7647966b7343c29048673252e490f736",
    "product_id": 89,
    "variation_id": 0,
    "variation": [],
    "quantity": 1,
    "data_hash": "b5c1d5ca8bae6d4896cf1807cdf763f0",
    "line_tax_data": {
      "subtotal": [],
      "total": []
    },
    "line_subtotal": 12,
    "line_subtotal_tax": 0,
    "line_total": 12,
    "line_tax": 0,
    "data": {}
  }
}

Get Cart for Guest Customers

This method is designed for guest customers only. Using the cart_key parameter, you set the guest customers cart in session. See the "Cart Key" section for more information.

Parameters

Parameter Type Description
cart_key string Unique identifier for the cart. ? optional

HTTP request

GET
/wp-json/cocart/v2/cart?cart_key=<cart_key>

How to get a guest customers cart.

curl -X GET https://example.com/wp-json/cocart/v2/cart?cart_key=9e18904482b4faf8762361836a83b93d \
  -H "Content-Type: application/json"
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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart?cart_key=9e18904482b4faf8762361836a83b93d",
  method: "GET",
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart?cart_key=9e18904482b4faf8762361836a83b93d",
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$args = array(
  'headers' => array(
    'Content-Type' => 'application/json; charset=utf-8',
  ),
  'timeout' => 30
);

$response = wp_remote_get( 'https://example.com/wp-json/cocart/v2/cart?cart_key=9e18904482b4faf8762361836a83b93d', $args );
$body = wp_remote_retrieve_body( $response );

JSON response is the same as the main example above.

Merge Carts

Wish to merge items from a guest customers cart with a registered customers cart? Then when fetching the cart, you must authenticate as the registered customer and set the guests customers cart key.

Parameters

Parameter Type Description
cart_key string Unique identifier for the cart. ? optional

Properties

Attribute Type Description
thumb bool Set as false to remove the product thumbnail for each item. optional, default is true

HTTP request

GET
/wp-json/cocart/v2/cart?cart_key=<cart_key>
curl -X GET https://example.com/wp-json/cocart/v2/cart?cart_key=<cart_key> \
  -u username:password \
  -H "Content-Type: application/json"
// import CoCartAPI from "@cocart/cocart-rest-api"; // Supports ESM
const CoCartAPI = require("@cocart/cocart-rest-api").default;

const CoCart = new CoCartAPI({
  url: "https://example.com",
  consumerKey: 'sebtest123',
  consumerSecret: 'happycoding24'
});

CoCart.get("get-cart?cart_key=<cart_key>")
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart?cart_key=<cart_key>",
  headers: {
      "Authorization": "Basic " + btoa('username:password'),
  },
  method: "GET",
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart?cart_key=<cart_key>",
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v1',
    'Authorization: Basic ' . base64_encode($username . ':' . $password)
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$args = array(
  'headers' => array(
    'Authorization' => 'Basic ' . base64_encode( 'username:password' ),
    'Content-Type' => 'application/json; charset=utf-8',
  ),
  'timeout' => 30
);

$response = wp_remote_get( 'https://example.com/wp-json/cocart/v2/cart?cart_key=<cart_key>', $args );
$body = wp_remote_retrieve_body( $response );

Clear Cart

GitHub Mark Logo Edit on GitHub

This API helps you clear the contents of the cart.

Parameters

Parameter Type Description
cart_key string Unique identifier for the cart. ? optional

Properties

Property Type Description
keep_removed_items bool Keeps removed items in session when clearing the cart. optional

HTTP request

POST
/wp-json/cocart/v2/cart/clear
curl -X POST https://example.com/wp-json/cocart/v2/cart/clear \
  -H "Content-Type: application/json"
CoCart.post("cart/clear")
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart/clear",
  method: "POST",
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart/clear",
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$response = wp_remote_post( 'https://example.com/wp-json/cocart/v2/cart/clear' );
$body = wp_remote_retrieve_body( $response );
"Cart is cleared."

Add to Cart

GitHub Mark Logo Edit on GitHub

The most important part of CoCart is adding items to the cart. This API helps you to add an item or items to the cart.

Parameters

Parameter Type Description
cart_key string Unique identifier for the cart. ? optional

Properties

Property Type Description
id string Unique identifier for the product. A SKU ID can also be used here. mandatory
quantity string Set the quantity of the product you want to add to the cart. Default is 1
variation object Attribute values. required, for variable products only
item_data object Used to apply extra cart item data we want to pass with the item. optional
return_item bool Set as true to return the item details once added. optional

HTTP request

POST
/wp-json/cocart/v2/cart/add-item

Add a Simple Product

There are two ways of adding a simple product. Either use the product ID or it's SKU ID.

Example of adding to the cart via product ID.

curl -X POST https://example.com/wp-json/cocart/v2/cart/add-item \
  -H "Content-Type: application/json" \
  -d '{
    "id": "71",
    "quantity": "1"
  }'
CoCart.post("cart/add-item", {
  id: "71",
  quantity: "1"
})
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart/add-item",
  method: "POST",
  data: JSON.stringify({
    "id" : "71",
    "quantity" : "1"
  }),
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

$args = array(
  'id' => "71",
  'quantity' => "1"
);

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart/add-item",
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $args,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$args = array(
  'headers' => array(
    'Content-Type' => 'application/json; charset=utf-8',
  ),
  'body' => wp_json_encode( [
    'id' => "71",
    'quantity' => "1"
  ] ),
  'timeout' => 30
);

$response = wp_remote_post( 'https://example.com/wp-json/cocart/v2/cart/add-item', $args );
$body = wp_remote_retrieve_body( $response );

Example of adding to the cart via SKU ID.

curl -X POST https://example.com/wp-json/cocart/v2/cart/add-item \
  -H "Content-Type: application/json" \
  -d '{
    "id": "woo-hoodie-with-logo",
    "quantity": "1"
  }'
CoCart.post("cart/add-item", {
  id: "woo-hoodie-with-logo",
  quantity: "1"
})
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart/add-item",
  method: "POST",
  data: JSON.stringify({
    "id" : "woo-hoodie-with-logo",
    "quantity" : "1"
  }),
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

$args = array(
  'id' => "woo-hoodie-with-logo",
  'quantity' => "1"
);

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart/add-item",
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $args,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$args = array(
  'headers' => array(
    'Content-Type' => 'application/json; charset=utf-8',
  ),
  'body' => wp_json_encode( [
    'id' => "woo-hoodie-with-logo",
    'quantity' => "1"
  ] ),
  'timeout' => 30
);

$response = wp_remote_post( 'https://example.com/wp-json/cocart/v2/cart/add-item', $args );
$body = wp_remote_retrieve_body( $response );
{
  "item_key": "12403d0e56cf4380c3d80d899185f2ce",
  "id": 71,
  "name": "Hoodie with Logo",
  "title": "Hoodie with Logo",
  "price": "45.00",
  "quantity": {
    "value": 1,
    "min_purchase": 1,
    "max_purchase": -1
  },
  "tax_data": {
    "subtotal": [],
    "total": []
  },
  "totals": {
    "subtotal": 45,
    "subtotal_tax": 0,
    "total": 45,
    "tax": 0
  },
  "slug": "hoodie-with-logo",
  "meta": {
    "product_type": "simple",
    "sku": "woo-hoodie-with-logo",
    "dimensions": {
      "length": "",
      "width": "",
      "height": "",
      "unit": "cm"
    },
    "weight": 0,
    "variation": []
  },
  "cart_item_data": []
}

Add a Variation of a Variable Product

Adding a variation of a variable product to the cart is easy. All you need is to identify the attributes and which attribute your customer has selected.

What are attributes?

Attributes are what identify a variation of a variable product from the colour of a t-shirt to the size.

Attributes can be managed in two ways. Globally or via the product if they are custom. It's important to know what attributes are used for the variation of the product.

All attributes start with a prefix. A global attribute prefix is like so attribute_pa_, while a custom attribute just has the prefix attribute_. Both are followed by the attribute slug. See the examples for comparison.

Example of adding a variation of a product to the cart.

curl -X POST https://example.com/wp-json/cocart/v2/cart/add-item \
  -H "Content-Type: application/json" \
  -d '{
    "id": "1820",
    "quantity": "1",
    "variation": {
      "attribute_colours": "Red",
      "attribute_pa_size": "2x-large"
    }
  }'
var data = {
  "id": "1820",
  "quantity": "1",
  "variation": {
    "attribute_colours": "Red",
    "attribute_pa_size": "2x-large"
  }
};

CoCart.post("cart/add-item", data)
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart/add-item",
  method: "POST",
  data: JSON.stringify({
    "id": "1820",
    "quantity": "1",
    "variation": {
      "attribute_colours": "Red",
      "attribute_pa_size": "2x-large"
    }
  }),
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

$args = array(
  'id' => '1820',
  'quantity' => '1',
  'variation' => {
    'attribute_colours': 'Red',
    'attribute_pa_size': '2x-large'
  }
);

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart/add-item",
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $args,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$args = array(
  'headers' => array(
    'Content-Type' => 'application/json; charset=utf-8',
  ),
  'body' => wp_json_encode( [
    'id' => '1820',
    'quantity' => '1',
    'variation' => {
      'attribute_colours': 'Red',
      'attribute_pa_size': '2x-large'
    }
  ] ),
  'timeout' => 30
);

$response = wp_remote_post( 'https://example.com/wp-json/cocart/v2/cart/add-item', $args );
$body = wp_remote_retrieve_body( $response );

Add a Grouped Product

This API will help you add grouped products to the cart.

Parameters

Parameter Type Description
cart_key string Unique identifier for the cart. ? optional

Properties

Property Type Description
id string Unique identifier for the product. A SKU ID can also be used here. mandatory
quantity object List of items and quantity in the cart.
item_data object Used to apply extra cart item data we want to pass with the item. optional
return_items bool Set as true to return the item details once added. optional

HTTP request

POST
/wp-json/cocart/v2/cart/add-items

Warning if you try to add grouped products using the wrong API route.

{
    "code": "cocart_cannot_add_product_type_to_cart",
    "message": "You cannot use this route to add \"grouped\" products to the cart. Please use /cocart/v2/cart/add-items instead.",
    "data": {
        "status": 403
    }
}
curl -X POST https://example.com/wp-json/cocart/v2/cart/add-items \
  -H "Content-Type: application/json" \
  -d '{
    "id": "91",
    "quantity": {
      "71": 2,
      "72": 1
    }
  }'
var data = {
  "id": "91",
  "quantity": {
    "71": 2,
    "72": 1
  }
};

CoCart.post("cart/add-item", data)
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart/add-items",
  method: "POST",
  data: JSON.stringify({
    "id": "91",
    "quantity": {
      "71": 2,
      "72": 1
    }
  }),
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

$args = array(
  'id' => '91',
  'quantity' => array(
    "71" => 2,
    "72" => 1
  )
);

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart/add-items",
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $args,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$args = array(
  'headers' => array(
    'Content-Type' => 'application/json; charset=utf-8',
  ),
  'body' => wp_json_encode( [
    'id' => '91',
    'quantity' => array(
      "71" => 2,
      "72" => 1
    )
  ] ),
  'timeout' => 30
);

$response = wp_remote_post( 'https://example.com/wp-json/cocart/v2/cart/add-items', $args );
$body = wp_remote_retrieve_body( $response );

Add Item with Custom Data

Need to pass custom data? This example will show you how.

Example of adding a product with custom data to the cart.

curl -X POST https://example.com/wp-json/cocart/v2/cart/add-item \
  -H "Content-Type: application/json" \
  -d '{
    "id": "3008",
    "quantity": "1",
    "item_data": {
      "engraved_name": "Sébastien Dumont",
      "engraved_size": "Medium"
    }
  }'
var data = {
  "id": "3008",
  "quantity": "1",
  "item_data": {
    "engraved_name": "Sébastien Dumont",
    "engraved_size": "Medium"
  }
};

CoCart.post("cart/add-item", data)
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart/add-item",
  method: "POST",
  data: JSON.stringify({
    "id": "3008",
    "quantity": "1",
    "item_data": {
      "engraved_name" : "Sébastien Dumont",
      "engraved_size" : "Medium"
    }
  }),
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

$args = array(
  'id' => '3008',
  'quantity' => "1",
  'item_data' => array(
    'engraved_name' => 'Sébastien Dumont',
    'engraved_size' => 'Medium'
  )
);

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart/add-item",
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $args,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$args = array(
  'headers' => array(
    'Content-Type' => 'application/json; charset=utf-8',
  ),
  'body' => wp_json_encode( [
    'id' => '3008',
    'quantity' => '1',
    'item_data' => array(
      'engraved_name' => 'Sébastien Dumont',
      'engraved_size' => 'Medium'
    )
  ] ),
  'timeout' => 30
);

$response = wp_remote_post( 'https://example.com/wp-json/cocart/v2/cart/add-item', $args );
$body = wp_remote_retrieve_body( $response );

Items in Cart

GitHub Mark Logo Edit on GitHub

Once items are in the cart, customers always make decisions on which items they want to buy now, change the quantities of a particular item and which items they should remove.

The following API's help with all of that.

Items

This API help you view just the items added in the cart.

Properties

Property Type Description
cart_key string Unique identifier for the cart. ? optional

HTTP request

GET
/wp-json/cocart/v2/cart/items
curl -X GET https://example.com/wp-json/cocart/v2/cart/items \
 -H "Content-Type: application/json"
CoCart.get("cart/items")
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart/items",
  method: "GET",
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart/items",
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v2/cart/items' );
$body = wp_remote_retrieve_body( $response );
{
    "f28cd9f0560070670a861d86462b8f14": {
        "item_key": "f28cd9f0560070670a861d86462b8f14",
        "id": 90,
        "name": "Beanie with Logo",
        "title": "Beanie with Logo",
        "price": "18.00",
        "quantity": {
            "value": 2,
            "min_purchase": 1,
            "max_purchase": -1
        },
        "tax_data": {
            "subtotal": [],
            "total": []
        },
        "totals": {
            "subtotal": 36,
            "subtotal_tax": 0,
            "total": 36,
            "tax": 0
        },
        "slug": "beanie-with-logo",
        "meta": {
            "product_type": "simple",
            "sku": "Woo-beanie-logo",
            "dimensions": {
                "length": "",
                "width": "",
                "height": "",
                "unit": "cm"
            },
            "weight": 0,
            "variation": []
        },
        "cart_item_data": [],
        "featured_image": "https://example.com/wp-content/uploads/2021/02/beanie-with-logo-1-324x324.jpg"
    },
    "af69a8dc2ae2de6cac18bc4a6a75afa3": {
        "item_key": "af69a8dc2ae2de6cac18bc4a6a75afa3",
        "id": 85,
        "name": "V-Neck T-Shirt - Blue",
        "title": "V-Neck T-Shirt",
        "price": "15.00",
        "quantity": {
            "value": 1,
            "min_purchase": 1,
            "max_purchase": -1
        },
        "tax_data": {
            "subtotal": [],
            "total": []
        },
        "totals": {
            "subtotal": 15,
            "subtotal_tax": 0,
            "total": 15,
            "tax": 0
        },
        "slug": "v-neck-t-shirt",
        "meta": {
            "product_type": "variation",
            "sku": "woo-vneck-tee-blue",
            "dimensions": {
                "length": "",
                "width": "",
                "height": "",
                "unit": "cm"
            },
            "weight": 0,
            "variation": {
                "Color": "Blue",
                "Size": "Large"
            }
        },
        "cart_item_data": [],
        "featured_image": "https://example.com/wp-content/uploads/2021/02/vnech-tee-blue-1-324x324.jpg"
    }
}

View a Single Item

This API help you view just a single item added in the cart.

Parameters

Parameter Type Description
cart_key string Unique identifier for the cart. ? optional

Properties

Property Type Description
item_key string Unique identifier for the item in the cart. mandatory

HTTP request

GET
/wp-json/cocart/v2/cart/item/<item_key>
curl -X GET https://example.com/wp-json/cocart/v2/cart/item/<item_key> \
 -H "Content-Type: application/json"
CoCart.get("cart/item/<item_key>")
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart/item/<item_key>",
  method: "GET",
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart/item/<item_key>",
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v2/cart/item/<item_key>' );
$body = wp_remote_retrieve_body( $response );
{
    "item_key": "af69a8dc2ae2de6cac18bc4a6a75afa3",
    "id": 85,
    "name": "V-Neck T-Shirt - Blue",
    "title": "V-Neck T-Shirt",
    "price": "15.00",
    "quantity": {
        "value": 1,
        "min_purchase": 1,
        "max_purchase": -1
    },
    "tax_data": {
        "subtotal": [],
        "total": []
    },
    "totals": {
        "subtotal": 15,
        "subtotal_tax": 0,
        "total": 15,
        "tax": 0
    },
    "slug": "v-neck-t-shirt",
    "meta": {
        "product_type": "variation",
        "sku": "woo-vneck-tee-blue",
        "dimensions": {
            "length": "",
            "width": "",
            "height": "",
            "unit": "cm"
        },
        "weight": 0,
        "variation": {
            "Color": "Blue",
            "Size": "Large"
        }
    },
    "cart_item_data": [],
    "featured_image": "https://example.com/wp-content/uploads/2021/02/vnech-tee-blue-1-324x324.jpg"
}

Count Items

This API helps you count the items in the cart.

Parameters

Parameter Type Description
cart_key string Unique identifier for the cart. ? optional

Properties

Property Type Description
removed_items bool Set as true to count items removed from the cart. optional

HTTP request

GET
/wp-json/cocart/v2/cart/items/count
curl -X GET https://example.com/wp-json/cocart/v2/cart/items/count \
 -H "Content-Type: application/json"
CoCart.get("cart/items/count")
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart/items/count",
  method: "GET",
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart/items/count",
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v2/cart/items/count' );
$body = wp_remote_retrieve_body( $response );
3

Remove Item from Cart

GitHub Mark Logo Edit on GitHub

This API helps you to remove an item from the cart. If an item has not already been removed and does exist in the cart then an updated cart response will return.

If an item does not exist in cart or has already been removed, then an error message will return instead as nothing has changed to the cart. Therefore there is no need to return the cart response.

Parameters

Parameter Type Description
cart_key string Unique identifier for the cart. ? optional

Properties

Property Type Description
item_key string Unique identifier for the item in the cart. mandatory
return_status bool Set as true to return a message after removing item from cart. optional

HTTP request

DELETE
/wp-json/cocart/v2/cart/item/<item_key>
curl -X DELETE https://example.com/wp-json/cocart/v2/cart/item/<item_key> \
  -H "Content-Type: application/json"
CoCart.delete("cart/item/<item_key>")
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart/item/<item_key>",
  method: "DELETE",
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart/item/<item_key>",
  CURLOPT_CUSTOMREQUEST => "DELETE",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$args = array(
  'headers' => array(
    'Content-Type' => 'application/json; charset=utf-8',
  ),
  'method' => 'DELETE',
  'timeout' => 30
);

$response = wp_remote_request( 'https://example.com/wp-json/cocart/v2/cart/item/<item_key>', $args );
$body = wp_remote_retrieve_body( $response );
// Returned response if item is removed with `return_status` set to `true`.
"\"Beanie\" has been removed from cart."

Restore Item to Cart

GitHub Mark Logo Edit on GitHub

This API helps you to restore an item to the cart. If an item has not already been restored then an updated cart response will return.

If an item does not exist in cart or has already been restored, then an error message will return instead as nothing has changed to the cart. Therefore there is no need to return the cart response.

Parameters

Parameter Type Description
cart_key string Unique identifier for the cart. ? optional

Properties

Property Type Description
item_key string Unique identifier for the item in the cart. mandatory
return_item bool Set as true to return the item details once restored back to the cart. optional

HTTP request

PUT
/wp-json/cocart/v2/cart/item/<item_key>
curl -X PUT https://example.com/wp-json/cocart/v2/cart/item/<item_key> \
  -H "Content-Type: application/json"
CoCart.put("cart/item/<item_key>", data)
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart/item/<item_key>",
  method: "PUT",
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart/item/<item_key>",
  CURLOPT_CUSTOMREQUEST => "PUT",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$args = array(
  'headers' => array(
    'Content-Type' => 'application/json; charset=utf-8',
  ),
  'method' => 'PUT',
  'timeout' => 30
);

$response = wp_remote_get( 'https://example.com/wp-json/cocart/v2/cart/item/<item_key>', $args );
$body = wp_remote_retrieve_body( $response );
// Returned response if item is restored with `return_item` set to `true.
{
    "item_key": "1ad001efb8a576ded17c71534502f4a5",
    "id": 73,
    "name": "Beanie",
    "title": "Beanie",
    "price": "18.00",
    "quantity": {
        "value": 1,
        "min_purchase": 1,
        "max_purchase": -1
    },
    "tax_data": {
        "subtotal": [],
        "total": []
    },
    "totals": {
        "subtotal": 18,
        "subtotal_tax": 0,
        "total": 18,
        "tax": 0
    },
    "slug": "beanie",
    "meta": {
        "product_type": "simple",
        "sku": "woo-beanie",
        "dimensions": {
            "length": "",
            "width": "",
            "height": "",
            "unit": "cm"
        },
        "weight": 0,
        "variation": []
    },
    "cart_item_data": [],
    "featured_image": "https://example.com/wp-content/uploads/2021/02/beanie-2-324x324.jpg"
}

Update Item in Cart

GitHub Mark Logo Edit on GitHub

This API helps you to update an item in the cart.

Parameters

Parameter Type Description
cart_key string Unique identifier for the cart. ? optional

Properties

Property Type Description
item_key string The cart item key of the product in the cart you want to update. mandatory
quantity float Set the quantity of the product you want to update in the cart. Default is 1
return_cart bool Set as true to return the whole cart once item is updated. optional

HTTP request

POST
/wp-json/cocart/v2/cart/item/<item_key>
curl -X POST https://example.com/wp-json/cocart/v2/cart/item/<item_key> \
  -H "Content-Type: application/json" \
  -d '{
    "quantity": 2
  }'
var data = {
  "quantity": 2
};

CoCart.post("cart/item/<item_key>", data)
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart/item/<item_key>",
  method: "POST",
  data: JSON.stringify({
    "quantity" : 2
  }),
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

$args = array(
  'quantity' => 2
);

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart/item/<item_key>",
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $args,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$args = array(
  'headers' => array(
    'Content-Type' => 'application/json; charset=utf-8',
  ),
  'body' => wp_json_encode( [
    'quantity' => 2
  ] ),
  'timeout' => 30
);

$response = wp_remote_post( 'https://example.com/wp-json/cocart/v2/cart/item/<item_key>', $args );
$body = wp_remote_retrieve_body( $response );

Totals

GitHub Mark Logo Edit on GitHub

Retrieve Cart Totals

This API helps you retrieve the cart totals. You can also return the totals pre-formatted to save you time applying the currency symbol.

Parameters

Parameter Type Description
cart_key string Unique identifier for the cart. ? optional

Properties

Property Type Description
html bool Set as true to return the totals as strings with currency symbol. optional

HTTP request

GET
/wp-json/cocart/v2/cart/totals
curl -X GET https://example.com/wp-json/cocart/v2/cart/totals \
 -H "Content-Type: application/json"
CoCart.get("cart/totals")
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart/totals",
  method: "GET",
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart/totals",
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v2/cart/totals' );
$body = wp_remote_retrieve_body( $response );
{
  "subtotal":"123.00",
  "subtotal_tax":8.4,
  "shipping_total":"33.00",
  "shipping_tax":6.6,
  "shipping_taxes": {
    "12": 6.6
  },
  "discount_total":24.6,
  "discount_tax":0,
  "cart_contents_total":"98.40",
  "cart_contents_tax":8.4,
  "cart_contents_taxes": {
    "12": 8.4
  },
  "fee_total":"0.00",
  "fee_tax":0,
  "fee_taxes":[],
  "total":"146.40",
  "total_tax":15
}

Here is what to do to return the totals formatted with currency symbol.

curl -X GET https://example.com/wp-json/cocart/v2/cart/totals \
  -H "Content-Type: application/json" \
  -d '{
    "html": true
  }'
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart/totals",
  method: "GET",
  data: JSON.stringify({
    "html" : true
  }),
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

$args = array(
  'html' => true
);

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart/totals",
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_POSTFIELDS => $args,
  CURLOPT_RETURNTRANSFER => true
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$args = array(
  'html' => true
);
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v2/cart/totals', $args );
$body = wp_remote_retrieve_body( $response );
{
  "subtotal":"£123.00",
  "subtotal_tax":"£8.40",
  "shipping_total":"£33.00",
  "shipping_tax":"£6.60",
  "shipping_taxes": {
    "12": 6.6
  },
  "discount_total":"£24.60",
  "discount_tax":"£0.00",
  "cart_contents_total":"£98.40",
  "cart_contents_tax":"£8.40",
  "cart_contents_taxes": {
    "12": 8.4
  },
  "fee_total":"£0.00",
  "fee_tax":"£0.00",
  "fee_taxes":[],
  "total":"£146.40",
  "total_tax":"£15.00"
}

Calculate Cart Totals

GitHub Mark Logo Edit on GitHub

This API helps you calculate the cart totals. You can also request to return the totals once calculated to reduce API requests and use the Retrieve Cart Totals properties.

Parameters

Parameter Type Description
cart_key string Unique identifier for the cart. ? optional

Properties

Property Type Description
return bool Set as true to return the totals once calculated. optional

HTTP request

POST
/wp-json/cocart/v2/cart/calculate
curl -X POST https://example.com/wp-json/cocart/v2/cart/calculate \
    -H "Content-Type: application/json"
CoCart.post("calculate")
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart/calculate",
  method: "POST",
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart/calculate",
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$response = wp_remote_post( 'https://example.com/wp-json/cocart/v2/cart/calculate' );
$body = wp_remote_retrieve_body( $response );
"Cart totals have been calculated."

Login

GitHub Mark Logo Edit on GitHub

This API requires authentication and returns basic information about the user logged in.

HTTP request

POST
/wp-json/cocart/v2/login
curl -X POST https://example.com/wp-json/cocart/v2/login \
  -H "Content-Type: application/json" \
CoCart.post("login")
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/login",
  method: "POST",
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/login",
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$response = wp_remote_post( 'https://example.com/wp-json/cocart/v2/login' );
$body = wp_remote_retrieve_body( $response );
{
    "user_id": "5143",
    "display_name": "sebastien",
    "role": "Customer",
    "dev_note": "Don't forget to store the users login information in order to authenticate all other routes with CoCart."
}

Logout

GitHub Mark Logo Edit on GitHub

This API logs out your customers. This will clear all session cookies for WordPress and CoCart.

HTTP request

POST
/wp-json/cocart/v2/logout
curl -X POST https://example.com/wp-json/cocart/v2/logout \
  -H "Content-Type: application/json" \
CoCart.post("logout")
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/logout",
  method: "POST",
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/logout",
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$response = wp_remote_post( 'https://example.com/wp-json/cocart/v2/logout' );
$body = wp_remote_retrieve_body( $response );
true

Load Cart from Session

GitHub Mark Logo Edit on GitHub

This feature is designed to transfer the cart over to the web version of your store. It allows the customer to continue shopping or checkout what they already have in the cart added via your app. Handy if you don't yet have a checkout system in your app.

You can choose to override the cart (if anything is set) or merge the cart items together. If a customer is logged in via the web version of your store then WooCommerce will then merge any items in the cart together with the items the guest customer has in cart.

Properties

Property Type Description
cocart-load-cart string Set the cart key of the cart you wish to load. mandatory
notify bool Set as true to notify customers once arrived on the web version of your store. Default is false
keep-cart bool Set as false to merge cart data. Default is true

To load the cart from session on your web store, you must use the properties above to query your website. You can query any page you prefer your customer to land on as the cart is loaded in the background.

Example
https://example.com/cart/?cocart-load-cart=bbfa8e97ac9cff4c861d62a109e83bb6

If the same item already exists in cart and you are merging the two carts together, that item will not change. It will not increase or decrease the quantity if the cart item key are the same.

Sessions

GitHub Mark Logo Edit on GitHub

Get Sessions

This API helps you retrieve all sessions for the store.

HTTP request

GET
/wp-json/cocart/v2/sessions
curl -X GET https://example.com/wp-json/cocart/v2/sessions \
  -u username:password \
  -H "Content-Type: application/json"
// import CoCartAPI from "@cocart/cocart-rest-api"; // Supports ESM
const CoCartAPI = require("@cocart/cocart-rest-api").default;

const CoCart = new CoCartAPI({
  url: "https://example.com",
  consumerKey: 'sebtest123',
  consumerSecret: 'happycoding24'
});

CoCart.get("sessions")
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/sessions",
  headers: {
      "Authorization": "Basic " + btoa('username:password'),
  },
  method: "GET",
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/sessions",
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
    'Authorization: Basic ' . base64_encode($username . ':' . $password)
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v2/sessions' );
$body = wp_remote_retrieve_body( $response );
[
  {
    "cart_id": "4038",
    "cart_key": "afa399e3a0647fe660438409d9ad7eb9",
    "customers_name": "John Snow",
    "customers_email": "",
    "cart_created": "04/23/2021 07:46:59",
    "cart_expiry": "04/30/2021 07:48:40",
    "cart_source": "woocommerce",
    "link": "https://example.com/wp-json/cocart/v2/session/afa399e3a0647fe660438409d9ad7eb9"
  },
  {
    "cart_id": "4335",
    "cart_key": "8f36f08beca94f2b51faedcb7c6864b8",
    "customers_name": "Clark Kent",
    "customers_email": "clark@dailyplanet.wb",
    "cart_created": "04/25/2021 12:14:09",
    "cart_expiry": "05/02/2021 12:14:05",
    "cart_source": "cocart",
    "link": "https://example.com/wp-json/cocart/v2/session/8f36f08beca94f2b51faedcb7c6864b8"
  }
]

View Cart in Session

This API helps you retrieve a specified session and return the cart details.

HTTP request

GET
/wp-json/cocart/v2/session/<cart_key>
curl -X GET https://example.com/wp-json/cocart/v2/session/<cart_key> \
  -u username:password \
  -H "Content-Type: application/json"
// import CoCartAPI from "@cocart/cocart-rest-api"; // Supports ESM
const CoCartAPI = require("@cocart/cocart-rest-api").default;

const CoCart = new CoCartAPI({
  url: "https://example.com",
  consumerKey: 'sebtest123',
  consumerSecret: 'happycoding24'
});

CoCart.get("session/<cart_key>")
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/session/<cart_key>",
  headers: {
      "Authorization": "Basic " + btoa('username:password'),
  },
  method: "GET",
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/session/<cart_key>",
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
    'Authorization: Basic ' . base64_encode($username . ':' . $password)
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v2/session/<cart_key>' );
$body = wp_remote_retrieve_body( $response );
{
  "cart_hash": "475c7af8e8881aaa1302fdbae3bc93e0",
  "cart_key": "1",
  "currency": {
    "currency_code": "GBP",
    "currency_symbol": "£",
    "currency_minor_unit": 2,
    "currency_decimal_separator": ".",
    "currency_thousand_separator": ",",
    "currency_prefix": "£",
    "currency_suffix": ""
  },
  "customer": {
    "billing_address": {
      "billing_first_name": "Sebastien Dumont",
      "billing_last_name": "Dumont",
      "billing_company": "",
      "billing_country": "FR",
      "billing_address_1": "1",
      "billing_address_2": "",
      "billing_postcode": "12345",
      "billing_city": "Town",
      "billing_state": "",
      "billing_phone": "15103267814",
      "billing_email": "mailme@sebastiendumont.com"
    },
    "shipping_address": {
      "shipping_first_name": "Sebastien Dumont",
      "shipping_last_name": "Dumont",
      "shipping_company": "",
      "shipping_country": "FR",
      "shipping_address_1": "1",
      "shipping_address_2": "",
      "shipping_postcode": "12345",
      "shipping_city": "Town",
      "shipping_state": ""
    }
  },
  "items": [
    {
      "item_key": "f88f1e366aab64913744154e427ade89",
      "id": 1050,
      "name": "Virtual Product",
      "title": "Virtual Product",
      "price": "1.00",
      "quantity": {
        "value": 1,
        "min_purchase": 1,
        "max_purchase": -1
      },
      "tax_data": {
        "subtotal": [],
        "total": []
      },
      "totals": {
        "subtotal": 1,
        "subtotal_tax": 0,
        "total": 1,
        "tax": 0
      },
      "slug": "virtual-product",
      "meta": {
        "product_type": "simple",
        "sku": "smile",
        "dimensions": {
          "length": "",
          "width": "",
          "height": "",
          "unit": "cm"
        },
        "weight": 0,
        "variation": []
      },
      "cart_item_data": [],
      "featured_image": "https://example.com/wp-content/uploads/2021/04/smile-324x172.png"
    },
    {
      "item_key": "47686bc78b514a82756f71ddb661ea02",
      "id": 1015,
      "name": "T-shirt with logo",
      "title": "T-shirt with logo",
      "price": "12.00",
      "quantity": {
        "value": 1,
        "min_purchase": 1,
        "max_purchase": -1
      },
      "tax_data": {
        "subtotal": [],
        "total": []
      },
      "totals": {
        "subtotal": 12,
        "subtotal_tax": 0,
        "total": 12,
        "tax": 0
      },
      "slug": "t-shirt-with-logo",
      "meta": {
        "product_type": "simple",
        "sku": "Woo-tshirt-logo",
        "dimensions": {
          "length": "",
          "width": "",
          "height": "",
          "unit": "cm"
        },
        "weight": 0,
        "variation": []
      },
      "cart_item_data": [],
      "featured_image": "https://example.com/wp-content/uploads/2021/02/t-shirt-with-logo-1-324x324.jpg"
    },
    {
      "item_key": "f28cd9f0560070670a861d86462b8f14",
      "id": 90,
      "name": "Beanie with Logo",
      "title": "Beanie with Logo",
      "price": "18.00",
      "quantity": {
        "value": 1,
        "min_purchase": 1,
        "max_purchase": -1
      },
      "tax_data": {
        "subtotal": [],
        "total": []
      },
      "totals": {
        "subtotal": 18,
        "subtotal_tax": 0,
        "total": 18,
        "tax": 0
      },
      "slug": "beanie-with-logo",
      "meta": {
        "product_type": "simple",
        "sku": "Woo-beanie-logo",
        "dimensions": {
          "length": "",
          "width": "",
          "height": "",
          "unit": "cm"
        },
        "weight": 0,
        "variation": []
      },
      "cart_item_data": [],
      "featured_image": "https://example.com/wp-content/uploads/2021/02/beanie-with-logo-1-324x324.jpg"
    },
    {
      "item_key": "80f119e2ee66d2d8a0b601f695c305d8",
      "id": 82,
      "name": "Single",
      "title": "Single",
      "price": "2.00",
      "quantity": {
        "value": 1,
        "min_purchase": 1,
        "max_purchase": -1
      },
      "tax_data": {
        "subtotal": [],
        "total": []
      },
      "totals": {
        "subtotal": 2,
        "subtotal_tax": 0,
        "total": 2,
        "tax": 0
      },
      "slug": "single",
      "meta": {
        "product_type": "simple",
        "sku": "woo-single",
        "dimensions": {
          "length": "",
          "width": "",
          "height": "",
          "unit": "cm"
        },
        "weight": 0,
        "variation": []
      },
      "cart_item_data": [],
      "featured_image": "https://example.com/wp-content/uploads/2021/02/single-1-324x324.jpg"
    }
  ],
  "item_count": 6,
  "items_weight": 0,
  "coupons": [
    {
      "coupon": "testcoupon",
      "label": "Coupon: testcoupon",
      "saving": "-500",
      "saving_html": "-£5.00"
    }
  ],
  "needs_payment": true,
  "needs_shipping": true,
  "shipping": {
    "total_packages": 1,
    "show_package_details": false,
    "has_calculated_shipping": true,
    "packages": {
      "default": {
        "package_name": "Shipping",
        "rates": {
          "flat_rate:1": {
            "key": "flat_rate:1",
            "method_id": "flat_rate",
            "instance_id": 1,
            "label": "Flat rate",
            "cost": "20.00",
            "html": "Flat rate: £20.00",
            "taxes": [],
            "chosen_method": true
          }
        },
        "package_details": "",
        "index": 0,
        "chosen_method": "flat_rate:1",
        "formatted_destination": "1, 12345 TOWN"
      }
    }
  },
  "fees": [],
  "taxes": [],
  "totals": {
    "subtotal": "19200",
    "subtotal_tax": "0",
    "fee_total": "0",
    "fee_tax": "0",
    "discount_total": "500",
    "discount_tax": "0",
    "shipping_total": "2000",
    "shipping_tax": "0",
    "total": "20700",
    "total_tax": "0"
  },
  "removed_items": [],
  "cross_sells": [],
  "notices": []
}

View Cart Items in Session

This API helps you retrieve a specified session and returns just the cart items.

HTTP request

GET
/wp-json/cocart/v2/session/<cart_key>/items
curl -X GET https://example.com/wp-json/cocart/v2/session/<cart_key>/items \
  -u username:password \
  -H "Content-Type: application/json"
// import CoCartAPI from "@cocart/cocart-rest-api"; // Supports ESM
const CoCartAPI = require("@cocart/cocart-rest-api").default;

const CoCart = new CoCartAPI({
  url: "https://example.com",
  consumerKey: 'sebtest123',
  consumerSecret: 'happycoding24'
});

CoCart.get("session/<cart_key>/items")
.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.
});
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/session/<cart_key>/items",
  headers: {
      "Authorization": "Basic " + btoa('username:password'),
  },
  method: "GET",
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/session/<cart_key>/items",
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'User-Agent: CoCart API/v2',
    'Authorization: Basic ' . base64_encode($username . ':' . $password)
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v2/session/<cart_key>/items' );
$body = wp_remote_retrieve_body( $response );
{
  "f88f1e366aab64913744154e427ade89": {
    "item_key": "f88f1e366aab64913744154e427ade89",
    "id": 1050,
    "name": "Virtual Product",
    "title": "Virtual Product",
    "price": "1.00",
    "quantity": {
      "value": 1,
      "min_purchase": 1,
      "max_purchase": -1
    },
    "tax_data": {
      "subtotal": [],
      "total": []
    },
    "totals": {
      "subtotal": 1,
      "subtotal_tax": 0,
      "total": 1,
      "tax": 0
    },
    "slug": "virtual-product",
    "meta": {
      "product_type": "simple",
      "sku": "smile",
      "dimensions": {
        "length": "",
        "width": "",
        "height": "",
        "unit": "cm"
      },
      "weight": 0,
      "variation": []
    },
    "cart_item_data": [],
    "featured_image": "https://example.com/wp-content/uploads/2021/04/smile-324x172.png"
  },
  "47686bc78b514a82756f71ddb661ea02": {
    "item_key": "47686bc78b514a82756f71ddb661ea02",
    "id": 1015,
    "name": "T-shirt with logo",
    "title": "T-shirt with logo",
    "price": "12.00",
    "quantity": {
      "value": 1,
      "min_purchase": 1,
      "max_purchase": -1
    },
    "tax_data": {
      "subtotal": [],
      "total": []
    },
    "totals": {
      "subtotal": 12,
      "subtotal_tax": 0,
      "total": 12,
      "tax": 0
    },
    "slug": "t-shirt-with-logo",
    "meta": {
      "product_type": "simple",
      "sku": "Woo-tshirt-logo",
      "dimensions": {
        "length": "",
        "width": "",
        "height": "",
        "unit": "cm"
      },
      "weight": 0,
      "variation": []
    },
    "cart_item_data": [],
    "featured_image": "https://example.com/wp-content/uploads/2021/02/t-shirt-with-logo-1-324x324.jpg"
  },
  "f28cd9f0560070670a861d86462b8f14": {
    "item_key": "f28cd9f0560070670a861d86462b8f14",
    "id": 90,
    "name": "Beanie with Logo",
    "title": "Beanie with Logo",
    "price": "18.00",
    "quantity": {
      "value": 1,
      "min_purchase": 1,
      "max_purchase": -1
    },
    "tax_data": {
      "subtotal": [],
      "total": []
    },
    "totals": {
      "subtotal": 18,
      "subtotal_tax": 0,
      "total": 18,
      "tax": 0
    },
    "slug": "beanie-with-logo",
    "meta": {
      "product_type": "simple",
      "sku": "Woo-beanie-logo",
      "dimensions": {
        "length": "",
        "width": "",
        "height": "",
        "unit": "cm"
      },
      "weight": 0,
      "variation": []
    },
    "cart_item_data": [],
    "featured_image": "https://example.com/wp-content/uploads/2021/02/beanie-with-logo-1-324x324.jpg"
  },
  "80f119e2ee66d2d8a0b601f695c305d8": {
    "item_key": "80f119e2ee66d2d8a0b601f695c305d8",
    "id": 82,
    "name": "Single",
    "title": "Single",
    "price": "2.00",
    "quantity": {
      "value": 1,
      "min_purchase": 1,
      "max_purchase": -1
    },
    "tax_data": {
      "subtotal": [],
      "total": []
    },
    "totals": {
      "subtotal": 2,
      "subtotal_tax": 0,
      "total": 2,
      "tax": 0
    },
    "slug": "single",
    "meta": {
      "product_type": "simple",
      "sku": "woo-single",
      "dimensions": {
        "length": "",
        "width": "",
        "height": "",
        "unit": "cm"
      },
      "weight": 0,
      "variation": []
    },
    "cart_item_data": [],
    "featured_image": "https://example.com/wp-content/uploads/2021/02/single-1-324x324.jpg"
  }
}

WP-CLI

GitHub Mark Logo Edit on GitHub

CoCart CLI offers the ability to manage CoCart via the command-line, using WP CLI. The documentation here covers the version of WC CLI that started shipping in CoCart 3.0.0 and later.

What is WP-CLI?

For those who have never heard before WP-CLI, here's a brief description extracted from the official website.

CoCart Commands

All CoCart related commands are grouped into wp cocart command. The available commands (as of CoCart v3.0) are:

Command Description
wp cocart update Updates the CoCart database.
wp cocart version Returns the version of CoCart installed.
wp cocart db-version Returns the database version of CoCart installed.

Extending CoCart

GitHub Mark Logo Edit on GitHub

CoCart is developer friendly even for extending support for other product types. This is useful for WooCommerce extensions developed by a 3rd party. Take the WooCommerce Mix and Match Products extension for example.

Add to Cart Handler

GitHub Mark Logo View source

The handler allows support for other product types besides simple and variable products.

It allows you to override the product type to trigger the product handler before the item is added to the cart.

This is handy if you don't need to provide your own product handler for your custom product type but just need to use a handler already in the core of CoCart.

In CoCart Pro this filter is used so simple subscriptions and variable subscriptions can be added as a simple or variable product as there is not difference between the two when being added to the cart.

<?php
add_filter( 'cocart_add_to_cart_handler', 'my_add_to_cart_handler' );

function my_add_to_cart_handler( $handler ) {
  if ( $handler == 'my-custom-product-type' ) {
    return 'simple';
  }
}

Add to Cart Validation

GitHub Mark Logo View source

This filter allows plugin developers to pass their own validation before an item is added to the cart. Unlike the woocommerce_add_to_cart_validation filter, you can not pass form requests. If you have custom data for the product that must be validated, it must be passed via $cart_item_data and checked to see if it exists.

In addition, to save time identifying the product type, it is also passed through automatically for you via $product_type which saves a database request and increases loading speed.

Parameter Type Description
$passed_validation bool The status of adding an item to cart. Default is true.
$product_id integer The product ID.
$quantity float The quantity of the product.
$variation_id integer The variation of the product being added to the cart.
$variation array Attribute values.
$cart_item_data array Cart item data passed with the item.
$product_type string The product type.
<?php
add_filter( 'cocart_add_to_cart_validation', 'my_add_to_cart_validation', 10, 7 );

function my_add_to_cart_validation( $passed_validation, $product_id, $quantity, $variation_id, $variation, $cart_item_data, $product_type ) {
  // Add your validation here and simply return true|false.
  return true;
}

Add cart item data

GitHub Mark Logo View source

<?php
add_filter( 'cocart_add_cart_item_data', 'my_add_cart_item_data', 10, 7 );

function my_add_cart_item_data( $cart_item_data ) {
  // Add your validation here and simply return true|false.
  return $cart_item_data;
}

Extending Schema

Details coming soon.

Actions

GitHub Mark Logo Edit on GitHub

The cart API has a number of action hooks that you can use to extend the API to your needs.

See the tweaks plugin for examples.

Get Cart

Perhaps you need to apply something to the whole of the cart before it returns or send a notification. The choice is yours.

Use hook name: cocart_get_cart

Parameter Type Description
$cart_contents array An array of items added to the cart.

Clear Cart

Could be used to send a registered customer an email once they have emptied their cart. 😢

Use hook name: cocart_cart_cleared

Item Added

You can do something once an item has been added to the cart.

Use hook name: cocart_item_added_to_cart

Parameter Type Description
$item_key string The cart item key of the product in the cart.
$item_added array The details of the added item.

Item Removed

Use hook name: cocart_item_removed

Parameter Type Description
$current_data array The details of the item removed.

Item Restored

Use hook name: cocart_item_restored

Parameter Type Description
$current_data array The details of the item restored.

Item Quantity Changed

Should you need to change some other detail for the updated item.

Use hook name: cocart_item_quantity_changed

Parameter Type Description
$cart_item_key string The cart item key of the product in the cart.
$new_data array The details of the item updated.

Filters

GitHub Mark Logo Edit on GitHub

The cart API has a number of filters that you can use to change or control the API to your needs.

See the tweaks plugin for examples.

Cart Data

Return Cart Contents

GitHub Mark Logo View source

If you are in need to change the formatting of the returned cart contents, this filter cocart_return_cart_contents is for you.

In CoCart Pro you can filter the same results for removed cart contents.

If you have Get Cart Enhanced add-on installed, this filter will already be used but can still be used again to apply your own.

<?php
// Returns the cart contents without the cart item key as the parent array.
add_filter( 'cocart_return_cart_contents', 'remove_parent_cart_item_key', 0 );

function remove_parent_cart_item_key( $cart_contents ) {
  $new_cart_contents = array();

  foreach ( $cart_contents as $item_key => $cart_item ) {
    $new_cart_contents[] = $cart_item;
  }

  return $new_cart_contents;
}

Return Cart Contents in Session

GitHub Mark Logo View source

Identical to cocart_return_cart_contents filter, only this one is used to filter the cart contents returned for a cart in session that you have requested to view specifically.

<?php
add_filter( 'cocart_return_cart_session_contents', 'remove_parent_cart_item_key' );

function remove_parent_cart_item_key( $cart_contents ) {
  $new_cart_contents = array();

  foreach ( $cart_contents as $item_key => $cart_item ) {
    $new_cart_contents[] = $cart_item;
  }

  return $new_cart_contents;
}

Empty Cart

GitHub Mark Logo View source

If you don't want to return an empty array when the cart is empty, you can return a custom response instead.

If you have Get Cart Enhanced add-on installed, this filter will already be used but can still be used again to apply your own.

<?php
add_filter( 'cocart_return_empty_cart', 'empty_cart_message' );

function empty_cart_message() {
  return 'Your cart is empty! Go and fill it.';
}

Thumbnail size

GitHub Mark Logo View source

By default, the product thumbnail returns using woocommerce_thumbnail image size. You can change this simply by returning the image size registered on your WordPress installation with this filter cocart_item_thumbnail_size.

<?php
add_filter( 'cocart_item_thumbnail_size', 'thumbnail_size' );

function thumbnail_size() {
  return 'thumbnail';
}

Return more item details

GitHub Mark Logo View source

Sometimes you just need more product data for the items added. You can do so using cocart_cart_contents filter.

Parameter Type Description
$cart_contents array An array of items added to the cart.
$item_key string Unique generated ID for the item in cart.
$cart_item array An array of details of the item in the cart.
$_product object The product data of the item.
<?php
add_filter( 'cocart_cart_contents', 'return_product_weight', 15, 4 );

function return_product_sku( $cart_contents, $item_key, $cart_item, $_product ) {
  $cart_contents[$item_key]['sku'] = $_product->get_sku();

  return $cart_contents;
}

Overrides

Sold Individually

GitHub Mark Logo View source

With this filter you can force items sold individually to have more or less.

<?php
add_filter( 'cocart_add_to_cart_sold_individually_quantity', 'override_sold_individual_quantity' );

function override_sold_individual_quantity() {
  return 2;
}

OK to add item?

GitHub Mark Logo View source

Want to stop an item being added and return a custom message should it require an item not in the cart first.

Use the cocart_ok_to_add and cocart_ok_to_add_response filters.

Parameter Type Description
$status bool The status of adding an item to cart.
$response string The returned message.
$product_data object The product data of the item.
<?php
add_filter( 'cocart_ok_to_add', 'requires_specific_item', 10, 2 );

function requires_specific_item( $status, $product_data ) {
  $cart_contents = isset( WC()->cart ) ? WC()->cart->get_cart() : WC()->session->cart;

  $required_product_id = '123'; // Replace with real product ID number.

  foreach ( $cart_contents as $item_key => $cart_item ) { 
      // If required product ID does not exist return false.
      if ( $cart_item['id'] != $required_product_id ) {
        $status = false;
      }
  }

  return $status;
}
<?php
add_filter( 'cocart_ok_to_add_message', 'requires_specific_item', 10, 2 );

function requires_specific_item_response( $response, $product_data ) {
  $response = __( 'This item requires a specific item to be added first to the cart.' );

  return $response;
}

Product name

GitHub Mark Logo View source

You can override the product name when cart is returned or just added to the cart.

Parameter Type Description
$name string Original name of product.
$_product WC_Product The product data.
$cart_item array Cart item.
$item_key string Cart item key.
<?php
add_filter( 'cocart_product_name', 'override_product_name', 10, 4 );

function override_product_name( $name, $_product, $cart_item, $item_key ) {
  return 'This product is special';
}
<?php
add_filter( 'cocart_item_added_product_name', 'override_product_name', 10, 3 );

function override_product_name( $name, $_product, $item_key ) {
  return 'This product is special';
}

Product title

GitHub Mark Logo View source

You can override the product title when cart is returned or just added to the cart.

Parameter Type Description
$name string Original name of product.
$_product WC_Product The product data.
$cart_item array Cart item.
$item_key string Cart item key.
<?php
add_filter( 'cocart_product_title', 'override_product_title', 10, 4 );

function override_product_title( $name, $_product, $cart_item, $item_key ) {
  return 'This product is awesome';
}
<?php
add_filter( 'cocart_item_added_product_title', 'override_product_title', 10, 3 );

function override_product_title( $name, $_product, $item_key ) {
  return 'This product is awesome';
}

Product thumbnail source

GitHub Mark Logo View source

This filter in particular allows you to change the source of the image for a specific item. The source could be external for example.

Parameter Type Description
$thumbnail_src string The original thumbnail source.
$cart_item array Cart item.
$item_key string Cart item key.
<?php
add_filter( 'cocart_item_thumbnail_src', 'override_item_thumbail_src', 10, 3 );

function override_item_thumbail_src( $thumbnail_src, $cart_item, $item_key ) {
  return 'https://placekitten.com/100/100';
}

Product quantity

GitHub Mark Logo View source

You could use this filter to force certain products to be added to the cart with a certain quantity or for example use the $quantity value to calculate double the amount if your doing something unique for your store.

Parameter Type Description
$quantity float The original quantity of the item.
$product_id integer The product ID.
$variation_id integer The variation ID.
$variation array The variation data.
$cart_item_data array Cart item data passed with the item.
<?php
add_filter( 'cocart_add_to_cart_quantity', 'override_product_quantity', 10, 5 );

function override_product_quantity( $quantity, $product_id, $variation_id, $variation, $cart_item_data ) {
  // Make sure you specify the product ID you want to override.
  if ( $product_id == 32 ) {
    return 3; // Make sure that you just return the number and not override the `$quantity` variable.
  }

  // Return `$quantity` variable for all other products that you are NOT overriding.
  return $quantity;
}

Cannot Add Product Type to Cart Message

GitHub Mark Logo View source

Change the returned message when you try to add a product type that cannot be added to the cart.

<?php
add_filter( 'cocart_cannot_add_product_type_to_cart_message', 'cannot_add_product_type_to_cart_message' );

function cannot_add_product_type_to_cart_message() {
  /* params: %1$s: product name, %2$s: product type */
  sprintf( 'You cannot add "%1$s" to your cart as it is a "%2$s" product.', $product_data->get_name(), $product_data->get_type() );
}

Cart Item Removed Message

GitHub Mark Logo View source

Parameter Type Description
$message string The original message.
$_product WC_Product The product data.
<?php
add_filter( 'cocart_cart_item_removed_message', 'cart_item_removed_message', 10, 2 );

function cart_item_removed_message( $message, $_product ) {
  return sprintf( '%s has been removed from your cart because it can no longer be purchased. Please contact us if you need assistance.', $_product->get_name() );
}

Session Management

GitHub Mark Logo View source

This filter allows you to disable support for the CoCart cookie that handles the session for customers. Use only if you are using the alternative method for customers.

<?php
add_filter( 'cocart_cookie_supported', function() { return false; });

GitHub Mark Logo View source

This could be changed to include your store brand name.

<?php
add_filter( 'cocart_cookie', 'my_cocart_cookie_name' );

function my_cocart_cookie_name() {
  return 'randomloot_store_' . COOKIEHASH;
}

GitHub Mark Logo View source

Be default this will set as true if your site has SSL enabled. Otherwise it will return false. Filtering will force it.

<?php
add_filter( 'cocart_cart_use_secure_cookie', function() { return true; });

Cart Expiration

GitHub Mark Logo View source

There are two filters for cart expiration. The first is used to detect if we are close to expiration of the cart. The second is used to set how long the cart will be stored until expired.

<?php
add_filter( 'cocart_cart_expiring', function() { return DAY_IN_SECONDS * 3; });
add_filter( 'cocart_cart_expiration', function() { return DAY_IN_SECONDS * 4; });

Empty Cart Expiration

Deprecated since v2.7.2

This filter allows you to change the expiration of an empty cart. Default value is 6 hours.

<?php
add_filter( 'cocart_empty_cart_expiration', function() { return HOUR_IN_SECONDS * 1; });

Generated Customer ID

GitHub Mark Logo View source

This filter allows you to change the generated customer ID for the guest customer. Use this filter with caution. Cannot be longer than 42 characters, exceed it and the database will not save the cart.

<?php
add_filter( 'cocart_customer_id', 'my_custom_generate_customer_id' );

function my_custom_generate_customer_id( $hasher ) {
  return md5( $hasher->get_random_bytes( 42 ) );
}

Cart Loaded Successful Message

GitHub Mark Logo View source

<?php
add_filter( 'cocart_cart_loaded_successful_message', 'cart_loaded_successful_message' );

function cart_loaded_successful_message( $message ) {
  return sprintf( 'Your 🛒 cart has been transferred over. You may %1$scontinue shopping%3$s or %2$scheckout%3$s.', '<a href="' . wc_get_page_permalink( "shop" ) . '">', '<a href="' . wc_get_checkout_url() . '">', '</a>' ) );
}

API Access

CoCart Logging

GitHub Mark Logo View source

If you are debugging CoCart during your development, enabling the logger is a great tool to have.

Then when making any request, you can view the logs created via your WordPress dashboard under WooCommerce > System Status > Logs

I personally like to change the WooCommerce log handler to be stored via the database which you set in your wp-config.php file.

WooCommerce Log Handler

<?php
define( 'WC_LOG_HANDLER', 'WC_Log_Handler_DB' );

CoCart Logging filter

<?php
add_filter( 'cocart_logging', function() { return true; });

CORS: Allow all cross origin headers

Introduced filter since v2.2

GitHub Mark Logo View source

If you are getting a warning about cross origin headers then you may need to enable support for it. Simply apply this filter and the headers will set for you with no further configuration.

<?php
add_filter( 'cocart_disable_all_cors', function() { return false; });

Set Allow Origin Header

Introduced filter since v2.5.1

GitHub Mark Logo View source

For added security when you go into production. Set 'Access-Control-Allow-Origin' header to be more specific. Allow all cross origin headers must be enabled first as shown above.

<?php
add_filter( 'cocart_allow_origin', function() { return 'https://wp-demo.cocart.xyz'; });

Is REST API Request?

Introduced filter since v2.7.0

GitHub Mark Logo View source

This filter allows you to run your own API check-up with CoCart.

<?php
add_filter( 'cocart_is_rest_api_request', function() {
  $rest_prefix         = trailingslashit( rest_get_url_prefix() );
  $is_rest_api_request = ( false !== strpos( $_SERVER['REQUEST_URI'], $rest_prefix . 'myrestapi/' ) );

  return $is_rest_api_request;
});

Introduced filter since v2.9.1

GitHub Mark Logo View source

This filter allows you to change the SameSite attribute applied to the CoCart cookie.

<?php
add_filter( 'cocart_cookie_samesite', function() {
    return "None; Secure";
});

Misc

Merge Cart Items

GitHub Mark Logo View source

This filter allows you to change how the items are merged together before loaded into session when requesting to keep the current cart via the web.

<?php
/**
 * @param  `$new_cart_content` - Returns the cart items merged from both cart in session and the cart requested to load.
 * @param  `$new_cart` - Returns the requested cart to load.
 * @param  `$cart_in_session` - Returns the current cart contents, if any.
 * @return `$new_cart_content` - Returns your results of the cart contents.
 */
add_filter( 'cocart_merge_cart_content', 'merge_cart_contents', 10, 3 );

function merge_cart_contents( $new_cart_content, $new_cart, $cart_in_session ) {
  return $new_cart_content;
}

Authenticate User ID

Introduced filter since v2.6.0

GitHub Mark Logo View source

Overrides the determined user ID when authenticating. NOTE This will only be active if not already authenticated.

<?php
add_filter( 'cocart_authenticate', function(){});

CoCart Add-ons

CoCart Lite is just the tip of the iceberg. These add-ons take your headless build to the next level.

CoCart Pro

GitHub Mark Logo Edit on GitHub

CoCart Pro, an extension that completes the CoCart API package with more control over the cart from coupons, shipping methods to additional fees and more.

Purchase here

The following table shows API versions present in each major version of CoCart Pro:

API Version CoCart Pro Version WC Version WP Version Documentation
v1 1.0.x or later 4.0.x or later 4.4 or later view api documentation

CoCart Products

GitHub Mark Logo Edit on GitHub

CoCart Products provides a public API version of accessing products, categories, tags, attributes and even reviews without the need to authenticate. Designed more suited for the frontend so none of the shop manager only features are exploited and it comes with a few more parameters to filter and return the products the way you want or need.

Purchase here

The following table shows API versions present in each major version of CoCart Products:

API Version CoCart Version WC Version WP Version Documentation
v1 2.0.x or later 4.0.x or later 5.2 or later view api documentation

WooCommerce Extensions

GitHub Mark Logo Edit on GitHub

These extensions either support CoCart or is supported in CoCart Pro.

Mix and Match Products

Selling cases of wine? A dozen donuts? Fruit baskets? Six-packs of T-shirts? Mix and Match Products is ideal for offering similar products in bulk containers. Perfect for encouraging customers to buy in bulk without forcing them to buy items that don’t interest them.

Add item to Cart

Once you have setup "Mix and Match Products" WooCommerce extension. Here is how you can add a container with the customers selected items and quantity.

Example of adding a Mix and Match Product

CoCart.post("cart/add-item", {
  "id": "1102",
  "quantity": "5",
  "cart_item_data": {
      "mnm_config": [
          {
              "product_id": 987,
              "quantity": 1
          },
          {
              "product_id": 1001,
              "quantity": 2
          },
          {
              "product_id": 1003,
              "quantity": 3
          }
      ]
  },
})
.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.
});
curl -X POST https://example.com/wp-json/cocart/v2/cart/add-item \
  -H "Content-Type: application/json" \
  -d '{
    "id": "1102",
    "quantity": "2",
    "cart_item_data": {
        "mnm_config": [
            {
                "product_id": 987,
                "quantity": 1
            },
            {
                "product_id": 1001,
                "quantity": 2
            },
            {
                "product_id": 1003,
                "quantity": 3
            }
        ]
    }
}'
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart/add-item",
  method: "POST",
  data: JSON.stringify({
    "id": "1102",
    "quantity": "5",
    "cart_item_data": {
        "mnm_config": [
            {
                "product_id": 987,
                "quantity": 1
            },
            {
                "product_id": 1001,
                "quantity": 2
            },
            {
                "product_id": 1003,
                "quantity": 3
            }
        ]
    },
  }),
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

$args = array(
  'id' => '1102',
  'quantity' => '5',
  'cart_item_data' => array(
      'mnm_config' => array(
          array(
              'product_id' => 987,
              'quantity' => 1
          ),
          array(
              'product_id' => 1001,
              'quantity' => 2
          ),
          array(
              'product_id' => 1003,
              'quantity' => 3
          )
      )
  )
);

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart/add-item",
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $args,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'Content-Type: application/json',
    'User-Agent: CoCart API/v1',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$args = array(
  'headers' => array(
    'Content-Type' => 'application/json; charset=utf-8',
  ),
  'body' => wp_json_encode( [
    'id' => '1102',
    'quantity' => '5',
    'cart_item_data' => array(
        'mnm_config' => array(
            array(
                'product_id' => 987,
                'quantity' => 1
            ),
            array(
                'product_id' => 1001,
                'quantity' => 2
            ),
            array(
                'product_id' => 1003,
                'quantity' => 3
            )
        )
    )
  ] ),
  'timeout' => 30
);
$response = wp_remote_post( 'https://example.com/wp-json/cocart/v2/cart/add-item', $args );
$body = wp_remote_retrieve_body( $response );
{
    "6563b32f054b00c7ed83ce4c9bb9eedd": {
        "mnm_config": {
            "987": {
                "product_id": 987,
                "quantity": 1
            },
            "1001": {
                "product_id": 1001,
                "quantity": 2
            },
            "1003": {
                "product_id": 1003,
                "quantity": 3
            }
        },
        "mnm_contents": [
            "8e9868e336b9bafe4722c31ade00a8f6",
            "a29fe85f04188ccc5a7106dec6f5ca89",
            "4531239fed8c9875e0cce609b86be85a"
        ],
        "key": "6563b32f054b00c7ed83ce4c9bb9eedd",
        "product_id": 1102,
        "variation_id": 0,
        "variation": [],
        "quantity": 1,
        "data_hash": "d88f7e7e5dfa45731252a34e3e64325c",
        "line_tax_data": {
            "subtotal": [],
            "total": []
        },
        "line_subtotal": 9.7013,
        "line_subtotal_tax": 0,
        "line_total": 9.7013,
        "line_tax": 0,
        "data": {
            "product_type": "mix-and-match",
            "is_nyp": false
        },
        "product_name": "Mix and Match Products",
        "product_title": "Mix and Match Products",
        "product_price": "£2.00"
    },
    "8e9868e336b9bafe4722c31ade00a8f6": {
        "mnm_container": "6563b32f054b00c7ed83ce4c9bb9eedd",
        "mnm_child_id": 1102,
        "product_id": 987,
        "variation_id": 0,
        "variation": [],
        "quantity": 1,
        "line_tax_data": {
            "subtotal": [],
            "total": []
        },
        "line_subtotal": 1.28355,
        "line_subtotal_tax": 0,
        "line_total": 1.28355,
        "line_tax": 0,
        "data": {},
        "product_name": "Cupcake",
        "product_title": "Cupcake",
        "product_price": "£1.28"
    },
    "a29fe85f04188ccc5a7106dec6f5ca89": {
        "mnm_container": "6563b32f054b00c7ed83ce4c9bb9eedd",
        "mnm_child_id": 1102,
        "product_id": 1001,
        "variation_id": 0,
        "variation": [],
        "quantity": 2,
        "line_tax_data": {
            "subtotal": [],
            "total": []
        },
        "line_subtotal": 2.5671,
        "line_subtotal_tax": 0,
        "line_total": 1.28355,
        "line_tax": 0,
        "data": {},
        "product_name": "Turquoise Cupcake",
        "product_title": "Turquoise Cupcake",
        "product_price": "£1.28"
    },
    "4531239fed8c9875e0cce609b86be85a": {
        "mnm_container": "6563b32f054b00c7ed83ce4c9bb9eedd",
        "mnm_child_id": 1102,
        "product_id": 1003,
        "variation_id": 0,
        "variation": [],
        "quantity": 3,
        "line_tax_data": {
            "subtotal": [],
            "total": []
        },
        "line_subtotal": 3.85065,
        "line_subtotal_tax": 0,
        "line_total": 1.28355,
        "line_tax": 0,
        "data": {},
        "product_name": "Buttercup and Bumblebee Cupcakes",
        "product_title": "Buttercup and Bumblebee Cupcakes",
        "product_price": "£1.28"
    }
}

Retrieve a product

If you are using CoCart Products API, any Mix and Match Product will return additional product data under a new array variable mnm_data. View example.

Name Your Price

The Name Your Price plugin extension lets you be flexible in what price you are willing to accept for selected products. You can use this plugin to accept donations or to take a new approach to selling products. You can suggest a price to your customers and optionally enforce a minimum acceptable price, or leave it entirely in the hands of the customer.

Add item to Cart

Once you have setup "Name Your Price" for your particular products. Here is how you can apply the customers requested price for the product when adding to cart.

Example of adding an item with a custom price.

CoCart.post("cart/add-item", {
  "id": "1102",
  "quantity": "5",
  "cart_item_data": {
      "nyp": 24
  }
})
.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.
});
curl -X POST https://example.com/wp-json/cocart/v2/cart/add-item \
  -H "Content-Type: application/json" \
  -d '{
    "id": "129",
    "quantity": "1",
    "cart_item_data": {
      "nyp": 24
    }
  }'
$.ajax({
  url: "https://example.com/wp-json/cocart/v2/cart/add-item",
  method: "POST",
  data: JSON.stringify({
    "id": "129",
    "quantity": "1",
    "cart_item_data": {
      "nyp": 24
    }
  }),
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

$args = array(
  'id' => '129',
  'quantity' => '1',
  'cart_item_data' => array(
    'nyp' => 24
  )
);

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v2/cart/add-item",
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $args,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => array(
    'Accept: application/json',
    'Content-Type: application/json',
    'User-Agent: CoCart API/v1',
  )
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$args = array(
  'headers' => array(
    'Content-Type' => 'application/json; charset=utf-8',
  ),
  'body' => wp_json_encode( [
    'id' => '129',
    'quantity' => '1',
    'cart_item_data' => array(
      'nyp' => 24
    )
  ] ),
  'timeout' => 30
);
$response = wp_remote_post( 'https://example.com/wp-json/cocart/v2/cart/add-item', $args );
$body = wp_remote_retrieve_body( $response );
{
    "nyp": "24",
    "key": "1dc5e4af26b22d63451acb95d2b9deba",
    "product_id": 129,
    "variation_id": 0,
    "variation": [],
    "quantity": 1,
    "data": {},
    "data_hash": "b5c1d5ca8bae6d4896cf1807cdf763f0",
    "line_tax_data": {
        "subtotal": [],
        "total": []
    },
    "line_subtotal": 24,
    "line_subtotal_tax": 0,
    "line_total": 24,
    "line_tax": 0,
    "product_name": "Name your price",
    "product_title": "Name your price",
    "product_price": "£24.00"
}

wp-config.php

GitHub Mark Logo Edit on GitHub

For more handling over CoCart for your store or a client, you will find that using the wp-config.php file is the best place to setup certain conditions.

Uninstall

To prevent any data loss when uninstalling CoCart from the backend and to ensure only the site owner can perform this action. You need to enable the ability to remove it.

<?php
/**
 * Allows the full un-installation of CoCart.
 */
define( 'COCART_REMOVE_ALL_DATA', true );

White Labelling

If you are developing a headless store for a client and need to hide CoCart. Enabling white label mode comes in handy if that is something you would want.

Enabling this hides CoCart completely from the backend including the admin menu, plugin row links, plugin notices, WooCommerce inbox notices and WooCommerce System Status information.

<?php
/**
 * Hides CoCart from the WordPress dashboard.
 */
define( 'COCART_WHITE_LABEL', true );

Load Cart for the Web

Introduced filter since v2.8.2

In addition to white labelling, you can filter the parameter name cocart-load-cart `to what ever you like.

<?php
/**
 * Change the parameter name for loading the cart via the web.
 */
add_filter( 'cocart_load_cart_query_name', function() { return 'my-cart'; });

Libraries

GitHub Mark Logo Edit on GitHub

npm install --save @cocart/cocart-rest-api

// import CoCartAPI from "@cocart/cocart-rest-api"; // Supports ESM
const CoCartAPI = require("@cocart/cocart-rest-api").default;

const CoCart = new CoCartAPI({
  url: "https://example.com",
  version: "cocart/v2"
});

Tools

GitHub Mark Logo Edit on GitHub

Some useful tools you can use to access the API include:

If you use Postman you can use these collections made ready for you.

Learn more

Learn more about the REST API by checking the official WordPress REST API documentation.

Demo CoCart

GitHub Mark Logo Edit on GitHub

If you don't yet have CoCart installed or a WordPress setup ready, you can test the results in your app using the demo site prepared.

When you do make a request, make sure you use https://wp-demo.cocart.xyz/ as the domain to use the demo.

Get Cart Enhanced add-on is installed so some results may appear different to the example results you see throughout the documentation. It also gives you a look at what is possible using the filters available to customize CoCart to your needs.

Adding an item

Here is an example of adding a item to the cart via the demo.

HTTP request

POST
/wp-json/cocart/v2/cart/add-item

View more on add to cart

curl -X POST https://wp-demo.cocart.xyz/wp-json/cocart/v2/cart/add-item \
  -H "Content-Type: application/json" \
  -d '{
    "id": "183",
    "quantity": "1"
  }'
CoCart.post("add-item", {
  id: "183",
  quantity: "1"
})
.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.
});
$.ajax({
  url: "https://wp-demo.cocart.xyz/wp-json/cocart/v2/cart/add-item",
  method: "POST",
  data: JSON.stringify({
    "id": "183",
    "quantity": "1"
  }),
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  complete: function (response) {
    console.log(response);
  }
});
<?php
$curl = curl_init();

$args = array(
  'id' => '183',
  'quantity' => '1'
);

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://wp-demo.cocart.xyz/wp-json/cocart/v2/cart/add-item",
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $args,
  CURLOPT_RETURNTRANSFER => true
) );

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$args = array(
  'id' => '183',
  'quantity' => '1'
);
$response = wp_remote_post( 'https://wp-demo.cocart.xyz/wp-json/cocart/v2/cart/add-item', $args );
$body = wp_remote_retrieve_body( $response );

Authenticate Customer

Test authentication as a customer via the basic method.

Username Password
demo &nm5y7^sf&hm1D5MwKLgrQeC

Products

Here is a table of products you can use to test with.

ID Variation ID Name Type Price Sold Individually Variation
183 - Beanie with Logo Simple £18.00 Yes
174 - Album Simple (Virtual) £15.00 No
163 179 Hoodie Variable £42.00 No "attribute_pa_color": "red", "attribute_logo": "No" mandatory
163 180 Hoodie Variable £45.00 No "attribute_pa_color": "green", "attribute_logo": "No" mandatory
163 181 Hoodie Variable £45.00 No "attribute_pa_color": "blue", "attribute_logo": "No" mandatory
329 - The Last of Us Part 2 - Simple (Name Your Price) Suggested: £229 No
Ellie Edition Minimum: £180
744 - Netfoobar Simple Subscription £5.99 / month with a 14-day free trial. Yes

Coupons

Here is a table of coupons you can use to test with.

Code Coupon Type Coupon Amount Description
get10offcart Percentage discount 10 Takes 10% off the cart total.
£25OFF Fixed cart discount 25 Takes £25 off the cart total.

Contribute

If you or your company use CoCart or appreciate the work I’m doing in open source, please consider purchasing CoCart Pro where you not just get the full cart experience but also support me directly so I can continue maintaining CoCart and keep evolving the project.

Please also consider starring ✨ and sharing 👍 the project repo! This helps the project getting known and grow with the community. 🙏

Thank you for your support! 🙌