NAV
cURL jQuery PHP WP API

Introduction

GitHub Mark Logo Edit on GitHub

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

What is a REST API?

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

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

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

API Versions

The current WordPress REST API integration for CoCart is version v1 which takes a first-order position in the endpoints.

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

API Version CoCart Version WC Version WP Version PHP Version
v1 2.0.x or later 3.6.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
wc-api-v2 3.0.x or later 4.4 or later wc-api-v2 docs

Requirements

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

Request/Response Format

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

Some general information about response:

Body Types

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

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

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

Errors

Occasionally you might encounter errors when accessing the REST API. There are four 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 API keys
404 Not Found Requests to resources that don't exist or are missing
500 Internal Server Error Server error

WP REST API error example

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

CoCart error example

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

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

Parameters

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

Getting Started

GitHub Mark Logo Edit on GitHub

Install and Activate

How to install and activate the CoCart plugin.

List of server requirements.

Automatic installation

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

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

CoCart WordPress Plugin

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

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

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

GitHub - Download / Clone Plugin

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

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

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

Error Responses

GitHub Mark Logo Edit on GitHub

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

Error Status Error Response
cocart_cannot_read_cart Cannot read cart!
cocart_customer_missing Customer ID is required!
cocart_cart_id_missing Cart ID is required!
cocart_cart_in_session_not_valid Cart in session is not valid!
cocart_clear_cart_failed Clearing the cart failed!
cocart_product_id_required Product ID number is required!
cocart_product_id_not_numeric Product ID must be numeric!
cocart_quantity_not_numeric Quantity must be numeric!
cocart_product_does_not_exist Warning: This product does not exist!
cocart_product_sold_individually You cannot add another "%s" to your cart. %s is the product name
cocart_cannot_be_purchased Sorry, this product cannot be purchased.
cocart_product_out_of_stock You cannot add "%s" to the cart because the product is out of stock. %s is the product name
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.
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.
cocart_cannot_add_to_cart You cannot add "%s" to your cart. %s is the product name
cocart_can_not_remove_item Unable to remove item from cart.
cocart_can_not_restore_item Unable to restore item to the cart.
cocart_can_not_update_item Unable to update item quantity in cart.
cocart_cart_item_key_required Cart item key is required!
cocart_no_items No items in cart.
cocart_item_not_in_cart Item specified does not exist in cart.
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
cocart_invalid_variation_data Invalid value posted for %1$s. Allowed values: %2$s %1$s: Attribute name, %2$s: Allowed values
cocart_missing_variation_data Missing variation data for variable product. %s is a required field. %s: Attribute name.
cocart_missing_variation_data Missing variation data for variable product. %s are required fields. %s: Attribute name.
cocart_no_variation_found No matching variation found.
cocart_cart_invalid_parent_product This product cannot be added to the cart.
cocart_product_failed_validation Product did not pass validation!
cocart_product_sold_individually You cannot add another "%s" to your cart.
cocart_can_not_increase_quantity You can only have 1 %s in your cart. %s is the product name

Index

GitHub Mark Logo Edit on GitHub

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

HTTP request

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

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

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

$response = curl_exec($curl);

curl_close($curl);

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

JSON response example:

