Public API

The public API is the new way to access Snipcart data. It allows you to retrieve some relevant information about the current Snipcart session.

All methods of the public API can be accessed through the Snipcart.api object.

Make sure that you always call these methods when Snipcart is fully loaded. We suggest you subscribe to the snipcart.ready event and do the operations needed in the callback of this event.

document.addEventListener('snipcart.ready', function() {
    var count = Snipcart.api.items.count();
});

The API exposes multiple services.

  • cart gives you access to some cart details such as billing and shipping information. You can also start a new cart, store information in cart metadata and some other useful actions.
  • items lets you manage items in the cart, you can add new items, remove some of them or clear them all. You can also retrieve the actual cart items.
  • plans lets you manage plans in the cart, you can add new plans, remove a single one of clear them all. You can also retrieve the plans in the cart.
  • discounts lets you add new discounts to the cart. It can be used to add discounts trigerred by a coupon code only.
  • modal lets you show or hide Snipcart modal window.
  • user lets you retrieve information on the current logged in user.
  • products lets you set product metadata.

All async methods return promises. If you are not familiar with this concept we suggest you read this excellent introduction on Google website.


cart

Snipcart.api.cart allows you to interact with the current order.

get

This method returns the current cart data. If there is no cart in progress, we return null.

var cart = Snipcart.api.cart.get();

​ The method will return a JSON object like this: ​

{
    "currency": "cad",
    "customFields": [{
        "name": "Slug",
        "options": "",
        "type": "textbox",
        "value": "Test",
        "required": true,
    }, {
        "name": "Average age",
        "options": "20-25|25-30|30-35",
        "type": "dropdown",
        "value": "",
        "required": false,
    }, {
        "name": "Do you accept terms",
        "options": "true|false",
        "type": "checkbox",
        "value": "true",
        "required": true,
    }],
    "token": "5bdfe11f-63d2-4fcc-8bc3-98978fe5a64d",
    "email": "geeks@snipcart.com",
    "mode": "Test",
    "status": "InProgress",
    "shipToBillingAddress": true,
    "billingAddress": {
        "name": "John Doe",
        "company": "Snipcart",
        "address1": "226 rue Saint-Joseph E",
        "address2": "",
        "city": "Quebec",
        "country": "CA",
        "postalCode": "G1K3A9",
        "province": "QC",
        "phone": "418 888 8888",
        "email": "geeks@snipcart.com",
        "shippingSameAsBilling": true,
        "errors": null
    },
    "completionDate": null,
    "invoiceNumber": "",
    "paymentMethod": 0,
    "items": [{
        "quantity": 1,
        "stackable": true,
        "uniqueId": "e86a3fc3-46d5-491b-9afd-f2426c78f06c",
        "token": "5bdfe11f-63d2-4fcc-8bc3-98978fe5a64d",
        "id": "SMARTPHONE",
        "name": "Smartphone",
        "price": 399,
        "description": "",
        "url": "/",
        "image": "",
        "minQuantity": null,
        "maxQuantity": null,
        "shippable": true,
        "taxable": true,
        "taxes": [],
        "customFields": [{
            "name": "Memory size",
            "options": "16GB|32GB[+50.00]",
            "type": "dropdown",
            "value": "32GB",
            "operation": "50",
            "required": false,
            "sanitizedName": "snipcart_custom_Memory-size"
        }],
        "duplicatable": false,
        "alternatePrices": {
            "vip": 299
        },
        "unitPrice": 449,
        "totalPrice": 449,
        "addedOn": "2016-04-11T21:48:41.563Z",
        "dimensions": {}
    }],
    "discounts": [{
        "id": "c7333bdb-615e-4cc4-aafc-cfbbd8cf80ba",
        "amountSaved": 20,
        "name": "20$ off",
        "type": "FixedAmount",
        "trigger": "Code",
        "code": "Snipcart rocks",
        "affectedItems": []
    }],
    "plans": [],
    "total": 439,
    "taxes": [],
    "shippingAddress": {
        "name": "John Doe",
        "company": "Snipcart",
        "address1": "226 rue Saint-Joseph E",
        "address2": "",
        "city": "Quebec",
        "country": "CA",
        "postalCode": "G1K3A9",
        "province": "QC",
        "phone": "418 888 8888",
        "email": "charles.ouellet@gmail.com",
        "shippingSameAsBilling": true
    },
    "shippingInformation": {
        "method": "Livraison",
        "fees": 10
    }
}

