Methods for cart management

Find out more about cart in its current state.

With Checkout API, you can manage shopping cart on the storefront with JavaScript code: get cart contents, add or remove product positions, set an address for the customer, etc. These methods work from any Ecwid storefront page.

Learn about all available methods below.

Enable JS API on the storefront

The methods listed below require JS API to be loaded on the page. Read more on how to enable JS API.

Ecwid.Cart.get()

This method allows you to receive full information about the current shopping cart. The response is available in the callback cart function.

Code example:

Ecwid.Cart.get(function(cart){
  console.log(JSON.stringify(cart));
});

/* prints

{
    "id": "TJ6VG",
    "cartId": "99E7E224-5F6F-4C00-BFE9-9F72F2B5A471",
    "orderId": 506524300,
    "items": [
        {
            "quantity": 2,
            "product": {
                "id": 455570501,
                "sku": "0000077",
                "price": 500,
                "name": "Pizza #2",
                "weight": 1,
                "shortDescription": "",
                "url": "https://example.company.site/products/Example-product-p455570501",
                "variation": 2343242
            },
            "options": {}
        },
        {
            "quantity": 4,
            "product": {
                "id": 439710255,
                "sku": "000001",
                "price": 500,
                "name": "Pizza",
                "weight": 0.5,
                "shortDescription": "",
                "url": "https://example.company.site/products/Example-product-2-p439710255"
            },
            "options": {
                "Size": "L, R",
                "Print_number": "123"
            }
        }
    ],
    "productsQuantity": 6,
    "shippingMethod": "Pickup",
    "shippingPerson": {
        "countryCode": "GE",
        "countryName": "Georgia",
        "name": "Jhn Doe",
        "phone": "16019521325",
        "stateOrProvinceCode": "TB"
    },
    "weight": 6
}

/*

cart

NameTypeDescription
cartIdstringCart ID. Matches with the cart ID in REST API /carts endpoint.
idstringOrder ID, assigned to the cart. Remains the same when an order is placed.
couponNamestringName of the discount coupon applied to the cart. Does not contain the actual coupon code.
itemsarray{object}Details about products in the shopping cart.
orderIdnumberInternal order ID.
productsQuantitynumberTotal quantity of products added to the shopping cart.
weightnumberTotal weight of products added to the shopping cart.
shippingMethodstringName of the selected shipping method. Available only when a customer goes to the checkout_payment_details page.
shippingPersonobject{shippingPerson}Details about shipping address. Available only when a customer goes to the shipping_delivery page.

items

items contains an array of objects with the details for each product added to the shopping cart.

NameTypeDescription
quantitynumberQuantity of the specific product added to the shopping cart.
productobject{product}Details about the product added to the shopping cart.
optionsobjectMap of the selected product options (option name as a key and option value as a value). Code example:
"options": { "Size": "L, R", "Print_number": "123" }

product

NameTypeDescription
idnumberProduct ID. Matches product ID in REST API.
skustringProduct SKU.
pricenumberProduct price before applied taxes, fees, or discounts.
namestringProduct name.
weightnumberProduct weight.
shortDescriptionstringProduct description truncated to 120 characters.
urlstringLink to the product page.
variationnumberProduct variation ID.

shippingPerson

NameTypeDescription
namestringCustomer's name.
companyNamestring, optionalCompany name of a customer, if available.
streetstring, optionalShipping/billing address. Street.
citystring, optionalShipping/billing address. City.
countryNamestring, optionalShipping/billing address. Country name.
countryCodestring, optionalShipping/billing address. Country code in ISO 3166-2.
postalCodestring, optionalShipping/billing address. ZIP code.
stateOrProvinceCodestring, optionalShipping/billing address. State code ISO 3166-2.
phonestring, optionalCustomer's phone number, if available.

Ecwid.Cart.addProduct()

This method allows you to add a new product position to the shopping cart. It accepts two arguments: product and callback. The product argument accepts either product ID or a product object with extended details including product ID, quantity, selected options, or subscription product settings.

When you use this method, it first checks the product by specified ID for stock and variations. If the selected options match one of the variations, Ecwid will check its stock first. If you don't have enough stock to add a product, Ecwid adds the available quantity. If the product is out of stock, nothing is added to the shopping cart.

Code example:

var product = {
  id: 10,
  quantity: 3,
  options: {
    "Size": "L"
  },
  recurringChargeSettings: { 
    recurringInterval: "month",
    recurringIntervalCount: 1,
    },
  callback: function(success, product, cart) {
    // ...  
  }
}

Ecwid.Cart.addProduct(product);

product argument fields:

NameTypeDescription
idnumberProduct ID.
quantitynumberQuantity that will be added to the shopping cart.
optionsobject{options}Selected product options. Must match options available on the product page. Code example:
"options": { "Size": "L, R", "Print_number": "123" }
selectedPricenumberSelected price for the product with the parameter "nameYourPriceEnabled": true. If specified for a product with "nameYourPriceEnabled": false, the product will be added with the default price.
recurringChargeSettingsobject{recurringChargeSettings}Define subscription product settings if needed.
callbackfunction(arguments){}Define the callback function.

recurringChargeSettings

FieldTypeDescription
recurringIntervalstringCharge recurring interval. Supported values: DAY, WEEK, MONTH, YEAR.
recurringIntervalCountnumberCharge recurring interval. Supported values: for DAY - 1 (daily), for WEEK - 1 (weekly), 2 (biweekly), for MONTH - 1 (monthly), 3 (quarterly), for YEAR - 1 (annually).

callback

Callback function receives 4 arguments: success, product, cart, error

NameTypeDescription
successbooleanIndicates operation status. If true - the product was added to the shopping cart.
productobject{product}product object after the operation.
cartobject{cart}cart object after the operation.
errorstringIf success is false, contains error message.

Ecwid.Cart.removeProduct()

This method removes product position from the shopping cart entirely. It has one argument called index that accepts the index of the product position.

Get an index from the Ecwid.Cart.get() method. Position of the product in the items array is the index. For example, if you have two different products added to the cart, the first product has an index of 0, and the second has an index of 1.

Code example.

Ecwid.Cart.removeProduct(0);

This method can only remove the product from the cart, it cannot decrease its quantity. If you want to decrease the quantity, first make the Ecwid.Cart.get() request, save product details, then call Ecwid.Cart.removeProduct() and add the product back with decreased quantity with Ecwid.Cart.addProduct().

Ecwid.Cart.clear()

This method allows you to clear all details from the shopping cart. It has a callback function with two arguments: success (boolean) and error (string). If the method clears the cart successfully, you receive true in the success argument.

Code example:

Ecwid.Cart.clear(function(success,error) { 
  if (success == true) {
      console.log("Cart was cleared");
  } else {
      console.log("Cart clear failed. Error message: " + error);
  }
});

// prints
// Cart was cleared

Ecwid.Cart.calculateTotal()

This method calculates the cart total asynchronously and passes the result as an order callback argument with a snapshot of the generated order with essential details.

Code example:

Ecwid.Cart.calculateTotal(function(order) {
  console.log(JSON.stringify(order));
});

/* prints

{
    "subtotal": 3500,
    "subtotalWithoutTax": 3500,
    "total": 3850,
    "totalWithoutTax": 3500,
    "tax": 350,
    "couponDiscount": 0,
    "volumeDiscount": 0,
    "customerGroupDiscount": 0,
    "customerGroupVolumeDiscount": 0,
    "discount": 0,
    "shipping": 0,
    "shippingWithoutTax": 0,
    "handlingFee": 0,
    "handlingFeeWithoutTax": 0,
    "pricesIncludeTax": false,
    "cart": {
        "id": "TJ6VG",
        "cartId": "99E7E224-5F6F-4C00-BFE9-9F72F2B5A471",
        "orderId": 506524300,
        "items": [
            {
                "quantity": 3,
                "product": {
                    "id": 455570501,
                    "sku": "0000077",
                    "price": 500,
                    "name": "Pizza #2",
                    "weight": 1,
                    "shortDescription": "",
                    "url": "https://example.company.site/products/Example-product-p455570501"
                },
                "options": {}
            },
            {
                "quantity": 4,
                "product": {
                    "id": 439710255,
                    "sku": "000001",
                    "price": 500,
                    "name": "Pizza",
                    "weight": 1,
                    "shortDescription": "123 pie",
                    "url": "https://wexample.company.site/products/Example-product-2-p439710255"
                },
                "options": {
                    "Size": "L, R",
                    "djbfdmnfb": "1234"
                }
            }
        ],
        "productsQuantity": 7,
        "shippingMethod": "Pickup",
        "shippingPerson": {
            "countryCode": "GE",
            "countryName": "Georgia",
            "name": "Jon Stewart Doe",
            "phone": "16019521325",
            "stateOrProvinceCode": "TB"
        },
        "weight": 7
    }
}

*/

