Last big sale in a while. CoCart Pro and it's add-ons are 30% OFF. It's also 30% OFF recurring payments too on any tier. Use "BIGSALE2020" at checkout. Hurry. Sale ends 5th December 2020.
NAV
cURL jQuery PHP WP API

Introduction

GitHub Mark Logo Edit on GitHub

Welcome to the documentation site for CoCart, the free, open-source WordPress plugin that brings the power of WooCommerce's shopping cart via the REST API.

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 v1 which takes a first-order position in the endpoints.

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

API Version CoCart Version WC Version WP Version PHP Version
v1 2.0.x or later 4.0.x or later 5.2 or later 7.0 or later

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

I personally find using raw works best if you are passing an object of data for a variation or cart_item_data.

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/v1/item?cart_item_key=270edd69788dce200a3b395a6da6fdb7&quantity=2. All parameters are documented along each endpoint.

Getting Started

GitHub Mark Logo Edit on GitHub

Install and Activate

How to install and activate the CoCart plugin.

List of server requirements.

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”.

CoCart WordPress Plugin

CoCart is a free, open-source WordPress plugin that provides a REST API for WooCommerce to access the front-end features of your store.

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.

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

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/v1
curl -X GET https://example.com/wp-json/cocart/v1 \
  -H "Content-Type: application/json"
var settings = {
  "url": "https://example.com/wp-json/cocart/v1",
  "method": "GET"
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v1",
  CURLOPT_CUSTOMREQUEST => "GET",
  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
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v1' );
$body = wp_remote_retrieve_body( $response );

JSON response example:

{
    "namespace": "cocart/v1",
    "routes": {
        "/cocart/v1": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": {
                        "namespace": {
                            "required": false,
                            "default": "cocart/v1"
                        },
                        "context": {
                            "required": false,
                            "default": "view"
                        }
                    }
                }
            ],
            "_links": {
                "self": [
                    {
                        "href": "https://example.com/wp-json/cocart/v1"
                    }
                ]
            }
        },
        "/cocart/v1/get-cart": {
            "namespace": "cocart/v1",
            "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/v1/get-cart"
                    }
                ]
            }
        },
        "/cocart/v1/get-cart/(?P<id>[\\w]+)": {
            "namespace": "cocart/v1",
            "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/v1/get-cart/customer/(?P<id>[\\d]+)": {
            "namespace": "cocart/v1",
            "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/v1/add-item": {
            "namespace": "cocart/v1",
            "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/v1/add-item"
                    }
                ]
            }
        },
        "/cocart/v1/clear": {
            "namespace": "cocart/v1",
            "methods": [
                "POST"
            ],
            "endpoints": [
                {
                    "methods": [
                        "POST"
                    ],
                    "args": []
                }
            ],
            "_links": {
                "self": [
                    {
                        "href": "https://example.com/wp-json/cocart/v1/clear"
                    }
                ]
            }
        },
        "/cocart/v1/calculate": {
            "namespace": "cocart/v1",
            "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/v1/calculate"
                    }
                ]
            }
        },
        "/cocart/v1/count-items": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": {
                        "return": {
                            "required": false,
                            "default": "numeric"
                        }
                    }
                }
            ],
            "_links": {
                "self": [
                    {
                        "href": "https://example.com/wp-json/cocart/v1/count-items"
                    }
                ]
            }
        },
        "/cocart/v1/item": {
            "namespace": "cocart/v1",
            "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/v1/item"
                    }
                ]
            }
        },
        "/cocart/v1/logout": {
            "namespace": "cocart/v1",
            "methods": [
                "POST"
            ],
            "endpoints": [
                {
                    "methods": [
                        "POST"
                    ],
                    "args": []
                }
            ],
            "_links": {
                "self": [
                    {
                        "href": "https://example.com/wp-json/cocart/v1/logout"
                    }
                ]
            }
        },
        "/cocart/v1/totals": {
            "namespace": "cocart/v1",
            "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/v1/totals"
                    }
                ]
            }
        }
    },
    "_links": {
        "up": [
            {
                "href": "https://example.com/wp-json/"
            }
        ]
    }
}