start

This method can be used to create a new cart instance. If a cart is already in progress, it will be returned to the promise.

Snipcart.api.cart.start()
    .then(function (cart) {
        console.log (cart);
    });

The promise callback will receive the newly created cart data or will return the current cart information like the get method does if a cart was already in progress.

currency

If no parameters are passed, this method will return the current cart currency.

var currency = Snipcart.api.cart.currency();

When a currency code is passed as a parameter; this method is used to set the current session currency. If a cart is already started in another currency, it will reset when this method is called. You must supply us a ISO4217 currency code.

By default, the currency will be the one defined in the dashboard under the Regional settings menu.

Snipcart.api.cart.currency('cad');

metadata

This method can be used to add some metadata to an order. It can be useful if you need to add any extra data to an order that you will then consume through our API.

We also have some metadata that can be specified and will be used by some parts or our system. For example, you can add paypalCustom to populate the CUSTOM field in PayPal manager when paying an order with PayPal Payments Pro gateway.

Here is a list of metadata that you can specify and that will trigger some behaviors on our side.

Key Value
paypalCustom Used to populate the CUSTOM field with PayPal Payments Pro gateway. This comment will be displayed in PayPal Manager. It must be a string. The maximum number of characters is 256.
Snipcart.api.cart.metadata({
    "paypalCustom": "Custom field",
    "customUserId": "customer@example.com",
    "trackingCode": "UAC-123"
});

metadata returns a promise that you can chain with then.

customField

This method can be used to update order custom fields.

The first parameter of the method is the name of the custom field. If you have a custom field configured like this: data-cart-custom1-name="Slug" then it should be Slug.

The second parameter is the value to set.

Snipcart.api.cart.customField('Slug', 'value');

billingAddress

This method can be used to update or set default billing address.

Snipcart.api.cart.billingAddress({
    "name": "John Doe",
    "email": "geeks@snipcart.com",
    "address1": "226 rue St-Joseph E",
    "address2": "Suite 200",
    "city": "Quebec",
    "province": "QC",
    "country": "CA",
    "company": "Snipcart",
    "postalCode": "G1K3A9"
}).then (function (cart) {
    console.log (cart); // It will contain the cart details with updated values.
});

shippingAddress

This method can be used to update or set default shipping address.

Snipcart.api.cart.shippingAddress({
    "name": "John Doe",
    "address1": "226 rue St-Joseph E",
    "address2": "Suite 200",
    "city": "Quebec",
    "province": "QC",
    "country": "CA",
    "company": "Snipcart",
    "postalCode": "G1K3A9"
}).then (function (cart) {
    console.log (cart); // It will contain the cart details with updated values.
});

items

Snipcart.api.items allows you to retrieve current cart items information and to add items programmatically.

count

This method allows you to retrieve the current cart items count.

var count = Snipcart.api.items.count();

It will return an integer representing the total number of items in the cart.

all

This method allows you to retrieve the list of all items in the cart.

var items = Snipcart.api.items.all();

The method will return an array containing all items in the cart.

[{
    "quantity": 1,
    "stackable": true,
    "customFields": [],
    "id": "1",
    "name": "A poster",
    "description": "An awesome Nicolas Cage's poster",
    "image": "http://placecage.com/50/50",
    "minQuantity": null,
    "maxQuantity": null,
    "duplicatable": false,
    "price": 300,
    "url": "https://snipcart.com",
    "dimensions": {
        "weight": 3000,
        "width": 64,
        "height": 49,
        "length": 16
    },
    "shippable": true,
    "taxable": true,
    "alternatePrices": {
        "vip": 200
    },
    "uniqueId": "fed2b669-1c27-4e90-aa66-50f37c646735",
    "token": "c2aa31c8-b54d-46ac-8b21-2ad12c0d88f4",
    "taxes": [],
    "unitPrice": 300,
    "totalPrice": 300,
    "addedOn": "2016-04-07T19:20:14.6635766Z"
}, {
    "id": "SMARTPHONE",
    "name": "Smartphone",
    "description": "",
    "quantity": 2,
    "stackable": true,
    "customFields": [{
        "name": "Memory size",
        "options": "16GB|32GB[+50.00]",
        "type": "dropdown",
        "value": "",
        "required": false,
        "sanitizedName": "snipcart_custom_Memory-size"
    }],
    "image": "",
    "minQuantity": null,
    "maxQuantity": null,
    "duplicatable": false,
    "price": 399,
    "url": "https://snipcart.com",
    "dimensions": {
        "weight": null,
        "width": null,
        "height": null,
        "length": null
    },
    "shippable": true,
    "taxable": true,
    "alternatePrices": {
        "vip": 299
    },
    "uniqueId": "45b8c65e-a5cb-4197-9f03-51728359c246",
    "token": "c2aa31c8-b54d-46ac-8b21-2ad12c0d88f4",
    "taxes": [],
    "unitPrice": 399,
    "totalPrice": 798,
    "addedOn": "2016-04-07T19:19:59.427Z"
}]