Subscribe to the Ecwid.OnAPILoaded JS API event to ensure availability of this function.

order argument fields

NameTypeDescription
cartobject{cart}Contains full cart details matching the Ecwid.Cart.get() result.
couponDiscountnumberTotal discount from applied coupons.
customerGroupDiscountnumberDiscount value from customer group discounts.
customerGroupVolumeDiscountnumberAbsolute discount from customer group discounts.
discountnumberTotal discount value from all sources.
handlingFeenumberTotal fees applied to order.
handlingFeeWithoutTaxnumberTotal fees applied to order before taxes.
pricesIncludeTaxbooleanSpecifies if product prices include taxes defining tax calculation formulae. If true, the store works with "gross prices". If false the store works with "net prices".
shippingnumberTotal shipping cost.
shippingWithoutTaxnumberTotal shipping cost before taxes applied.
subtotalnumberOrder subtotal. Includes the shopping cart total with discounts and taxes but without shipping costs or handling fees.
subtotalWithoutTaxnumberOrder subtotal before applied taxes.
taxnumberTotal sum of taxes applied to order.
totalnumberOrder total that includes all costs, fees, taxes, and discounts.
totalWithoutTaxnumberOrder total before taxes applied.
volumeDiscountnumberTotal discount for order subtotal.

Ecwid.Cart.canGotoCheckout()