F.A.Q.

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.

When viewing the cart you will find the key.

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

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 are cart items merged?

If you mean between two or more customers. This is most likely because you tested the API with one of the tools available and did not reset before testing as another customer.

For example, you started customer "A" as a guest adding an item to the cart. You then added another item while authenticating (logging in) as customer "B" without clearing the session cookie.

When you do this, WooCommerce thinks you are still the same customer so it merges the cart items together for customer "B" while customer "A" is removed from session as it is no longer a guest customer.

Is it possible to use the admin key/secret to 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.

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

CoCart can be authenticated by various methods with the WordPress REST API. First being via the REST API Keys in WooCommerce. Though this method is designed for the backend with their 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.

It is also possible to authenticate using any of the following WP REST API authentication methods:

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.

If you have tested other authentication plugins or methods, please let me know via the feedback page so that I can add it to the list.

Thank you. 😄

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.

Steps to follow

  1. Download and Install Basic Auth plugin

Adding an item to the cart as a customer.

curl -X POST https://example.com/wp-json/cocart/v1/add-item \
  -u username:password \
  -H "Content-Type: application/json" \
  -d '{
    "product_id": "32",
    "quantity": 1
  }'
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/add-item",
  "headers": {
      "Authorization": "Basic " + btoa('username:password'),
  },
  "method": "POST",
  "data": {
    "product_id" : "32",
    "quantity" : 1
  },
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
<?php
$curl = curl_init();

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

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

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v1/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( [
    'product_id' => "32",
    'quantity' => 1
  ] ),
  'timeout' => 30
);

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

JSON response example

{
  "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.
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/add-item",
  "headers": {
      "Authorization": "Bearer " + token,
  },
  "method": "POST",
  "data": {
    "product_id" : 32,
    "quantity" : 1
  },
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
<?php
$curl = curl_init();

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

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

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v1/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;

Cart Key

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.

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 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 any of the CoCart API to load this cart when required using the cart_key parameter.

Cart Key in Cart Response

It's also possible to return the cart key when you get the cart. Simply download and activate the Get Cart Enhanced add-on plugin and the cart key is returned along with other enhancements in the response.

Cookie

GitHub Mark Logo Edit on GitHub

CoCart only creates and uses 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 if they are not logged in. The cookie is read on the server and returns the cart stored in the cookie.

The cookie stores 4 key values.

If the framework your using is not able to read the cookie, 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 cookie value yourself and explode it by || and get the first key value. Once you have that value you can use it to set the cart_key parameter on all API requests. This will use the Set Cart ID 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.

Get Cart

GitHub Mark Logo Edit on GitHub

The cart API is powerful and allows you to view the cart in session, add new items, update the quantity of an item and delete individual items from the cart.

Using the individual endpoints and their properties, you can control what you need and what is returned when the request is finished.

Get Cart Contents

This API returns the contents of the cart for a guest customer or logged in registered customer.

Properties

Property Type Description
cart_key string Unique identifier for the cart. ? optional
thumb bool Set as true to return the product thumbnail for each item.

HTTP request

GET
/wp-json/cocart/v1/get-cart
curl -X GET https://example.com/wp-json/cocart/v1/get-cart \
  -H "Content-Type: application/json"
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/get-cart",
  "method": "GET"
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v1/get-cart",
  CURLOPT_CUSTOMREQUEST => "GET",
  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
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v1/get-cart' );
$body = wp_remote_retrieve_body( $response );

JSON response example

{
  "19ca14e7ea6328a42e0eb13d585e4c22":{
    "key":"19ca14e7ea6328a42e0eb13d585e4c22",
    "product_id":36,
    "variation_id":0,
    "variation":[],
    "quantity":1,
    "data_hash":"b5c1d5ca8bae6d4896cf1807cdf763f0",
    "line_tax_data": {
      "subtotal": {
        "12": 8.4
      },
      "total": {
        "12": 8.4
      }
    },
    "line_subtotal":18,
    "line_subtotal_tax":8.4,
    "line_total":14.4,
    "line_tax":8.4,
    "data":{},
    "product_name":"Vneck Tshirt",
    "product_title":"Vneck Tshirt",
    "product_price": "£18"
  }
}

Here is what to do to include the product thumbnail.

curl -X GET https://example.com/wp-json/cocart/v1/get-cart \
  -H "Content-Type: application/json" \
  -d '{
    "thumb": true
  }'
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/get-cart",
  "method": "GET",
  "data": {
    "thumb" : true
  }
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
<?php
$curl = curl_init();

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

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v1/get-cart",
  CURLOPT_CUSTOMREQUEST => "GET",
  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( [
    'thumb' => true
  ] )
);