{
    "namespace": "cocart/v1",
    "routes": {
        "/cocart/v1": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": {
                        "namespace": {
                            "required": false,
                            "default": "cocart/v1"
                        },
                        "context": {
                            "required": false,
                            "default": "view"
                        }
                    }
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1"
            }
        },
        "/cocart/v1/add-item": {
            "namespace": "cocart/v1",
            "methods": [
                "POST"
            ],
            "endpoints": [
                {
                    "methods": [
                        "POST"
                    ],
                    "args": {
                        "product_id": {
                            "required": false,
                            "description": "Unique identifier for the product ID.",
                            "type": "integer"
                        },
                        "quantity": {
                            "required": false,
                            "default": 1,
                            "description": "The quantity amount of the item to add to cart.",
                            "type": "integer"
                        },
                        "variation_id": {
                            "required": false,
                            "description": "Unique identifier for the variation ID.",
                            "type": "integer"
                        },
                        "variation": {
                            "required": false
                        },
                        "cart_item_data": {
                            "required": false
                        },
                        "refresh_totals": {
                            "required": false,
                            "default": false,
                            "description": "Re-calculates the totals once item has been added or the quantity of the item has increased.",
                            "type": "boolean"
                        }
                    }
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/add-item"
            }
        },
        "/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": "bool"
                        }
                    }
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/calculate"
            }
        },
        "/cocart/v1/clear": {
            "namespace": "cocart/v1",
            "methods": [
                "POST"
            ],
            "endpoints": [
                {
                    "methods": [
                        "POST"
                    ],
                    "args": []
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/clear"
            }
        },
        "/cocart/v1/count-items": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": {
                        "return": {
                            "required": false,
                            "default": "numeric"
                        }
                    }
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/count-items"
            }
        },
        "/cocart/v1/get-cart": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": {
                        "thumb": {
                            "required": false,
                            "default": false,
                            "description": "Returns the URL of the product image thumbnail.",
                            "type": "boolean"
                        }
                    }
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/get-cart"
            }
        },
        "/cocart/v1/get-cart/(?P<id>[\\d]+)": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": {
                        "id": {
                            "required": true,
                            "description": "Unique identifier for the customer.",
                            "type": "integer"
                        },
                        "thumb": {
                            "required": false,
                            "default": false,
                            "description": "Returns the URL of the product image thumbnail.",
                            "type": "boolean"
                        }
                    }
                }
            ]
        },
        "/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"
                        },
                        "refresh_totals": {
                            "required": false,
                            "default": false,
                            "description": "Re-calculates the totals once item has been updated.",
                            "type": "boolean"
                        },
                        "return_cart": {
                            "required": false,
                            "default": false,
                            "description": "Returns the whole cart to reduce requests.",
                            "type": "boolean"
                        }
                    }
                },
                {
                    "methods": [
                        "POST"
                    ],
                    "args": {
                        "cart_item_key": {
                            "required": false,
                            "description": "Unique identifier for the item in the cart.",
                            "type": "string"
                        },
                        "refresh_totals": {
                            "required": false,
                            "default": false,
                            "description": "Re-calculates the totals once item has been updated.",
                            "type": "boolean"
                        },
                        "return_cart": {
                            "required": false,
                            "default": false,
                            "description": "Returns the whole cart to reduce requests.",
                            "type": "boolean"
                        },
                        "quantity": {
                            "required": false,
                            "default": 1,
                            "type": "integer"
                        }
                    }
                },
                {
                    "methods": [
                        "DELETE"
                    ],
                    "args": {
                        "cart_item_key": {
                            "required": false,
                            "description": "Unique identifier for the item in the cart.",
                            "type": "string"
                        },
                        "refresh_totals": {
                            "required": false,
                            "default": false,
                            "description": "Re-calculates the totals once item has been updated.",
                            "type": "boolean"
                        },
                        "return_cart": {
                            "required": false,
                            "default": false,
                            "description": "Returns the whole cart to reduce requests.",
                            "type": "boolean"
                        }
                    }
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/item"
            }
        },
        "/cocart/v1/totals": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": {
                        "html": {
                            "required": false,
                            "default": false
                        }
                    }
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/totals"
            }
        },
        "/cocart/v1/calculate/fees": {
            "namespace": "cocart/v1",
            "methods": [
                "POST"
            ],
            "endpoints": [
                {
                    "methods": [
                        "POST"
                    ],
                    "args": {
                        "set_session": {
                            "required": false,
                            "default": false,
                            "description": "Sets the cart fees in session once calculated.",
                            "type": "bool"
                        },
                        "return": {
                            "required": false,
                            "default": false,
                            "description": "Returns the cart fees once calculated.",
                            "type": "bool"
                        }
                    }
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/calculate/fees"
            }
        },
        "/cocart/v1/calculate/shipping": {
            "namespace": "cocart/v1",
            "methods": [
                "POST"
            ],
            "endpoints": [
                {
                    "methods": [
                        "POST"
                    ],
                    "args": {
                        "country": {
                            "required": true,
                            "description": "Country is a required minimum to calculate shipping.",
                            "type": "string"
                        },
                        "state": {
                            "required": false,
                            "description": "State is optional but maybe required under some circumstances.",
                            "type": "string"
                        },
                        "city": {
                            "required": false,
                            "description": "Enter City to specify location in country.",
                            "type": "string"
                        },
                        "postcode": {
                            "required": false,
                            "description": "Enter postcode / ZIP to narrow down location for more accurate shipping cost.",
                            "type": "string"
                        },
                        "return_methods": {
                            "required": false,
                            "default": false,
                            "description": "If set to true it will return shipping methods available once shipping is calculated.",
                            "type": "bool"
                        }
                    }
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/calculate/shipping"
            }
        },
        "/cocart/v1/customer": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": []
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/customer"
            }
        },
        "/cocart/v1/coupon": {
            "namespace": "cocart/v1",
            "methods": [
                "GET",
                "POST",
                "DELETE"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": []
                },
                {
                    "methods": [
                        "POST"
                    ],
                    "args": {
                        "coupon": {
                            "required": true,
                            "description": "Coupon to apply to the cart.",
                            "type": "string"
                        }
                    }
                },
                {
                    "methods": [
                        "DELETE"
                    ],
                    "args": {
                        "coupon": {
                            "required": true,
                            "description": "Coupon to remove from the cart.",
                            "type": "string"
                        }
                    }
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/coupon"
            }
        },
        "/cocart/v1/check-coupons": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": []
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/check-coupons"
            }
        },
        "/cocart/v1/cross-sells": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": {
                        "thumb": {
                            "required": false,
                            "default": false,
                            "description": "Returns the URL of the product image thumbnail.",
                            "type": "boolean"
                        }
                    }
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/cross-sells"
            }
        },
        "/cocart/v1/fees": {
            "namespace": "cocart/v1",
            "methods": [
                "GET",
                "POST",
                "DELETE"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": []
                },
                {
                    "methods": [
                        "POST"
                    ],
                    "args": {
                        "name": {
                            "required": true,
                            "description": "Name of the fee.",
                            "type": "string"
                        },
                        "amount": {
                            "required": true,
                            "description": "Amount for the fee.",
                            "type": "string"
                        },
                        "taxable": {
                            "required": false,
                            "default": false,
                            "description": "Determins if the fee is taxable.",
                            "type": "bool"
                        },
                        "tax_class": {
                            "required": false,
                            "description": "The tax class the fee applies to.",
                            "type": "string"
                        }
                    }
                },
                {
                    "methods": [
                        "DELETE"
                    ],
                    "args": []
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/fees"
            }
        },
        "/cocart/v1/payment-methods": {
            "namespace": "cocart/v1",
            "methods": [
                "GET",
                "POST"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": []
                },
                {
                    "methods": [
                        "POST"
                    ],
                    "args": {
                        "gateway_id": {
                            "required": true
                        }
                    }
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/payment-methods"
            }
        },
        "/cocart/v1/quantities": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": []
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/quantities"
            }
        },
        "/cocart/v1/removed-items": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": []
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/removed-items"
            }
        },
        "/cocart/v1/shipping-methods": {
            "namespace": "cocart/v1",
            "methods": [
                "GET",
                "POST"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": {
                        "recurring_cart_key": {
                            "required": false,
                            "description": "Recurring cart key is required only to get shipping methods for that subscription.",
                            "type": "string"
                        }
                    }
                },
                {
                    "methods": [
                        "POST"
                    ],
                    "args": {
                        "method_id": {
                            "required": true
                        },
                        "instance_id": {
                            "required": true
                        }
                    }
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/shipping-methods"
            }
        },
        "/cocart/v1/totals/discount": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": []
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/totals/discount"
            }
        },
        "/cocart/v1/totals/discount/coupon-totals": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": []
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/totals/discount/coupon-totals"
            }
        },
        "/cocart/v1/totals/discount/coupon-tax": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": []
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/totals/discount/coupon-tax"
            }
        },
        "/cocart/v1/totals/fee": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": []
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/totals/fee"
            }
        },
        "/cocart/v1/totals/fee/tax": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": []
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/totals/fee/tax"
            }
        },
        "/cocart/v1/totals/shipping": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": {
                        "calculate": {
                            "required": false,
                            "default": false
                        }
                    }
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/totals/shipping"
            }
        },
        "/cocart/v1/totals/shipping/tax": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": {
                        "calculate": {
                            "required": false,
                            "default": false
                        }
                    }
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/totals/shipping/tax"
            }
        },
        "/cocart/v1/totals/subtotal": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": []
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/totals/subtotal"
            }
        },
        "/cocart/v1/totals/subtotal/tax": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": []
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/totals/subtotal/tax"
            }
        },
        "/cocart/v1/totals/tax": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": []
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/totals/tax"
            }
        },
        "/cocart/v1/totals/total": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": []
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/totals/total"
            }
        },
        "/cocart/v1/weight": {
            "namespace": "cocart/v1",
            "methods": [
                "GET"
            ],
            "endpoints": [
                {
                    "methods": [
                        "GET"
                    ],
                    "args": []
                }
            ],
            "_links": {
                "self": "https://example.com/wp-json/cocart/v1/weight"
            }
        }
    },
    "_links": {
        "up": [
            {
                "href": "https://example.com/wp-json/"
            }
        ]
    }
}