add

This method allows you to add items to the cart. You can either pass an array of items or a single item.

To add a single item, simply pass an object like the following:

Snipcart.api.items.add({
    "id": "SMARTPHONE",
    "name": "Smartphone",
    "description": "",
    "url": "/",
    "price": "399.00",
    "quantity": 2,
    "stackable": true,
    "categories": ["cat1", "cat2", "cat3"],
    "customFields": [{
        "name": "Memory size",
        "options": "16GB|32GB[+50.00]",
        "value": "32GB",
        "required": false
    }],
    "metadata": {
        "key": "value"
    }
});

The method will return a promise. So you can use the then to chain any commands you need when the item has been added.

Snipcart.api.items.add({
    "id": "SMARTPHONE",
    "name": "Smartphone",
    "description": "",
    "url": "/",
    "price": "399.00"
}).then (function (item) { console.log(item) });

You can also pass an array of items to the add method. Each item will be added sequentially.

Snipcart.api.items.add([{
    "id": "SMARTPHONE",
    "name": "Smartphone",
    "description": "",
    "url": "/",
    "price": 399.00,
    "quantity": 2,
    "stackable": true,
    "customFields": [{
        "name": "Memory size",
        "options": "16GB|32GB[+50.00]",
        "value": "32GB",
        "required": false
    }]
}, {
    "id": "BACON",
    "name": "Slice of bacon",
    "description": "",
    "url": "/",
    "price": 19.99,
    "quantity": 1,
    "stackable": true
}]);

If you want to add an item with custom fields and update them afterwards, you must set a custom field id.

Snipcart.api.items.add({
    "id": "BACON",
    "name": "Slice of bacon",
    "url": "/",
    "price": "12.97",
    "quantity": 1,
    "customFields": [{
        "id": "flavor",
        "name": "Flavor",
        "options": "Nature|Mapple",
        "value": "Nature"
    }],
});

To specify the item dimensions, you will need to add the dimensions object on your item:

Snipcart.api.items.add({
    "id": "BACON",
    "name": "Slice of bacon",
    "url": "/",
    "price": "12.97",
    "quantity": 1,
    "dimensions": {
        "weight": 20, // weight in grams, required by our integrated shipping providers
        "width": 100, // width in centimeters, optional
        "height": 40, // height in centimeters, optional
        "length": 150 // length in centimeters, optional
    }
});

If a cart is already in progress, it will be resolved by the promise. You can use then to handle the callback.

You can also set a payment schedule on an item if you want to use our Recurring payments & subscriptions feature. To do so, you'll need to specify a paymentSchedule object.

{
    "paymentSchedule": {
        // interval: Require property that sets the interval of 
        // the recurring payment, it can be: Day, Week, Month or Year.
        "interval": "Day|Week|Month|Year", 
        // intervalCount: Optional property that lets you define the 
        // interval count, for instance, if the interval is 'Month' 
        // and the intervalCount is '2', a payment will 
        // be charged every 2 months. The default is 0.
        "intervalCount": 1,
        // trialPeriodInDays: Optional property that lets you add 
        // a trial period to the subscription. The default is 0.
        "trialPeriodInDays": 10 
    }
}

Code example:

Snipcart.api.items.add({
    "id": "BACON",
    "name": "Slice of bacon",
    "url": "/",
    "price": "12.97",
    "paymentSchedule": {
        "interval": "Month",
        "intervalCount": "2",
        "trialPeriodInDays": 10
    },
    "quantity": 1
});

remove

This method can be used to remove an item from the cart. You will need to pass the item id as parameter. The remove method will also return a promise.