$response = wp_remote_get( 'https://example.com/wp-json/cocart/v1/get-cart', $args );
$body = wp_remote_retrieve_body( $response );

JSON response example

{
  "19ca14e7ea6328a42e0eb13d585e4c22":{
    "key":"19ca14e7ea6328a42e0eb13d585e4c22",
    "product_id":36,
    "variation_id":0,
    "variation":[],
    "quantity":1,
    "data_hash":"b5c1d5ca8bae6d4896cf1807cdf763f0",
    "line_tax_data": {
      "subtotal": {
        "12": 8.4
      },
      "total": {
        "12": 8.4
      }
    },
    "line_subtotal":18,
    "line_subtotal_tax":8.4,
    "line_total":14.4,
    "line_tax":8.4,
    "data":{},
    "product_name":"Vneck Tshirt",
    "product_title":"Vneck Tshirt",
    "product_price": "£18",
    "product_image":"https://example.com/wp-content/uploads/2019/06/vneck-tee.jpg"
  }
}

Cart for Guest Customers

Supported since v2.1

For guest customers there are two methods available for developers to use. The first method uses a cookie and handles everything for you. The second method allows you to set the cart key yourself.

Once a new customer has added the first item, a cookie is generated that stores the cart key and cart expiration. This cookie is used in order to load the cart again for that individual customer. No parameters are required to pass as it is all done in the background.

Cart Key Method

This method allows you to set the cart key yourself via the cart_key parameter which must be passed with each API request made. This sets the ID in session allowing to create/fetch the cart before changes are made.

Example of getting the cart for a guest customer.

curl -X GET https://example.com/wp-json/cocart/v1/get-cart \
  -H "Content-Type: application/json" \
  -d '{
    "cart_key": "9e18904482b4faf8762361836a83b93d"
  }'
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/get-cart",
  "method": "GET",
  "data": {
    "cart_key": "9e18904482b4faf8762361836a83b93d"
  }
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
<?php
$curl = curl_init();

$args = array(
  'cart_key': '9e18904482b4faf8762361836a83b93d'
);

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v1/get-cart",
  CURLOPT_CUSTOMREQUEST => "GET",
  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( [
    'cart_key': '9e18904482b4faf8762361836a83b93d'
  ] )
);

$response = wp_remote_get( 'https://example.com/wp-json/cocart/v1/get-cart', $args );
$body = wp_remote_retrieve_body( $response );

JSON response is the same as the example above.

Retrieve a Cart in Session

This API allows you to retrieve a cart stored in the database that is in session.

HTTP request

GET
/wp-json/cocart/v1/get-cart/9e18904482b4faf8762361836a83b93d
curl -X GET https://example.com/wp-json/cocart/v1/get-cart/9e18904482b4faf8762361836a83b93d \
  -H "Content-Type: application/json" \
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/get-cart/9e18904482b4faf8762361836a83b93d",
  "method": "GET"
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v1/get-cart/9e18904482b4faf8762361836a83b93d",
  CURLOPT_CUSTOMREQUEST => "GET",
  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
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v1/get-cart/9e18904482b4faf8762361836a83b93d' );
$body = wp_remote_retrieve_body( $response );