Authentication

GitHub Mark Logo Edit on GitHub

CoCart can be authenticated by various methods with the WP REST API. First being via the REST API Keys in WooCommerce. Though this method is designed for the backend with their REST API, with some custom coding you can make it work for the frontend with CoCart.

Checkout my guide on how to authenticate with WooCommerce.

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

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

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

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

Thank you. 😄

Basic Authentication

What is the Basic Authentication method?

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

Steps to follow

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

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

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

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

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

$response = curl_exec($curl);

curl_close($curl);

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

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

JSON response example

{
  "404dcc91b2aeaa7caa47487d1483e48a":{
    "key":"404dcc91b2aeaa7caa47487d1483e48a",
    "product_id":32,
    "variation_id":0,
    "variation":[],
    "quantity":1,
    "line_tax_data":{
      "subtotal":[],
      "total":[]
    },
    "line_subtotal":18,
    "line_subtotal_tax":0,
    "line_total":18,
    "line_tax":0,
    "data":{}
  }
}

Authentication issues?

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

.htaccess Rewrite rule

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

JWT Authentication

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

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

Steps to follow

  1. Download and Install JWT Authentication plugin from WordPress.org.
  2. Configure the Secret Key.
  3. Get your token.
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/add-item",
  "headers": {
      "Authorization": "Bearer " + token,
  },
  "method": "POST",
  "data": {
    "product_id" : 32,
    "quantity" : 1
  },
};

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

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

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

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