This method checks whether you can send customers to the first step of the checkout. It has one callback argument containing the boolean response. If true, you can send customers to the checkout, for example, with the Ecwid.Cart.gotoCheckout() method.

Ecwid.Cart.canGotoCheckout(function(callback){
  console.log(callback);
});

// prints
// true

Ecwid.Cart.gotoCheckout();

This method sends a customer to the first checkout step. This method only works if your checkout doesn't require legal terms checkboxes. Find legal terms setting in Ecwid admin > Settings > General > Legal Pages > "Show “I agree with Terms & Conditions”. Or check the availability of this method with the Ecwid.Cart.canGotoCheckout().

Code example:

Ecwid.Cart.gotoCheckout(function(){
  console.log("Checkout process started");
});

// prints
// Checkout process started

Ecwid.Cart.setCustomerEmail()

This method allows you to pre-define customer email with JavaScript. Combined with the Ecwid.Cart.gotoCheckout() you can skip the first checkout step. The method has three callback arguments: email, successCallback and errorCallback.

The email argument defines the customer email, and callback arguments are functions called if the method works successfully or fails.

Code example:

Ecwid.Cart.setCustomerEmail(
    "[email protected]",
    function (successCallback) { console.log("Success") },
    function (errorCallback) { console.log("Fail") }
);

// prints
// Success

Ecwid.Cart.setOrderComments()

This method allows you to pre-define customer comments for order with JavaScript. The method has three callback arguments: orderComments, successCallback and errorCallback.

The orderComments argument defines the customer email, and callback arguments are functions called if the method works successfully or fails.

Code example:

Ecwid.Cart.setOrderComments(
    "Please ask courier to call  1-800 on the door",
    function (successCallback) { console.log("Success") },
    function (errorCallback) { console.log("Fail") }
);

// prints
// Success

Ecwid.Cart.setAddress()

This method allows you to prefill the shipping address before customers get to the checkout. It is useful when you want to remove some address fields, like country or state. Prefill address fields with this method and then hide them with CSS {display: none;} style.

The method has three arguments: address with the address details and two function callbacks, successCallback called if the method works successfully, and errorCallback called if it fails.

Ecwid.Cart.setAddress(
	{
		"name": "John Carmichael",
  	"companyName": "Cool Slippers",
  	"street": "5th Ave",
  	"city": "New York",
  	"countryName": "United States",
  	"postalCode": "10002",
  	"stateOrProvinceCode": "NY",
  	"phone": "+1 234 523 11 42"
  },
  function(successCallback){ console.log('Success') },
  function(errorCallback){ console.log('Fail') }
);

// prints
// Success

Address fields in this method match the shippingPerson object.

Ecwid.Cart.setBillingAddress()

This method allows you to prefill the customer billing address before customers get to the checkout. It accepts three arguments: address with the address details and two function callbacks, successCallback called if the method works successfully, and errorCallback called if it fails.

Ecwid.Cart.setBillingAddress(
	{
		"name": "John Carmichael",
  	"companyName": "Cool Slippers",
  	"street": "5th Ave",
  	"city": "New York",
  	"countryName": "United States",
  	"postalCode": "10002",
  	"stateOrProvinceCode": "NY",
  	"phone": "+1 234 523 11 42"
  },
  function(successCallback){ console.log('Success') },
  function(errorCallback){ console.log('Fail') }
);

// prints
// Success

Address fields in this method match the shippingPerson object.

Set order referer

This method allows you to declare the ec.order.referer_id variable in your JavaScript code to set the order referer.

Code example:

ec.order = ec.order || {};
ec.order.referer_id = 'Amazon'

The field appears in exported order CSVs, invoices, email notifications, and REST API as refererId field.