JSON response example

{
  "19ca14e7ea6328a42e0eb13d585e4c22":{
    "key":"19ca14e7ea6328a42e0eb13d585e4c22",
    "product_id":36,
    "variation_id":0,
    "variation":[],
    "quantity":1,
    "data_hash":"b5c1d5ca8bae6d4896cf1807cdf763f0",
    "line_tax_data": {
      "subtotal": {
        "12": 8.4
      },
      "total": {
        "12": 8.4
      }
    },
    "line_subtotal":18,
    "line_subtotal_tax":8.4,
    "line_total":14.4,
    "line_tax":8.4,
    "data":{},
    "product_name":"Vneck Tshirt",
    "product_title":"Vneck Tshirt",
    "product_price": "£18"
  }
}

Clear Cart

GitHub Mark Logo Edit on GitHub

This API helps you clear the contents of the cart.

Properties

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

HTTP request

POST
/wp-json/cocart/v1/clear
curl -X POST https://example.com/wp-json/cocart/v1/clear \
  -H "Content-Type: application/json"
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/clear",
  "method": "POST"
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v1/clear",
  CURLOPT_CUSTOMREQUEST => "POST",
  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
$response = wp_remote_post( 'https://example.com/wp-json/cocart/v1/clear' );
$body = wp_remote_retrieve_body( $response );

JSON response example

"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 to the cart. You can also request to return the whole cart once item is added to reduce API requests and use the Get Cart Content properties.

Properties

Property Type Description
cart_key string Unique identifier for the cart. ? optional
product_id string The product ID is required in order to add a product to the cart. A SKU ID can also be used here instead. mandatory
quantity float Set the quantity of the product you want to add to the cart. Default is 1
variation_id integer Used to set the variation of the product being added to the cart. optional
variation object Attribute values. required, for variable products only
cart_item_data object Used to apply extra cart item data we want to pass with the item. optional
return_cart bool Set as true to return the cart once item added. optional

HTTP request

POST
/wp-json/cocart/v1/add-item

Add Item to Cart

Example of adding a product via product ID to the cart.

curl -X POST https://example.com/wp-json/cocart/v1/add-item \
  -H "Content-Type: application/json" \
  -d '{
    "product_id": "32",
    "quantity": 1
  }'
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/add-item",
  "method": "POST",
  "data": {
    "product_id" : "32",
    "quantity" : 1
  }
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
<?php
$curl = curl_init();

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

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v1/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( [
    'product_id' => "32",
    'quantity' => 1
  ] ),
  'timeout' => 30
);

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

Example of adding a product via SKU ID to the cart.

curl -X POST https://example.com/wp-json/cocart/v1/add-item \
  -H "Content-Type: application/json" \
  -d '{
    "product_id": "Red Hoodie",
    "quantity": 1
  }'
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/add-item",
  "method": "POST",
  "data": {
    "product_id" : "Red Hoodie",
    "quantity" : 1
  }
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
<?php
$curl = curl_init();

$args = array(
  'product_id' => "Red Hoodie",
  'quantity' => 1
);

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v1/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( [
    'product_id' => "Red Hoodie",
    'quantity' => 1
  ] ),
  'timeout' => 30
);

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

JSON response example

{
  "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":{}
  }
}

Add Variation Item

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

