Search code examples
snipcart

Snipcart add item via JS API


I'm building a very small e-commerce website for selling customizable jewels, so I have a graphical configurator that lets you design the jewel and then you can add it to the cart. The product should have a custom field in JSON format that contains the item configuration. I see that Snipcart has data-item-custom{x} fields, but is populated only with dropdowns... is not suitable for me.

Do you think I can handle this situation with Snipcart? Can I simply update via JS the HTML data-item- fields content? Or add the item to the cart via JS?

addToCart({
 name: 'Bracelet 1',
 customField1: 'JSON HERE'
})

Solution

  • There's a Javascript API available for Snipcart.

    It does allow to add product dynamically, however, the syntax for custom fields is slightly different. The example from the doc for Snipcart.api.items.add show how to use custom fields (removed unused fields for brevity):

    Snipcart.api.items.add({
        "id": "SMARTPHONE",
        "name": "Smartphone",
        "url": "/",
        "price": "399.00",
        "customFields": [{
            "name": "Memory size",
            "options": "16GB|32GB[+50.00]",
            "value": "32GB"
        }]
    });
    

    So instead of the flattened version with customFieldX, you can pass an array to customFields. The dropdown format is only used if you pass an options. For your use case this would become:

    Snipcart.api.items.add({
        "id": "SMARTPHONE",
        "name": "Smartphone",
        "url": "/",
        "price": "399.00",
        "customFields": [{
            "name": "configuration",
            "value": "{\"option1\":\"value1\"}" //...
        }]
    });
    

    However, custom fields are shown to the customer which would not be ideal to show them the raw json data. To pass hidden data you can instead use metadata which already expect a JSON object:

    Snipcart.api.items.add({
        "id": "SMARTPHONE",
        "name": "Smartphone",
        "url": "/",
        "price": "399.00",
        "customFields": [{
        "metadata": {
            "configuration": "configuration data"
        }
    });