Introduction
Welcome to the documentation site for CoCart, an open-source WordPress plugin that brings the power of WooCommerce's shopping cart via the REST API. If you haven't already, checkout the features CoCart support.
CoCart helps you manage shopping carts in any modern framework of your choosing. No local storing required. A powerful RESTful API that offers an integration to build your headless store with ease.
What is a REST API?
REST is an acronym for Representational State Transfer — an almost meaningless description of the most-used web service technology! REST is a way for two computer systems to communicate over HTTP in a similar way to web browsers and servers.
CoCart is a REST API designed in mind for those who want to create a headless e-commerce site powered by WooCommerce. Read what does headless mean?
CoCart allows developers to provide a shopping cart in their app that stores the customers items, coupons applied, shipping methods available and much more. Carts can be created, read, updated, and deleted using the requests available that return a response in JSON format and standard HTTP verbs which are understood by most HTTP clients.
API Versions
The current WordPress REST API integration for CoCart is version 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:
- WordPress 5.2 or later.
- WooCommerce 4.0 or later.
- PHP 7.0 or later.
- Pretty permalinks in
Settings > Permalinks
so that the custom endpoints are supported. Default permalinks will not work. - You may make requests over either HTTP or HTTPS, but HTTPS is recommended where possible.
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:
- Resource IDs are returned as integers.
- Other amounts, such as item counts, are returned as integers.
- Blank fields are generally included as
null
instead of being returned as blank strings or omitted.
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
This section is intended to help you get started with WordPress, WooCommerce and CoCart.
Setting up WordPress
One of the first things you might want to do is to set up a WordPress site on your personal computer.
I hands-down recommend using a tool called LocalWP. It’s a desktop application that allows you to create new WordPress sites on your computer with the click of a few buttons. It takes care of configuring PHP, MySQL and basic configuration of WordPress to connect to the database. It provides one-click support for enabling XDebug, allows access to your WordPress site using WP-CLI, and more. And, it’s free.
There are some alternatives for quickly spinning up a local environment:
When setting up your WordPress environment, please check that you have the server requirements for CoCart.
Setting up WooCommerce
Once you have your WordPress environment setup. The next step is to install WooCommerce and setup your store. Add products, configure shipping, taxes payment gateway etc.
A more detailed guide for setting up WooCommerce can be found at WooCommerce.com documentation.
Automatic installation
Automatic installation is the easiest option as WordPress handles the file transfers itself and you don’t need to leave your web browser. To do an automatic install of WooCommerce, log in to your WordPress dashboard, navigate to the Plugins menu and click Add New.
In the search field type “WooCommerce” and click Search Plugins. Once you’ve found the plugin you can view details about it such as the point release, rating and description. Most importantly of course, you can install it by simply clicking “Install Now”.
Setting up CoCart
Once you have your WooCommerce store setup. The next step is to install CoCart. Once installed you can the use the API.
Automatic installation
Automatic installation is the easiest option as WordPress handles the file transfers itself and you don’t need to leave your web browser. To do an automatic install of CoCart, log in to your WordPress dashboard, navigate to the Plugins menu and click Add New.
In the search field type “CoCart” and click Search Plugins. Once you’ve found the plugin you can view details about it such as the point release, rating and description. Most importantly of course, you can install it by simply clicking “Install Now”.
Recommended Version
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
.
Recommended Plugins
This section will list recommended plugins that will help with your development in creating a headless store.
Error Responses
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 |
Knowledge Base
Cart returns empty after adding items. Why?
As a guest customer, this is normally because the framework your using does not support cookies so it is unable to read the required cookie to load the cart on the next API request.
Read this guide on how to create a cart and keep using the same one.
If the cart returns empty while your authenticated then contact me so that I may be able to help.
I added several products but only 1 item returns in cart. Why?
As a guest customer, this is possibly because you did not store the cart key after the first item was added and set it on future API requests. So all your seeing is the last item added to the cart.
Read this guide on how to create a cart and keep using the same one.
Can I create and update a cart without cookies?
Yes you can. See cart key section for more details.
Where can I find the cart key?
The cart key (if not manually set), can be found via a few methods. See cart key section for more details.
Why am I not seeing the X-COCART-API header returning?
If this header is not returning then you need to enable CORS so that the header is exposed. Either enable CORS support via the filter or simply install CoCart CORS plugin for quick activation.
Where can I find a cart item key?
Each item added to the cart has it's on cart item key and you will find it under the property labelled "key". Use it to update, remove or restore an item in/from the cart.
{
"19ca14e7ea6328a42e0eb13d585e4c22":{
"key":"19ca14e7ea6328a42e0eb13d585e4c22", // This is the item key.
"product_id":36,
"variation_id":0,
...
}
As admininstator can I create and update a customers cart?
Unfortunately, no. This is because when you authenticate as the admin, you are logged in not the customer. Even if you specified the customers user ID as the cart key. It will not take affect.
How can I view debug logs recorded ?
If you have WP_DEBUG set to true
in your wp-config.php file then you should be able to view all the logs recorded by CoCart under WooCommerce -> System Status -> Logs in your WordPress dashboard.
URL Example: https://example.com/wp-admin/admin.php?page=wc-status&tab=logs
You can also change how the logs are presented.
How can I use CoCart on a multi-site network?
Using CoCart on any site on the network is just the same as you would on a single site. The only difference is the domain/sub-domain of the site.
Does CoCart work with the Dokan plugin?
Yes. The only feature you wont be able to use are coupons. This is because Dokan disables the use of coupons. All other features are compatible.
Authentication
The WordPress REST API incorporates a method called nonces to deal with CSRF issues. This ensures that all activities on the website remain segregated. This is because the WordPress REST API just like the WooCommerce REST API is designed for the back-end.
CoCart however, is designed for the front-end so for any CoCart requests made, the cookie authentication is disabled allowing the ability to authenticate in any code language without fault.
REST API authentication methods:
- Basic Authentication (Recommended with SSL Only!)
- JWT Authentication for WP REST API (Not Recommended according to feedback)
- WooCommerce API Keys (Best for Administrators Only!)
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
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
}'
// import CoCartAPI from "@cocart/cocart-rest-api"; // Supports ESM
const CoCartAPI = require("@cocart/cocart-rest-api").default;
const CoCart = new CoCartAPI({
url: "https://example.com",
consumerKey: 'sebtest123',
consumerSecret: 'happycoding24'
});
var data = {
"product_id": "32",
"quantity": 1
};
CoCart.post("add-item", data)
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
$.ajax({
url: "https://example.com/wp-json/cocart/v1/add-item",
headers: {
"Authorization": "Basic " + btoa('username:password'),
},
method: "POST",
data: JSON.stringify({
"product_id" : "32",
"quantity" : 1
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (response) {
console.log(response);
}
});
<?php
$curl = curl_init();
$args = json_encode( array(
'product_id' => "32",
'quantity' => 1
) );
$headers = array(
'Accept: 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 );
{
"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
- Download and Install JWT Authentication plugin from WordPress.org.
- Configure the Secret Key.
- Get your token.
$.ajax({
url: "https://example.com/wp-json/cocart/v1/add-item",
headers: {
"Authorization": "Bearer " + token,
},
method: "POST",
data: JSON.stringify({
"product_id" : 32,
"quantity" : 1
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (response) {
console.log(response);
}
});
<?php
$curl = curl_init();
$args = json_encode( array(
'product_id' => 32,
'quantity' => 1
) );
$headers = array(
'Accept: 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;
<?php
$args = array(
'headers' => array(
'Authorization' => 'Bearer ' . $token,
'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 );
WooCommerce API Keys
Though this method is designed for the backend with WooCommerce REST API, with some custom coding you can make it work for the frontend with CoCart. Checkout my guide on how to authenticate with WooCommerce.
Cart Key
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 cart key is normally stored in a cookie and is used to load the cart in session if the cart still exists.
For registered customers, the cart key is the user ID/customer ID and starts from a single digit and up.
For guest customers, the cart key is randomly generated of 42 characters. This is the database limit.
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 item is added to the cart.
Look for X-CoCart-API
and you will see the value of the cart key returned. You can then use this to set all future CoCart API requests to load this cart when required using the global cart_key
parameter.
Read this guide on how to create a cart and keep using the same one.
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
CoCart only creates and uses only one cookie per session/customer/device. The cookie name starts with wp_cocart_session_
followed by the WordPress COOKIEHASH. The cookie name can be changed using this filter.
If left enabled, this cookie will be used to identity the customers cart. The cookie is read on the server and returns the cart stored in the cookie.
The cookie stores 4 key values.
- Cart Key/Customer ID
- Cart expiring timestamp.
- Cart expiration timestamp.
- Cookie hash.
How the CoCart cookie is created
Once a customer has added the first item to the cart, a cookie is generated that stores the cart key (a.k.a the customers ID) and cart expiration.
This cookie is used in order to load the cart again in session for that individual customer. No parameters are required to pass as it is all done in the background.
This is the default behaviour for WooCommerce on the frontend and works fine in any framework that supports the use of creating and reading cookies.
What to do if I cant use Cookies?
If the framework your using is not able to read cookies, then there are a few things you can do.
- Look for a cookie support add-on for your framework. React for example has one called react-cookies.
- Read the cart key value in the returned header response
X-CoCart-API
. Once you have that value you can use it to set thecart_key
parameter on all API requests. This will use the Cart Key method.
Set-Cookie-headers
The cookie for CoCart and therefore the cart key is supplied through response headers, so called Set-Cookie-headers.
Cookies received via Set-Cookie-headers is stored in the browser for the domain upon which holds the API, meaning you can encounter problems reading the cookie values from your frontend.
If using a package like axios, make sure to supply the correct config parameters that enables cookies in requests to the server. As an example, axios has a config parameter called withAuthorization
. With the flag set to true, cookies previous set will be sent in the request.
P.S. Our official JS library already has this setup for you.
Can I change the SameSite Attribute?
If you need to change the SameSite attribute a filter is available that was introduced in v2.9.1
If you want to know more about SameSite attribute. Checkout this article.
Index
By default, the API provides information about all available endpoints on the site. Authentication is not required to access the API index.
HTTP request
/wp-json/cocart/v1
curl -X GET https://example.com/wp-json/cocart/v1 \
-H "Content-Type: application/json"
CoCart.get("")
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
$.ajax({
url: "https://example.com/wp-json/cocart/v1",
method: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (response) {
console.log(response);
}
});
<?php
$curl = curl_init();
curl_setopt_array( $curl, array(
CURLOPT_URL => "https://example.com/wp-json/cocart/v1",
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => array(
'Accept: 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',
),
'timeout' => 30
);
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v1', $args );
$body = wp_remote_retrieve_body( $response );
{
"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/"
}
]
}
}
Products
In order to access your products, you need to have the CoCart Products add-on.
It's a public API that provides access to non-sensitive product information, categories, tags, attributes and even reviews from your store without the need to authenticate.
Supports other products types created by WooCommerce extensions such as Subscriptions and more.
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 |
Get Cart
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.
Parameters
Parameter | Type | Description |
---|---|---|
cart_key |
string | Unique identifier for the cart. ? optional |
Properties
Attribute | Type | Description |
---|---|---|
thumb |
bool | Set as true to return the product thumbnail for each item. |
HTTP request
/wp-json/cocart/v1/get-cart
curl -X GET https://example.com/wp-json/cocart/v1/get-cart \
-H "Content-Type: application/json"
CoCart.get("get-cart")
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
$.ajax({
url: "https://example.com/wp-json/cocart/v1/get-cart",
method: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (response) {
console.log(response);
}
});
<?php
$curl = curl_init();
curl_setopt_array( $curl, array(
CURLOPT_URL => "https://example.com/wp-json/cocart/v1/get-cart",
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => array(
'Accept: 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',
),
'timeout' => 30
);
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v1/get-cart', $args );
$body = wp_remote_retrieve_body( $response );
{
"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
}'
CoCart.get("get-cart", {
thumb: true
})
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
$.ajax({
url: "https://example.com/wp-json/cocart/v1/get-cart",
method: "GET",
data: JSON.stringify({
"thumb" : true
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: 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',
'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
] ),
'timeout' => 30
);
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v1/get-cart', $args );
$body = wp_remote_retrieve_body( $response );
{
"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"
}
}
Get Cart using Cart Key
Supported since v2.1
This method allows you to set the cart key yourself via the cart_key
parameter. This sets the cart key in session allowing to create/fetch the cart before changes are made. See the "Cart Key" section for more information.
Example of getting the cart with cart key.
curl -X GET https://example.com/wp-json/cocart/v1/get-cart?cart_key=9e18904482b4faf8762361836a83b93d \
-H "Content-Type: application/json"
CoCart.get("get-cart?cart_key=9e18904482b4faf8762361836a83b93d")
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
$.ajax({
url: "https://example.com/wp-json/cocart/v1/get-cart?cart_key=9e18904482b4faf8762361836a83b93d",
method: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (response) {
console.log(response);
}
});
<?php
$curl = curl_init();
curl_setopt_array( $curl, array(
CURLOPT_URL => "https://example.com/wp-json/cocart/v1/get-cart?cart_key=9e18904482b4faf8762361836a83b93d",
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => array(
'Accept: 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',
),
'timeout' => 30
);
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v1/get-cart?cart_key=9e18904482b4faf8762361836a83b93d', $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
/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" \
CoCart.get("get-cart/9e18904482b4faf8762361836a83b93d")
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
$.ajax({
url: "https://example.com/wp-json/cocart/v1/get-cart/9e18904482b4faf8762361836a83b93d",
method: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (response) {
console.log(response);
}
});
<?php
$curl = curl_init();
curl_setopt_array( $curl, array(
CURLOPT_URL => "https://example.com/wp-json/cocart/v1/get-cart/9e18904482b4faf8762361836a83b93d",
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => array(
'Accept: 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',
),
'timeout' => 30
);
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v1/get-cart/9e18904482b4faf8762361836a83b93d', $args );
$body = wp_remote_retrieve_body( $response );
{
"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"
}
}
Merge Carts
Wish to merge items from a guest customers cart with a registered customers cart? Then when fetching the cart, you must authenticate as the registered customer and set the guests customers cart key.
Parameters
Parameter | Type | Description |
---|---|---|
cart_key |
string | Unique identifier for the cart. ? optional |
Properties
Attribute | Type | Description |
---|---|---|
thumb |
bool | Set as true to return the product thumbnail for each item. |
HTTP request
/wp-json/cocart/v1/get-cart?cart_key=<cart_key>
curl -X GET https://example.com/wp-json/cocart/v1/get-cart?cart_key=<cart_key> \
-u username:password \
-H "Content-Type: application/json"
// import CoCartAPI from "@cocart/cocart-rest-api"; // Supports ESM
const CoCartAPI = require("@cocart/cocart-rest-api").default;
const CoCart = new CoCartAPI({
url: "https://example.com",
consumerKey: 'sebtest123',
consumerSecret: 'happycoding24'
});
CoCart.get("get-cart?cart_key=<cart_key>")
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
$.ajax({
url: "https://example.com/wp-json/cocart/v1/get-cart?cart_key=<cart_key>",
headers: {
"Authorization": "Basic " + btoa('username:password'),
},
method: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (response) {
console.log(response);
}
});
<?php
$curl = curl_init();
curl_setopt_array( $curl, array(
CURLOPT_URL => "https://example.com/wp-json/cocart/v1/get-cart?cart_key=<cart_key>",
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => array(
'Accept: application/json',
'User-Agent: CoCart API/v1',
'Authorization: Basic ' . base64_encode($username . ':' . $password)
)
) );
$response = curl_exec($curl);
curl_close($curl);
echo $response;
<?php
$args = array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( 'username:password' ),
'Content-Type' => 'application/json; charset=utf-8',
),
'timeout' => 30
);
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v1/get-cart?cart_key=<cart_key>', $args );
$body = wp_remote_retrieve_body( $response );
Clear Cart
This API helps you clear the contents of the cart.
Parameters
Parameter | Type | Description |
---|---|---|
cart_key |
string | Unique identifier for the cart. ? optional |
HTTP request
/wp-json/cocart/v1/clear
curl -X POST https://example.com/wp-json/cocart/v1/clear \
-H "Content-Type: application/json"
CoCart.post("clear")
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
$.ajax({
url: "https://example.com/wp-json/cocart/v1/clear",
method: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (response) {
console.log(response);
}
});
<?php
$curl = curl_init();
curl_setopt_array( $curl, array(
CURLOPT_URL => "https://example.com/wp-json/cocart/v1/clear",
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => array(
'Accept: 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 );
"Cart is cleared."
Add to Cart
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.
Parameters
Parameter | Type | Description |
---|---|---|
cart_key |
string | Unique identifier for the cart. ? optional |
Properties
Attribute | Type | Description |
---|---|---|
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
/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
}'
CoCart.post("add-item", {
product_id: "32",
quantity: 1
})
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
$.ajax({
url: "https://example.com/wp-json/cocart/v1/add-item",
method: "POST",
data: JSON.stringify({
"product_id" : "32",
"quantity" : 1
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: 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',
'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
}'
CoCart.post("add-item", {
product_id: "Red Hoodie",
quantity: 1
})
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
$.ajax({
url: "https://example.com/wp-json/cocart/v1/add-item",
method: "POST",
data: JSON.stringify({
"product_id" : "Red Hoodie",
"quantity" : 1
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: 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',
'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 );
{
"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. A global attribute prefix is like so attribute_pa_
, while a custom attribute just has the prefix attribute_
. Both are followed by the attribute slug. See the examples for comparison.
Example of adding a variation of a product to the cart.
curl -X POST https://example.com/wp-json/cocart/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 data = {
"product_id": "1722",
"quantity": 1,
"variation_id": 1820,
"variation": {
"attribute_colours": "Red",
"attribute_pa_size": "2x-large"
}
};
CoCart.post("add-item", data)
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
$.ajax({
url: "https://example.com/wp-json/cocart/v1/add-item",
method: "POST",
data: JSON.stringify({
"product_id": "1722",
"quantity": 1,
"variation_id": 1820,
"variation": {
"attribute_colours": "Red",
"attribute_pa_size": "2x-large"
}
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (response) {
console.log(response);
}
});
<?php
$curl = curl_init();
$args = array(
'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',
'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 );
{
"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 data = {
"product_id": "3008",
"quantity": 1,
"cart_item_data": {
"engraved_name": "Sébastien Dumont",
"engraved_size": "Medium"
}
};
CoCart.post("add-item", data)
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
$.ajax({
url: "https://example.com/wp-json/cocart/v1/add-item",
method: "POST",
data: JSON.stringify({
"product_id" : "3008",
"quantity" : 1,
"cart_item_data" : {
"engraved_name" : "Sébastien Dumont",
"engraved_size" : "Medium"
}
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (response) {
console.log(response);
}
});
<?php
$curl = curl_init();
$args = array(
'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',
'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 );
{
"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
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
This API helps you count the items in the cart.
Parameters
Parameter | Type | Description |
---|---|---|
cart_key |
string | Unique identifier for the cart. ? optional |
HTTP request
/wp-json/cocart/v1/count-items
curl -X GET https://example.com/wp-json/cocart/v1/count-items \
-H "Content-Type: application/json"
CoCart.get("count-items")
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
$.ajax({
url: "https://example.com/wp-json/cocart/v1/count-items",
method: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (response) {
console.log(response);
}
});
<?php
$curl = curl_init();
curl_setopt_array( $curl, array(
CURLOPT_URL => "https://example.com/wp-json/cocart/v1/count-items",
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => array(
'Accept: 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',
),
'timeout' => 30
);
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v1/count-items', $args );
$body = wp_remote_retrieve_body( $response );
1
Remove Item from Cart
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.
Parameters
Parameter | Type | Description |
---|---|---|
cart_key |
string | Unique identifier for the cart. ? optional |
Properties
Attribute | Type | Description |
---|---|---|
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
/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 data = {
"cart_item_key": 404dcc91b2aeaa7caa47487d1483e48a
};
CoCart.delete("item", data)
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
$.ajax({
url: "https://example.com/wp-json/cocart/v1/item",
method: "DELETE",
data: JSON.stringify({
"cart_item_key" : "404dcc91b2aeaa7caa47487d1483e48a"
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: 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',
'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 );
"Item has been removed from cart."
Restore Item to Cart
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.
Parameters
Parameter | Type | Description |
---|---|---|
cart_key |
string | Unique identifier for the cart. ? optional |
Properties
Attribute | Type | Description |
---|---|---|
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
/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 data = {
"cart_item_key": 404dcc91b2aeaa7caa47487d1483e48a
};
CoCart.get("item", data)
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
$.ajax({
url: "https://example.com/wp-json/cocart/v1/item",
method: "GET",
data: JSON.stringify({
"cart_item_key" : "404dcc91b2aeaa7caa47487d1483e48a"
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: 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',
'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'
] )
);
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v1/item', $args );
$body = wp_remote_retrieve_body( $response );
"Item has been restored to the cart.""
Update Item in Cart
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.
Parameters
Parameter | Type | Description |
---|---|---|
cart_key |
string | Unique identifier for the cart. ? optional |
Properties
Attribute | Type | Description |
---|---|---|
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
/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 data = {
"cart_item_key": 404dcc91b2aeaa7caa47487d1483e48a,
"quantity": 2
};
CoCart.post("item", data)
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
$.ajax({
url: "https://example.com/wp-json/cocart/v1/item",
method: "POST",
data: JSON.stringify({
"cart_item_key" : "404dcc91b2aeaa7caa47487d1483e48a",
"quantity" : 2
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: 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',
'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 );
{
"message":"The quantity for 'Woo T-Shirt' has increased to '2'.",
"quantity":2
}
Totals
Retrieve Cart Totals
This API helps you retrieve the cart totals. You can also return the totals pre-formatted to save you time applying the currency symbol.
Parameters
Parameter | Type | Description |
---|---|---|
cart_key |
string | Unique identifier for the cart. ? optional |
Properties
Attribute | Type | Description |
---|---|---|
html |
bool | Set as true to return the totals as strings with currency symbol. optional |
HTTP request
/wp-json/cocart/v1/totals
curl -X GET https://example.com/wp-json/cocart/v1/totals \
-H "Content-Type: application/json"
CoCart.get("totals")
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
$.ajax({
url: "https://example.com/wp-json/cocart/v1/totals",
method: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (response) {
console.log(response);
}
});
<?php
$curl = curl_init();
curl_setopt_array( $curl, array(
CURLOPT_URL => "https://example.com/wp-json/cocart/v1/totals",
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => array(
'Accept: 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',
),
'timeout' => 30
);
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v1/totals', $args );
$body = wp_remote_retrieve_body( $response );
{
"subtotal":"123.00",
"subtotal_tax":8.4,
"shipping_total":"33.00",
"shipping_tax":6.6,
"shipping_taxes": {
"12": 6.6
},
"discount_total":24.6,
"discount_tax":0,
"cart_contents_total":"98.40",
"cart_contents_tax":8.4,
"cart_contents_taxes": {
"12": 8.4
},
"fee_total":"0.00",
"fee_tax":0,
"fee_taxes":[],
"total":"146.40",
"total_tax":15
}
Here is what to do to return the totals formatted with currency symbol.
curl -X GET https://example.com/wp-json/cocart/v1/totals \
-H "Content-Type: application/json" \
-d '{
"html": true
}'
$.ajax({
url: "https://example.com/wp-json/cocart/v1/totals",
method: "GET",
data: JSON.stringify({
"html" : true
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (response) {
console.log(response);
}
});
<?php
$curl = curl_init();
$args = array(
'html' => true
);
curl_setopt_array( $curl, array(
CURLOPT_URL => "https://example.com/wp-json/cocart/v1/totals",
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => $args,
CURLOPT_RETURNTRANSFER => true
) );
$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( [
'html' => true
] ),
'timeout' => 30
);
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v1/totals', $args );
$body = wp_remote_retrieve_body( $response );
{
"subtotal":"£123.00",
"subtotal_tax":"£8.40",
"shipping_total":"£33.00",
"shipping_tax":"£6.60",
"shipping_taxes": {
"12": 6.6
},
"discount_total":"£24.60",
"discount_tax":"£0.00",
"cart_contents_total":"£98.40",
"cart_contents_tax":"£8.40",
"cart_contents_taxes": {
"12": 8.4
},
"fee_total":"£0.00",
"fee_tax":"£0.00",
"fee_taxes":[],
"total":"£146.40",
"total_tax":"£15.00"
}
Calculate Cart Totals
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
/wp-json/cocart/v1/calculate
curl -X POST https://example.com/wp-json/cocart/v1/calculate \
-H "Content-Type: application/json"
CoCart.post("calculate")
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
$.ajax({
url: "https://example.com/wp-json/cocart/v1/calculate",
method: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (response) {
console.log(response);
}
});
<?php
$curl = curl_init();
curl_setopt_array( $curl, array(
CURLOPT_URL => "https://example.com/wp-json/cocart/v1/calculate",
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => array(
'Accept: 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',
),
'timeout' => 30
);
$response = wp_remote_post( 'https://example.com/wp-json/cocart/v1/calculate', $args );
$body = wp_remote_retrieve_body( $response );
"Cart totals have been calculated."
Logout
New API since v2.1
This API logs out your customers. This will clear all session cookies for WordPress and CoCart.
HTTP request
/wp-json/cocart/v1/logout
curl -X POST https://example.com/wp-json/cocart/v1/logout \
-H "Content-Type: application/json" \
CoCart.post("logout")
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
$.ajax({
url: "https://example.com/wp-json/cocart/v1/logout",
method: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (response) {
console.log(response);
}
});
<?php
$curl = curl_init();
curl_setopt_array( $curl, array(
CURLOPT_URL => "https://example.com/wp-json/cocart/v1/logout",
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => array(
'Accept: 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',
),
'timeout' => 30
);
$response = wp_remote_post( 'https://example.com/wp-json/cocart/v1/logout', $args );
$body = wp_remote_retrieve_body( $response );
true
Load Cart from Session
New Feature since v2.1
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.
Load for the Web
To load the cart from session for the web, you must use the properties below to query your website.
https://example.com/cart/?cocart-load-cart=bbfa8e97ac9cff4c861d62a109e83bb6
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 |
Extending CoCart
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
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
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
<?php
add_filter( 'cocart_add_cart_item_data', 'my_add_cart_item_data', 10, 7 );
function my_add_cart_item_data( $cart_item_data ) {
// Add your validation here and simply return true|false.
return $cart_item_data;
}
Extending Schema
Details coming soon.
Actions
The cart API has a number of action hooks that you can use to extend the API to your needs.
See the tweaks plugin for examples.
Get Cart
Perhaps you need to apply something to the whole of the cart before it returns or send a notification. The choice is yours.
Use hook name: cocart_get_cart
Parameter | Type | Description |
---|---|---|
$cart_contents |
array | An array of items added to the cart. |
Clear Cart
Could be used to send a registered customer an email once they have emptied their cart. 😢
Use hook name: cocart_cart_cleared
Item Added
You can do something once an item has been added to the cart.
Use hook name: cocart_item_added_to_cart
Parameter | Type | Description |
---|---|---|
$item_key |
string | The cart item key of the product in the cart. |
$item_added |
array | The details of the added item. |
Item Removed
Use hook name: cocart_item_removed
Parameter | Type | Description |
---|---|---|
$current_data |
array | The details of the item removed. |
Item Restored
Use hook name: cocart_item_restored
Parameter | Type | Description |
---|---|---|
$current_data |
array | The details of the item restored. |
Item Quantity Changed
Should you need to change some other detail for the updated item.
Use hook name: cocart_item_quantity_changed
Parameter | Type | Description |
---|---|---|
$cart_item_key |
string | The cart item key of the product in the cart. |
$new_data |
array | The details of the item updated. |
Filters
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
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
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
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
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
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
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?
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
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
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
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
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
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
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
Cookie Supported?
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; });
Change Cookie Name
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;
}
Should cart cookie be secure?
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
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
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
<?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
If you are debugging CoCart during your development, enabling the logger is a great tool to have.
Then when making any request, you can view the logs created via your WordPress dashboard under WooCommerce > System Status > Logs
I personally like to change the WooCommerce log handler to be stored via the database which you set in your wp-config.php
file.
WooCommerce Log Handler
<?php
define( 'WC_LOG_HANDLER', 'WC_Log_Handler_DB' );
CoCart Logging filter
<?php
add_filter( 'cocart_logging', function() { return true; });
CORS: Allow all cross origin headers
Introduced filter since v2.2
If you are getting a warning about cross origin headers then you may need to enable support for it. Simply apply this filter and the headers will set for you with no further configuration.
<?php
add_filter( 'cocart_disable_all_cors', function() { return false; });
Set Allow Origin Header
Introduced filter since v2.5.1
For added security when you go into production. Set 'Access-Control-Allow-Origin' header to be more specific. Allow all cross origin headers must be enabled first as shown above.
<?php
add_filter( 'cocart_allow_origin', function() { return 'https://wp-demo.cocart.xyz'; });
Is REST API Request?
Introduced filter since v2.7.0
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;
});
Cookie: Samesite Attribute
Introduced filter since v2.9.1
This filter allows you to change the SameSite attribute applied to the CoCart cookie.
<?php
add_filter( 'cocart_cookie_samesite', function() {
return "None; Secure";
});
Misc
Merge Cart Items
This filter allows you to change how the items are merged together before loaded into session when requesting to keep the current cart via the web.
<?php
/**
* @param `$new_cart_content` - Returns the cart items merged from both cart in session and the cart requested to load.
* @param `$new_cart` - Returns the requested cart to load.
* @param `$cart_in_session` - Returns the current cart contents, if any.
* @return `$new_cart_content` - Returns your results of the cart contents.
*/
add_filter( 'cocart_merge_cart_content', 'merge_cart_contents', 10, 3 );
function merge_cart_contents( $new_cart_content, $new_cart, $cart_in_session ) {
return $new_cart_content;
}
Authenticate User ID
Introduced filter since v2.6.0
Overrides the determined user ID when authenticating. NOTE This will only be active if not already authenticated.
<?php
add_filter( 'cocart_authenticate', function(){});
CoCart Add-ons
CoCart Lite is just the tip of the iceberg. These add-ons take your headless build to the next level.
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
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.
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
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.
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
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.
Parameters
Parameter | Type | Description |
---|---|---|
cart_key |
string | Unique identifier for the cart. ? optional |
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
}
]
}
}'
$.ajax({
url: "https://example.com/wp-json/cocart/v1/add-item",
method: "POST",
data: JSON.stringify({
"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
}
]
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: 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 );
{
"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.
Parameters
Parameter | Type | Description |
---|---|---|
cart_key |
string | Unique identifier for the cart. ? optional |
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
}
}'
$.ajax({
url: "https://example.com/wp-json/cocart/v1/add-item",
method: "POST",
data: JSON.stringify({
"product_id": "129",
"quantity": 1,
"cart_item_data": {
"nyp": 24
}
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (response) {
console.log(response);
}
});
<?php
$curl = curl_init();
$args = array(
'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 );
{
"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
For more handling over CoCart for your store or a client, you will find that using the wp-config.php
file is the best place to setup certain conditions.
Uninstall
To prevent any data loss when uninstalling CoCart from the backend and to ensure only the site owner can perform this action. You need to enable the ability to remove it.
<?php
/**
* Allows the full un-installation of CoCart.
*/
define( 'COCART_REMOVE_ALL_DATA', true );
White Labelling
If you are developing a headless store for a client and need to hide CoCart. Enabling white label mode comes in handy if that is something you would want.
Enabling this hides CoCart completely from the backend including the admin menu, plugin row links, plugin notices, WooCommerce inbox notices and WooCommerce System Status information.
<?php
/**
* Hides CoCart from the WordPress dashboard.
*/
define( 'COCART_WHITE_LABEL', true );
Load Cart for the Web
Introduced filter since v2.8.2
In addition to white labelling, you can filter the parameter name cocart-load-cart
`to what ever you like.
<?php
/**
* Change the parameter name for loading the cart via the web.
*/
add_filter( 'cocart_load_cart_query_name', function() { return 'my-cart'; });
Libraries
- Node.js Library
npm install --save @cocart/cocart-rest-api
// import CoCartAPI from "@cocart/cocart-rest-api"; // Supports ESM
const CoCartAPI = require("@cocart/cocart-rest-api").default;
const CoCart = new CoCartAPI({
url: "https://example.com",
version: "cocart/v1"
});
Tools
Some useful tools you can use to access the API include:
- Postman - A multi platform REST API GUI client (using Google Chrome or installing the app on Mac OS X or Windows).
- Hoppscotch - A fast and beautiful API request builder (web alternative to Postman).
- ExtendsClass - Another web HTTP client.
- Insomnia - Similar to Postman using an app on Mac OS X, Windows or Ubuntu.
- CocoaRestClient - A Mac OS X GUI client for interacting with the API.
- Paw HTTP Client - Another HTTP client for Mac OS X.
- RESTClient, a debugger for RESTful web services - Free Firefox add-on.
- Advanced REST client - Free Google Chrome extension.
- Hookbin - Another tool to test web hooks.
If you use Postman you can use these collections made ready for you.
Learn more
Learn more about the REST API by checking the official WordPress REST API documentation.
Demo CoCart
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
/wp-json/cocart/v1/add-item
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
}'
CoCart.post("add-item", {
product_id: "183",
quantity: 1
})
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
$.ajax({
url: "https://wp-demo.cocart.xyz/wp-json/cocart/v1/add-item",
method: "POST",
data: JSON.stringify({
"product_id" : "183",
"quantity" : 1
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: 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. |
Changelog
Below is the changelog for "CoCart Lite" documentation that matches with the version of the plugin release.
Doc Version v2.9.8
- Added: Products section to help identify the CoCart Products add-on up top. Can still be found under "CoCart Add-ons" section.
- Updated: All links pointing to cocart.xyz are now tagged for referral identification.
- Updated: Knowledge Base content. Improved questions and linked new guide for creating a cart.
Doc Version v2.9.7
- Added: Explanation to merge carts together.
- Updated: Knowledge Base content.
- Updated: Accessing the Cart Key content.
Doc Version v2.9.6
- Improved: Confusion of parameters and attributes. If both exist for the API they are split into two seperate tables.
Doc Version v2.9.5
- Updated: jQuery request examples.
Doc Version v2.9.4
- Improved: Getting Started content.
- Added: Node JS example for demo section.
- Tweaked: Made sure action and filter examples for
wp-config.php
section are shown no matter the language selected. - Renamed: Hooks to Actions
Doc Version v2.9.3 - Plugin Version v2.9.1
- Introduced
cocart_cookie_samesite
filter. - Updated: Introduction content.
- Updated: Knowledge Base content.
Doc Version v2.9.2
- Improved: Authentication content.
- Improved: Knowledge Base content.
- Tweaked: Load Cart from Session content.
- Dev: Updated Slate to v2.9.1
Doc Version v2.9.1
- Corrected: Label for JS library.
- Improved: Cookie section.
- Renamed: FAQ to Knowledge Base.
- Improved: Knowledge Base content.
- Improved: Styling of the code examples.
- Improved: Cart key content.
- Improved: Load cart for the web content.
- Improved: Extending CoCart examples now always show no matter the set language.
Doc Version v2.9
- NEW: Added Libraries section.
- NEW: Node.js examples added for our official library.
Doc Version v2.8.4
- Removed
'Content-Type: application/json'
from cURL examples.
Doc Version v2.8.3 - Plugin Release v2.8.2
- Corrected: Examples for use of the cart key global parameter.
- Improved: Explaining the use of the cart key global parameter.
- Dev: Added filter
cocart_load_cart_query_name
to allow developers add more white labelling when loading the cart via the web. See example
Doc Version v2.8.2
- Added warning notice for load for the web feature.
- Updated FAQ.
Doc Version v2.8 - Plugin Release v2.6 to v2.7
Doc Version v2.7 - Plugin Release v2.5.1
- Dev: Added filter
cocart_allow_origin
to set the origin header for added layer of security when you go into production.
Doc Version v2.6 - Plugin Release v2.5
- Improved: Information about adding a variation to the cart.
Doc Version v2.5
- Added: More detail for setting a cart key.
- Added: More JSON response examples that were missing.
- Corrected: Same product ID used for all product type examples.
- Improved: Add variable item to cart examples.
- Improved: Table layouts in the Markdown source files.
- Removed: Context that is no longer valid with current version of CoCart.
- Updated: API versions table and Requirements.
Doc Version v2.4
- NEW: WooCommerce Extensions section added with Mix and Match Products and Name Your Price being the first.
- Updated: Cookies section.
Doc Version v2.3
- Added: New error responses.
- Fixed: Corrected typos.
- Tweaked: Improved code highlight theme for accessibility.
- Tweaked: Links are now unique. Fixes issue with similar links generated.
- Tweaked: Menu now has more padding.
- Updated: Plugin requirements for CoCart.
- Updated: Slate script to v2.7.0 which introduces the ability to copy code to clipboard.
Doc Version v2.2 - Plugin Release v2.2
- Dev: Added
cocart_disable_all_cors
filter to enable all cross origin headers. - Dev: Added filters to override the product name
cocart_item_added_product_name
and product titlecocart_item_added_product_title
when adding item to cart. - Dev: Added
cocart_item_added
filter to allow additional data to be returned when item is added to cart.
Doc Version v2.1 - Plugin Release v2.1.3
- NEW: Added example for adding product with Name Your Price WooCommerce extension.
Doc Version v2.0 - Plugin Release v2.1.2
- Tweaked: WP API examples.
- Removed: Warning notice in the introduction section.
Doc Version v1.9
- NEW: Added Cookie section.
- NEW: Added link to Postman collections.
- Tweaked: Certain features or API's are tagged to identify that they are only available in v2.1
- Removed: Persistent Cart documentation.
Doc Version v1.8 - Plugin Release v2.1
- NEW: Added support for guest carts with a new endpoint to retrieve those carts.
- NEW: Added ability to load a cart from session.
- NEW: Can now add items to cart using a products SKU ID.
- NEW: When an item is updated, removed or restored... the cart totals are re-calculated.
- Dev: Added filter
cocart_add_to_cart_validation
to allow plugin developers to pass their own validation before item is added to the cart. - Dev: Added filters to override the product name
cocart_product_name
and product titlecocart_product_title
when getting the cart contents. - Dev: Added filter
cocart_item_thumbnail_src
to override the source URL of the product thumbnail when getting the cart contents. - Dev: Added filter
cocart_add_to_cart_quantity
to override the quantity when adding an item. - Dev: Added filter
cocart_add_cart_item_data
so other plugins can pass cart item data when adding an item. - Dev: Added hook
cocart_user_switched
to allow something to happen if a user has switched. - Dev: Added hook
cocart_load_cart
to manipulate the merged cart before it set in session. - Dev: Added hook
cocart_load_cart_override
to manipulate the overriding cart before it set in session. - Dev: Added hook
cocart_item_added_updated_in_cart
for when an item was added again but updated in cart. - Dev: Added filter
cocart_cookie_supported
to allow developers to disable cookie session support if they don't/can't support cookies within their app.
Doc Version v1.7
- NEW: Added links to edit documentation at the top of each section.
- NEW: Added Getting Started section for those new to WordPress.
- Corrected: Typos.
- Tweaked: Menu
- Tweaked: Brand colours and updated favicons.
Doc Version v1.6 - Plugin Release v2.0.13
- NEW: Added
cocart_return_empty_cart
filter and example. - NEW: Added
cocart_add_to_cart_sold_individually_quantity
and example. - Changed: Quantity parameter type to
float
. - Tweaked: Authentication notice moved to the top of it's sections content.
- Tweaked: Menu, content and added helpful links.
- Tweaked: Filter examples to be code highlighted correctly.
Doc Version v1.5 - Plugin Release v2.0.7
- NEW: Added link to products add-on documentation under CoCart Pro.
- NEW: Added a little section explaining the body types when making a request.
- NEW: Added example to add item with custom cart item data.
- NEW: Added Demo section.
- Improved: Authentication section.
Doc Version v1.4
- NEW: Added live chat so users can ask questions.
- Made it clearer to understand about retrieving specific customers cart.
- Improved the introduction a little.
Doc Version v1.3
- Added languages for jQuery, PHP and WP API.
Doc Version v1.2
- Added Work in Progress section.
- Added Authentication section.
Doc Version v1.1
- Added Index API.
- Linked logo to documentation homepage.
Doc Version v1 - Plugin Release v2
- Updated for CoCart v2
Doc Version v0.5
- Added attribute table for view cart.
- Added missing examples for count items and get cart totals.
Doc Version v0.4 - Plugin Release v1.0.5
- Project renamed to CoCart.
- Changed support to contribution.
- Updated links.
- Added Insomnia as another tool you can use to access the API with.
- Removed all languages except for cURL showing examples on how to use with official library wrappers due to authentication required whic CoCart does not.
Doc Version v0.3 - Plugin Release v1.0.4
- Official libraries are not supported as they require authentication which this API does not.
- Removed installation instruction for official libraries.
- Replaced logo to prevent confusion with the official REST API documentation.
Doc Version v0.2 - Plugin Release v1.0.1
- Updated endpoint for updating, restoring and removing items.
Doc Version v0.1 - Plugin Release v1.0.0
- Initial Commit
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! 🙌