$response = curl_exec($curl);

curl_close($curl);

echo $response;

Cookie

GitHub Mark Logo Edit on GitHub

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

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

The cookie stores 4 key values.

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

  1. Look for a cookie support add-on for your framework. React for example has one called react-cookies.
  2. Read the cookie value yourself and explode it by || and get the first key value. Once you have that value you can use it to set the cart_key parameter on all API requests. This will use the Set Cart ID Method.

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

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

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

Sometimes you need to avoid cookies. It's possible to do so by return the cart key when you return the cart endpoint. Simply download and activate the Get Cart Enhanced add-on plugin and you're good-to-go.

Cart

GitHub Mark Logo Edit on GitHub

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

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

Get Cart Contents

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

Properties

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

HTTP request

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

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

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

$response = curl_exec($curl);

curl_close($curl);

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

JSON response example

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

Here is what to do to include the product thumbnail.

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

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

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

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

$response = curl_exec($curl);

curl_close($curl);

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

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

JSON response example

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

Guest Customers

Supported in v2.1

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

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

Set Cart ID Method

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

Here are a few examples on how to pass the cart ID with each API request.

GET CART
/wp-json/cocart/v1/get-cart/?cart_key=9e18904482b4faf8762361836a83b93d
ADD ITEM
/wp-json/cocart/v1/add-item/?cart_key=9e18904482b4faf8762361836a83b93d&product_id=32