While the variation_id is important, it is not required to be know as the API will look it up for you based on the attributes passed. Without the attributes of the variation, there is no way to identify the variation added.

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 attribute_. A global attribute extends the prefix 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/v1/add-item \
  -H "Content-Type: application/json" \
  -d '{
    "product_id": "1723",
    "quantity": 1,
    "variation_id": 1820,
    "variation": {
      "attribute_colours": "Red",
      "attribute_pa_size": "2x-large"
    }
  }'
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/add-item",
  "method": "POST",
  "data": {
    "product_id": "1722",
    "quantity": 1,
    "variation_id": 1820,
    "variation": {
      "attribute_colours": "Red",
      "attribute_pa_size": "2x-large"
    }
  }
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
<?php
$curl = curl_init();

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

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v1/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( [
    'product_id' => '1722',
    'quantity' => 1
    'variation_id' => 1820,
    'variation' => {
      'attribute_colours': 'Red',
      'attribute_pa_size': '2x-large'
    }
  ] ),
  'timeout' => 30
);

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

JSON response example

{
    "key": "2c698d686c6cd8872e825fd9b05bd322",
    "product_id": 1722,
    "variation_id": 1820,
    "variation": {
        "attribute_colours": "Red",
        "attribute_pa_size": "2x-large"
    },
    "quantity": 1,
    "data": {},
    "data_hash": "89f41c195ac99955ca64fafcc1225796",
    "line_tax_data": {
        "subtotal": [],
        "total": []
    },
    "line_subtotal": 12,
    "line_subtotal_tax": 0,
    "line_total": 12,
    "line_tax": 0,
    "product_name": "T-shirt - Red",
    "product_title": "T-shirt",
    "product_price": "£12.00"
}

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/v1/add-item \
  -H "Content-Type: application/json" \
  -d '{
    "product_id": "3008",
    "quantity": 1,
    "cart_item_data": {
      "engraved_name": "Sébastien Dumont",
      "engraved_size": "Medium"
    }
  }'
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/add-item",
  "method": "POST",
  "data": {
    "product_id" : "3008",
    "quantity" : 1,
    "cart_item_data" : {
      "engraved_name" : "Sébastien Dumont",
      "engraved_size" : "Medium"
    }
  }
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
<?php
$curl = curl_init();

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

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v1/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( [
    'product_id' => '3008',
    'quantity' => 1
    'cart_item_data' => array(
      'engraved_name' => 'Sébastien Dumont',
      'engraved_size' => 'Medium'
    )
  ] ),
  'timeout' => 30
);
$response = wp_remote_post( 'https://example.com/wp-json/cocart/v1/add-item', $args );
$body = wp_remote_retrieve_body( $response );

JSON response example

{
    "engraved_name": "Sébastien Dumont",
    "engraved_size": "Medium",
    "key": "b440b5368da5b3e3a6eb1f40fa666279",
    "product_id": 3008,
    "variation_id": 0,
    "variation": [],
    "quantity": 1,
    "data": {},
    "data_hash": "b5c1d5ca8bae6d4896cf1807cdf763f0",
    "line_tax_data": {
        "subtotal": {
            "13": 8.4
        },
        "total": {
            "13": 8.4
        }
    },
    "line_subtotal": 42,
    "line_subtotal_tax": 8.4,
    "line_total": 42,
    "line_tax": 8.4,
    "product_name": "Silver Ring",
    "product_title": "Silver Ring",
    "product_price": "£80.00"
}

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.

Count Items

GitHub Mark Logo Edit on GitHub

This API helps you count the items in the cart.

Properties

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

HTTP request

GET
/wp-json/cocart/v1/count-items
curl -X GET https://example.com/wp-json/cocart/v1/count-items \
 -H "Content-Type: application/json"
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/count-items",
  "method": "GET"
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v1/count-items",
  CURLOPT_CUSTOMREQUEST => "GET",
  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
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v1/count-items' );
$body = wp_remote_retrieve_body( $response );

JSON response example

1

Remove Item from Cart

GitHub Mark Logo Edit on GitHub

This API helps you to remove an item from the cart. You can also request to return the whole cart once item is removed to reduce API requests and use the Get Cart Contents properties.

Properties