Snipcart.api.items.remove('SMARTPHONE')
    .then(function (item) { console.log(item); });

update

This method can be used to update an item property. Be careful if you change the price or URL to make sure that our crawl back validation still works.

The first parameter is the item ID and the second is an object containing properties to update.

Snipcart.api.items.update('SMARTPHONE', {
    "quantity": 10,
    "description": "10 smartphones",
    "metadata": {
        "key": "value"
    }
}).then(function (item) {
    console.log('Updated item is', item);
});

To update a custom field, use the custom field's id:

Snipcart.api.items.update('BACON', {
    "customFields": [{
        "id": "flavor",
        "value": "Mapple"
    }]
});

clear

This method can be used to clear all items from the current cart. The method returns a promise that will be resolved once all items are removed from the cart. So you can use then to add any code that needs to be executed after clear is completed.

Snipcart.api.items.clear().then(function (removedItems) {
    console.log(removedItems);
});

plans

Plans API has been deprecated, it will still work but we suggest you to update your code to use items API instead.

Snipcart.api.plans lets you interact with plans in the cart.

all

Returns the list of plans in the cart

var plans = Snipcart.api.plans.all();

It will return an array of plan objects:

[
    {
        "id": "Plan ID",
        "name": "Plan name",
        "url": "/",
        "amount": 20,
        "interval": "Month",
        "intervalCount": 1
    },
    ...
]

add

Add a plan to the cart.

Snipcart.api.plans.add({
    id: 'PlandId',
    name: 'Plan name'
    amount: 20,
    interval: 'Month', // Enum: Day|Week|Month|Year
    intervalCount: 2,
    url: '/'
}).then(function(plan) {
    console.log('My new plan is', plan);
});

remove

Removes a plan from the cart.

Snipcart.api.plans.remove('PlanId').then(function (plan) {
    console.log('This plan has been removed', plan);
});

clear

Removes all plans from the cart.

Snipcart.api.plans.clear().then(function() {
    console.log('All plans have been removed');
});

discounts

Snipcart.api.discounts lets you interact with discounts in cart. For example, you can apply a new discount with the API.

all

Returns all discounts currently in the cart. Can be useful to retrieve a discount ID.

var discounts = Snipcart.api.discounts.all();

applyDiscountCode

Add a discount code to the cart. Please note that only discounts triggered by a code can be added with this method.

Snipcart.api.discounts.applyDiscountCode('CODE')
    .then(function (appliedCode) {
        console.log(code);
    })
    .fail(function (error) {
        console.log("Something went wrong when adding the discount code, are you sure it's a valid code?", error);
    });

remove

Removes a discount, you need to specify the cart discount unique ID as the only parameter of this method.

Snipcart.api.discounts.remove('f8cd1613-a9b6-4885-814f-ed49bb5b5407')
    .then(function (discount) {
        console.log('The discount has been removed', discount);
    })
    .fail(function (error) {
        console.log('Something went wrong when removing the discount', discount);
    });

modal

Snipcart.api.modal lets you interact with the current Snipcart popup.

show

This method will open the cart if it is closed.

Snipcart.api.modal.show();

close

This method will close the cart if it is opened.

Snipcart.api.modal.close();

user

Snipcart.api.user lets you interact with the current logged-in user.

current

The current method will return the connected user, if there is none, null will be returned.

var user = Snipcart.api.user.current();

logout

This method will logout the current connected user.

Snipcart.api.user.logout();

products

Snipcart.api.products allow you to interact with some products-related information. At the moment it can be used to alter product metadata from your website. This API will only be available on domains that are whitelabeled in our dashboard. It will also work if you are on localhost. However, if you try to use those methods on a domain that is not part of the allowed ones the requests will be rejected.

metadata

This method allows you to retrieve or update metadata for a specific product. The first parameter is the product id. The product must have been added to a cart at least one time to be available.

You can retrieve metadata for a particular product by passing only the id as parameter. Please note that you must use the id that you specified with data-item-id attribute.

Snipcart.api.products.metadata("productId").then(function (metadata) {
  console.log(metadata);
});

You can also update metadata information by passing a second parameter. It must be a JSON object.

Snipcart.api.products.metadata("productId", {
  "meta": "data",
  "valid": "true"
}).then (function (metadata) {
    console.log(metadata);
});

Was this article helpful?