Retrieve a Cart

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

HTTP request

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

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

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

$response = curl_exec($curl);

curl_close($curl);

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

JSON response example

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

Clear Cart

GitHub Mark Logo Edit on GitHub

This API helps you clear the contents of the cart.

Properties

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

HTTP request

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

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

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

$response = curl_exec($curl);

curl_close($curl);

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

JSON response example

"Cart is cleared."

Count Items

GitHub Mark Logo Edit on GitHub

This API helps you count the items in the cart.

Properties

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

HTTP request

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

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

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

$response = curl_exec($curl);

curl_close($curl);

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

JSON response example

1

Calculate Cart Totals

GitHub Mark Logo Edit on GitHub

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

Properties

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

HTTP request

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

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

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

$response = curl_exec($curl);

curl_close($curl);

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

JSON response example

"Cart totals have been calculated."

Retrieve Cart Totals

GitHub Mark Logo Edit on GitHub

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

Properties

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

HTTP request

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

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

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

$response = curl_exec($curl);

curl_close($curl);

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

JSON response example

{
  "subtotal":"123.00",
  "subtotal_tax":8.4,
  "shipping_total":"33.00",
  "shipping_tax":6.6,
  "shipping_taxes": {
    "12": 6.6
  },
  "discount_total":24.6,
  "discount_tax":0,
  "cart_contents_total":"98.40",
  "cart_contents_tax":8.4,
  "cart_contents_taxes": {
    "12": 8.4
  },
  "fee_total":"0.00",
  "fee_tax":0,
  "fee_taxes":[],
  "total":"146.40",
  "total_tax":15
}

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

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

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

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

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

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$args = array(
  'html' => true
);
$response = wp_remote_get( 'https://example.com/wp-json/cocart/v1/totals', $args );
$body = wp_remote_retrieve_body( $response );

JSON response example

{
  "subtotal":"£123.00",
  "subtotal_tax":"£8.40",
  "shipping_total":"£33.00",
  "shipping_tax":"£6.60",
  "shipping_taxes": {
    "12": 6.6
  },
  "discount_total":"£24.60",
  "discount_tax":"£0.00",
  "cart_contents_total":"£98.40",
  "cart_contents_tax":"£8.40",
  "cart_contents_taxes": {
    "12": 8.4
  },
  "fee_total":"£0.00",
  "fee_tax":"£0.00",
  "fee_taxes":[],
  "total":"£146.40",
  "total_tax":"£15.00"
}

Items

GitHub Mark Logo Edit on GitHub

The most important part of CoCart is adding items to the 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.

Add Item to Cart

GitHub Mark Logo Edit on GitHub

This API helps you to add an item to the cart. You can also request to return the whole cart once item is added to reduce API requests and use the Get Cart Content properties.

Properties

Property Type Description
cart_key string Unique identifier for the cart. optional
product_id integer The product ID is required in order to add a product to the cart. 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 array Attribute values. optional
cart_item_data array Used to apply extra cart item data we want to pass with the item. optional
return_cart bool Set as true to return the cart once item added. optional

HTTP request

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

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

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

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

$response = curl_exec($curl);

curl_close($curl);

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

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

JSON response example

{
  "404dcc91b2aeaa7caa47487d1483e48a":{
    "key":"404dcc91b2aeaa7caa47487d1483e48a",
    "product_id":32,
    "variation_id":0,
    "variation":[],
    "quantity":1,
    "line_tax_data":{
      "subtotal":[],
      "total":[]
    },
    "line_subtotal":18,
    "line_subtotal_tax":0,
    "line_total":18,
    "line_tax":0,
    "data":{}
  }
}