Property Type Description
cart_key string Unique identifier for the cart. ? optional
cart_item_key string The cart item key of the product in the cart. mandatory
return_cart bool Set as true to return the whole cart once item is removed. optional

HTTP request

DELETE
/wp-json/cocart/v1/item
curl -X DELETE https://example.com/wp-json/cocart/v1/item \
  -H "Content-Type: application/json" \
  -d '{
    "cart_item_key": 404dcc91b2aeaa7caa47487d1483e48a
  }'
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/item",
  "method": "DELETE",
  "data": {
    "cart_item_key" : "404dcc91b2aeaa7caa47487d1483e48a"
  }
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
<?php
$curl = curl_init();

$args = array(
  'cart_item_key' => '404dcc91b2aeaa7caa47487d1483e48a'
);

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v1/item",
  CURLOPT_CUSTOMREQUEST => "DELETE",
  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( [
    'cart_item_key' => '404dcc91b2aeaa7caa47487d1483e48a'
  ] ),
  'method' => 'DELETE',
  'timeout' => 30
);

$response = wp_remote_request( 'https://example.com/wp-json/cocart/v1/item', $args );
$body = wp_remote_retrieve_body( $response );

JSON response example

"Item 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. You can also request to return the whole cart once item is restored to reduce API requests and use the Get Cart Contents properties.

Properties

Property Type Description
cart_key string Unique identifier for the cart. ? optional
cart_item_key string The cart item key of the product that was in the cart recently. mandatory
return_cart bool Set as true to return the whole cart once item is restored. optional

HTTP request

GET
/wp-json/cocart/v1/item
curl -X GET https://example.com/wp-json/cocart/v1/item \
  -H "Content-Type: application/json" \
  -d '{
    "cart_item_key": 404dcc91b2aeaa7caa47487d1483e48a
  }'
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/item",
  "method": "GET",
  "data": {
    "cart_item_key" : "404dcc91b2aeaa7caa47487d1483e48a"
  }
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
<?php
$curl = curl_init();

$args = array(
  'cart_item_key' => '404dcc91b2aeaa7caa47487d1483e48a'
);

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v1/item",
  CURLOPT_CUSTOMREQUEST => "GET",
  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
  'headers' => array(
    'Content-Type' => 'application/json; charset=utf-8',
  ),
  'body' => wp_json_encode( [
    'cart_item_key' => '404dcc91b2aeaa7caa47487d1483e48a'
  ] )
);

$response = wp_remote_get( 'https://example.com/wp-json/cocart/v1/item', $args );
$body = wp_remote_retrieve_body( $response );

JSON response example

"Item has been restored to the cart.""

Update Item in Cart

GitHub Mark Logo Edit on GitHub

This API helps you to update an item in the cart. You can also request to return the whole cart once item is updated to reduce API requests and use the Get Cart Contents properties.

Properties

Property Type Description
cart_key string Unique identifier for the cart. ? optional
cart_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/v1/item
curl -X POST https://example.com/wp-json/cocart/v1/item \
  -H "Content-Type: application/json" \
  -d '{
    "cart_item_key": "404dcc91b2aeaa7caa47487d1483e48a",
    "quantity": 2
  }'
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/item",
  "method": "POST",
  "data": {
    "cart_item_key" : "404dcc91b2aeaa7caa47487d1483e48a",
    "quantity" : 2
  }
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
<?php
$curl = curl_init();

$args = array(
  'cart_item_key' => '404dcc91b2aeaa7caa47487d1483e48a',
  'quantity' => 2
);

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v1/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( [
    'cart_item_key' => '404dcc91b2aeaa7caa47487d1483e48a',
    'quantity' => 2
  ] ),
  'timeout' => 30
);

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

JSON response example

{
  "message":"The quantity for 'Woo T-Shirt' has increased to '2'.",
  "quantity":2
}

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.

Properties

Property Type Description
cart_key string Unique identifier for the cart. ? optional
html bool Set as true to return the totals as strings with currency symbol. optional