Add Variation Item to Cart

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

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

What are attributes?

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

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

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

curl -X POST https://example.com/wp-json/cocart/v1/add-item \
  -H "Content-Type: application/json" \
  -d '{
    "product_id": 1723,
    "quantity": 1,
    "variation_id": 1820,
    "variation": {
      "attribute_colours": "Red",
      "attribute_pa_size": "2x-large"
    }
  }'
var settings = {
  "url": "https://example.com/wp-json/cocart/v1/add-item",
  "method": "POST",
  "data": {
    "product_id": 1722,
    "quantity": 1,
    "variation_id": 1820,
    "variation": {
      "attribute_colours": "Red",
      "attribute_pa_size": "2x-large"
    }
  }
};

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

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

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

$response = curl_exec($curl);

curl_close($curl);

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

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

JSON response example

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

Add Item to Cart + Custom Data

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

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

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

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

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

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$args = array(
  'headers' => array(
    'Content-Type' => 'application/json; charset=utf-8',
  ),
  'body' => wp_json_encode( [
    'product_id' => 3008,
    'quantity' => 1
    'cart_item_data' => array(
      'engraved_name' => 'Sébastien Dumont',
      'engraved_size' => 'Medium'
    )
  ] ),
  'timeout' => 30
);
$response = wp_remote_post( 'https://example.com/wp-json/cocart/v1/add-item', $args );
$body = wp_remote_retrieve_body( $response );

JSON response example

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

Remove Item from Cart

GitHub Mark Logo Edit on GitHub

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

Properties

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

HTTP request

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

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

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

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

$response = curl_exec($curl);

curl_close($curl);

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

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

JSON response example

"Item has been removed from cart."

Restore Item to Cart

GitHub Mark Logo Edit on GitHub

This API helps you to restore an item to the cart. You can also request to return the whole cart once item is restored to reduce API requests and use the Get Cart Content properties.

Properties

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

HTTP request

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

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

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

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

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
  'headers' => array(
    'Content-Type' => 'application/json; charset=utf-8',
  ),
  'body' => wp_json_encode( [
    'cart_item_key' => '404dcc91b2aeaa7caa47487d1483e48a'
  ] )
);

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

JSON response example

"Item has been restored to the cart.""

Update Item in Cart

GitHub Mark Logo Edit on GitHub

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

Properties

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

HTTP request

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

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

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

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

$response = curl_exec($curl);

curl_close($curl);

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

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

JSON response example

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

Load Cart from Session

New Feature in v2.1

GitHub Mark Logo Edit on GitHub

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

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

It can also be used to transfer the cart over to the web version of your store. This 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 data together.

Properties

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

Load for the Web

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

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

Logout

New API in v2.1

GitHub Mark Logo Edit on GitHub

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

HTTP request

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

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

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

$response = curl_exec($curl);

curl_close($curl);

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

JSON response example

true

Extending CoCart

CoCart is developer friendly. Every part of the API allows a developer to make changes to their needs so the API works according to their code design.

Filters

GitHub Mark Logo Edit on GitHub

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

See the tweaks plugin for examples.

Change empty response

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

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

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

Change thumbnail size

By default the size of the thumbnail uses woocommerce_thumbnail. You can change this by filtering the size using cocart_item_thumbnail_size filter.

<?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;
}

Sold Individually Quantity Override

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

Return cart contents

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

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

<?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;
}

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

Override 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';
}

Override 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';
}

Override product thumbnail source

This filter in particular allows you to change the source 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';
}

Override 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;
}

Return Cart Session Contents

Identical to cocart_return_cart_contents filter, only this one is used to filter the cart contents returned for a cart in session.

<?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;
}

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

This filter allows you to disable the cookie support for handling the session for guest customers. This is so you don't overload the cart database when the session is initialized if you are using the alternative method for guest customers.

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

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

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 * 6; });
add_filter( 'cocart_cart_expiration', function() { return DAY_IN_SECONDS * 7; });

Empty Cart Expiration

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. Can not be longer than 42 characters for the database.

<?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>' ) );
}

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.
 */
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;
}

CoCart Logging

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

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

Allowing all cross origin headers

New Filter in 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

New Filter in v2.5.1

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

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

Hooks

GitHub Mark Logo Edit on GitHub

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

See the tweaks plugin for examples.

Get Cart

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

Use hook name: cocart_get_cart

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

Clear Cart

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

Use hook name: cocart_cart_cleared

Item Added

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

Use hook name: cocart_item_added_to_cart

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

Item Removed

Use hook name: cocart_item_removed

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

Item Restored

Use hook name: cocart_item_restored

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

Item Quantity Changed

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

Use hook name: cocart_item_quantity_changed

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

CoCart Add-ons

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

CoCart Pro

GitHub Mark Logo Edit on GitHub

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

Purchase here

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

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

CoCart Products

GitHub Mark Logo Edit on GitHub

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

Purchase here

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

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

WooCommerce Extensions

GitHub Mark Logo Edit on GitHub

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

Mix and Match Products

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

Add item to Cart

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

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

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

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

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

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$args = array(
  'headers' => array(
    'Content-Type' => 'application/json; charset=utf-8',
  ),
  'body' => wp_json_encode( [
    'product_id' => 1102,
    'quantity' => 5,
    'cart_item_data' => array(
        'mnm_config' => array(
            array(
                'product_id' => 987,
                'quantity' => 1
            ),
            array(
                'product_id' => 1001,
                'quantity' => 2
            ),
            array(
                'product_id' => 1003,
                'quantity' => 3
            )
        )
    )
  ] ),
  'timeout' => 30
);
$response = wp_remote_post( 'https://example.com/wp-json/cocart/v1/add-item', $args );
$body = wp_remote_retrieve_body( $response );

JSON response example

{
    "6563b32f054b00c7ed83ce4c9bb9eedd": {
        "mnm_config": {
            "987": {
                "product_id": 987,
                "quantity": 1
            },
            "1001": {
                "product_id": 1001,
                "quantity": 2
            },
            "1003": {
                "product_id": 1003,
                "quantity": 3
            }
        },
        "mnm_contents": [
            "8e9868e336b9bafe4722c31ade00a8f6",
            "a29fe85f04188ccc5a7106dec6f5ca89",
            "4531239fed8c9875e0cce609b86be85a"
        ],
        "key": "6563b32f054b00c7ed83ce4c9bb9eedd",
        "product_id": 1102,
        "variation_id": 0,
        "variation": [],
        "quantity": 1,
        "data_hash": "d88f7e7e5dfa45731252a34e3e64325c",
        "line_tax_data": {
            "subtotal": [],
            "total": []
        },
        "line_subtotal": 9.7013,
        "line_subtotal_tax": 0,
        "line_total": 9.7013,
        "line_tax": 0,
        "data": {
            "product_type": "mix-and-match",
            "is_nyp": false
        },
        "product_name": "Mix and Match Products",
        "product_title": "Mix and Match Products",
        "product_price": "£2.00"
    },
    "8e9868e336b9bafe4722c31ade00a8f6": {
        "mnm_container": "6563b32f054b00c7ed83ce4c9bb9eedd",
        "mnm_child_id": 1102,
        "product_id": 987,
        "variation_id": 0,
        "variation": [],
        "quantity": 1,
        "line_tax_data": {
            "subtotal": [],
            "total": []
        },
        "line_subtotal": 1.28355,
        "line_subtotal_tax": 0,
        "line_total": 1.28355,
        "line_tax": 0,
        "data": {},
        "product_name": "Cupcake",
        "product_title": "Cupcake",
        "product_price": "£1.28"
    },
    "a29fe85f04188ccc5a7106dec6f5ca89": {
        "mnm_container": "6563b32f054b00c7ed83ce4c9bb9eedd",
        "mnm_child_id": 1102,
        "product_id": 1001,
        "variation_id": 0,
        "variation": [],
        "quantity": 2,
        "line_tax_data": {
            "subtotal": [],
            "total": []
        },
        "line_subtotal": 2.5671,
        "line_subtotal_tax": 0,
        "line_total": 1.28355,
        "line_tax": 0,
        "data": {},
        "product_name": "Turquoise Cupcake",
        "product_title": "Turquoise Cupcake",
        "product_price": "£1.28"
    },
    "4531239fed8c9875e0cce609b86be85a": {
        "mnm_container": "6563b32f054b00c7ed83ce4c9bb9eedd",
        "mnm_child_id": 1102,
        "product_id": 1003,
        "variation_id": 0,
        "variation": [],
        "quantity": 3,
        "line_tax_data": {
            "subtotal": [],
            "total": []
        },
        "line_subtotal": 3.85065,
        "line_subtotal_tax": 0,
        "line_total": 1.28355,
        "line_tax": 0,
        "data": {},
        "product_name": "Buttercup and Bumblebee Cupcakes",
        "product_title": "Buttercup and Bumblebee Cupcakes",
        "product_price": "£1.28"
    }
}