HTTP request

GET
/wp-json/cocart/v1/totals
curl -X GET https://example.com/wp-json/cocart/v1/totals \
 -H "Content-Type: application/json"
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/totals",
  "method": "GET"
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v1/totals",
  CURLOPT_CUSTOMREQUEST => "GET",
  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
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v1/totals' );
$body = wp_remote_retrieve_body( $response );

JSON response example

{
  "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/v1/totals \
  -H "Content-Type: application/json" \
  -d '{
    "html": true
  }'
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/totals",
  "method": "GET",
  "data": {
    "html" : true
  }
};

$.ajax(settings).done(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/v1/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/v1/totals', $args );
$body = wp_remote_retrieve_body( $response );

JSON response example

{
  "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.

Properties

Property Type Description
cart_key string Unique identifier for the cart. ? optional
return bool Set as true to return the totals once calculated. optional

HTTP request

POST
/wp-json/cocart/v1/calculate
curl -X POST https://example.com/wp-json/cocart/v1/calculate \
    -H "Content-Type: application/json"
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/calculate",
  "method": "POST"
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v1/calculate",
  CURLOPT_CUSTOMREQUEST => "POST",
  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
$response = wp_remote_post( 'https://example.com/wp-json/cocart/v1/calculate' );
$body = wp_remote_retrieve_body( $response );

JSON response example

"Cart totals have been calculated."

Logout

New API since v2.1

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/v1/logout
curl -X POST https://example.com/wp-json/cocart/v1/logout \
  -H "Content-Type: application/json" \
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/logout",
  "method": "POST"
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
<?php
$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v1/logout",
  CURLOPT_CUSTOMREQUEST => "POST",
  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
$response = wp_remote_post( 'https://example.com/wp-json/cocart/v1/logout' );
$body = wp_remote_retrieve_body( $response );

JSON response example

true

Load Cart from Session

New Feature since v2.1

GitHub Mark Logo Edit on GitHub

Load cart from session allows the cart of your choosing to be set before anything WooCommerce handles.

For example if you have a returning customer that started as a guest and then logs in to their account. WooCommerce will then merge the carts together should the customer already have a saved cart.

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) via the web or merge the cart items together.

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
redirect bool Set as true to redirect to cart page. Default is false. Web Only!

Load for the Web

To load the cart from session for the web, you must use the properties above to query your website.

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

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.

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

New 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

New 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?

New 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;
});

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

New 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(){});

Hooks

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.

CoCart Add-ons

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

Get Cart Enhanced

This free add-on for CoCart enhances the data returned for the cart and the items added to it.

You can download it from WordPress.org

Example of an empty cart with the add-on enabled.

{
  "currency": "GBP",
  "cart_key": "0", // Zero means no cart created yet.
  "cart_hash": "",
  "items": [],
  "item_count": 0,
  "needs_shipping": false,
  "needs_payment": false,
  "coupons": [],
  "totals": {
    "subtotal": "£0.00",
    "subtotal_tax": "£0.00",
    "shipping_total": "£0.00",
    "shipping_tax": "£0.00",
    "shipping_taxes": [],
    "discount_total": "£0.00",
    "discount_tax": "£0.00",
    "cart_contents_total": "£0.00",
    "cart_contents_tax": "£0.00",
    "cart_contents_taxes": [],
    "fee_total": "£0.00",
    "fee_tax": "£0.00",
    "fee_taxes": [],
    "total": "£0.00",
    "total_tax": "£0.00"
  },
  "total_weight": {
    "total": 0,
    "weight_unit": "kg"
  },
  "extras": {
    "removed_items": [],
    "cross_sells": []
  }
}

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

curl -X POST https://example.com/wp-json/cocart/v1/add-item \
  -H "Content-Type: application/json" \
  -d '{
    "product_id": "1102",
    "quantity": 2,
    "cart_item_data": {
        "mnm_config": [
            {
                "product_id": 987,
                "quantity": 1
            },
            {
                "product_id": 1001,
                "quantity": 2
            },
            {
                "product_id": 1003,
                "quantity": 3
            }
        ]
    }
}'
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/add-item",
  "method": "POST",
  "data": {
    "product_id": "1102",
    "quantity": 5,
    "cart_item_data": {
        "mnm_config": [
            {
                "product_id": 987,
                "quantity": 1
            },
            {
                "product_id": 1001,
                "quantity": 2
            },
            {
                "product_id": 1003,
                "quantity": 3
            }
        ]
    }
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
<?php
$curl = curl_init();

$args = array(
  'product_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/v1/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( [
    'product_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/v1/add-item', $args );
$body = wp_remote_retrieve_body( $response );

JSON response example

{
    "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.

curl -X POST https://example.com/wp-json/cocart/v1/add-item \
  -H "Content-Type: application/json" \
  -d '{
    "product_id": "129",
    "quantity": 1,
    "cart_item_data": {
      "nyp": 24
    }
  }'
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/add-item",
  "method": "POST",
  "data": {
    "product_id": "129",
    "quantity": 1,
    "cart_item_data": {
      "nyp": 24
    }
  }
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
<?php
$curl = curl_init();

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

curl_setopt_array( $curl, array(
  CURLOPT_URL => "https://example.com/wp-json/cocart/v1/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( [
    'product_id' => '129',
    'quantity' => 1,
    'cart_item_data' => array(
      'nyp' => 24
    )
  ] ),
  'timeout' => 30
);
$response = wp_remote_post( 'https://example.com/wp-json/cocart/v1/add-item', $args );
$body = wp_remote_retrieve_body( $response );

JSON response example

{
    "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.

/**
 * 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 your 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.

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

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/v1/add-item

View more on add to cart

curl -X POST https://wp-demo.cocart.xyz/wp-json/cocart/v1/add-item \
  -H "Content-Type: application/json" \
  -d '{
    "product_id": "183",
    "quantity": 1
  }'
var settings = {
  "url": "https://wp-demo.cocart.xyz/wp-json/cocart/v1/add-item",
  "method": "POST",
  "data": {
    "product_id" : "183",
    "quantity" : 1
  }
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
<?php
$curl = curl_init();

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

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

$response = curl_exec($curl);

curl_close($curl);

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

Authenticate Customer

Currently on the demo, you can test authentication as a customer via the basic method.

Username Password
demo &nm5y7^sf&hm1D5MwKLgrQeC

More authentication methods to test with on the demo will come in the future.

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
185 - WordPress Pennant External £11.05 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.

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.

Changelog

Below is the changelog for "CoCart Lite" documentation that matches with the version of the plugin release.

Doc Version v2.8.2

Doc Version v2.8 - Plugin Release v2.6 to v2.7

Doc Version v2.7 - Plugin Release v2.5.1

Doc Version v2.6 - Plugin Release v2.5

Doc Version v2.5

Doc Version v2.4

Doc Version v2.3

Doc Version v2.2 - Plugin Release v2.2

Doc Version v2.1 - Plugin Release v2.1.3

Doc Version v2.0 - Plugin Release v2.1.2

Doc Version v1.9

Doc Version v1.8 - Plugin Release v2.1

Doc Version v1.7

Doc Version v1.6 - Plugin Release v2.0.13

Doc Version v1.5 - Plugin Release v2.0.7

Doc Version v1.4

Doc Version v1.3

Doc Version v1.2

Doc Version v1.1

Doc Version v1 - Plugin Release v2

Doc Version v0.5

Doc Version v0.4 - Plugin Release v1.0.5

Doc Version v0.3 - Plugin Release v1.0.4

Doc Version v0.2 - Plugin Release v1.0.1

Doc Version v0.1 - Plugin Release v1.0.0

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! 🙌