Retrieve a product

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

Name Your Price

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

Add item to Cart

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

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

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

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

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

$response = curl_exec($curl);

curl_close($curl);

echo $response;
<?php
$args = array(
  'headers' => array(
    'Content-Type' => 'application/json; charset=utf-8',
  ),
  'body' => wp_json_encode( [
    'product_id' => 129,
    'quantity' => 1,
    'cart_item_data' => array(
      'nyp' => 24
    )
  ] ),
  'timeout' => 30
);
$response = wp_remote_post( 'https://example.com/wp-json/cocart/v1/add-item', $args );
$body = wp_remote_retrieve_body( $response );

JSON response example

{
    "nyp": "24",
    "key": "1dc5e4af26b22d63451acb95d2b9deba",
    "product_id": 129,
    "variation_id": 0,
    "variation": [],
    "quantity": 1,
    "data": {},
    "data_hash": "b5c1d5ca8bae6d4896cf1807cdf763f0",
    "line_tax_data": {
        "subtotal": [],
        "total": []
    },
    "line_subtotal": 24,
    "line_subtotal_tax": 0,
    "line_total": 24,
    "line_tax": 0,
    "product_name": "Name your price",
    "product_title": "Name your price",
    "product_price": "£24.00"
}

Demo CoCart

GitHub Mark Logo Edit on GitHub

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

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

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

Adding an item

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

HTTP request

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

View more on add to cart

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

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

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

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

$response = curl_exec($curl);

curl_close($curl);

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

Authenticate Customer

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

Username Password
demo &nm5y7^sf&hm1D5MwKLgrQeC

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

Products

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

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

Coupons

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

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

Tools

GitHub Mark Logo Edit on GitHub

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

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

Learn more

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

Changelog

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

Doc Version v2.7 - Plugin Release v2.5.1

Doc Version v2.6 - Plugin Release v2.5

Doc Version v2.5

Doc Version v2.4

Doc Version v2.3

Doc Version v2.2 - Plugin Release v2.2

Doc Version v2.1 - Plugin Release v2.1.3

Doc Version v2.0 - Plugin Release v2.1.2

Doc Version v1.9

Doc Version v1.8 - Plugin Release v2.1

Doc Version v1.7

Doc Version v1.6 - Plugin Release v2.0.13

Doc Version v1.5 - Plugin Release v2.0.7

Doc Version v1.4

Doc Version v1.3

Doc Version v1.2

Doc Version v1.1

Doc Version v1 - Plugin Release v2

Doc Version v0.5

Doc Version v0.4 - Plugin Release v1.0.5

Doc Version v0.3 - Plugin Release v1.0.4

Doc Version v0.2 - Plugin Release v1.0.1

Doc Version v0.1 - Plugin Release v1.0.0

Contribute

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

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

Thank you for your support! 🙌