How to manipulate cart in an app using external inventory?

How to manipulate cart in an app using external inventory?

GregL
Shopify Partner
3 0 0

Hi Everyone,

i am trying to develop an app which will use a kind of external inventory.
I created an app-theme-extension and created a block to check if a unit of the product exists in my inventory and if yes, i will add it to the cart and proceed to the purchase. See the code of my block below. 

My code is not working and i got the error : Uncaught (in promise) ReferenceError: cart is not defined
isn't it possible to use cart as an object ? 

Do you think this is the best approach ? 

<script>
// This script will check if the product is in stock in the external inventory system.
// If it is, it will add the product to the Shopify basket.
async function checkInventory() {
// Get the product ID from the Shopify product.
console.log("Product id:",{{product.id}});
const productId = {{product.id}};

// Make a request to the external inventory system to check the inventory for the product.
const response = await fetch('https://example.com/api/inventory/check/' + productId);

// Check the response status code.
if (response.status === 200) {
// The product is in stock. Add the product to the Shopify basket.
cart.items.push({
product_id: {{ product.id }},
quantity: 1
});
 
} else {
// The product is not in stock. Show an alert message to the customer.
alert('The product is not in stock.');
}
}
</script>
<button
typ="button"
class="shopify-payment-button__button"
style="background-color:{{ block.settings.background-color }};color:{{ block.settings.color }}"
onclick="checkInventory()"
>
{{ 'myapp.addToBasketButton.label' | t }}
</button>

{% schema %}
{
"name": "My app Product",
"target": "section",
"settings": [
{ "type": "product", "id": "product", "label": "product", "autofill": true },
{ "type": "color", "id": "color", "label": "Button Color", "default": "#FFFFFF" },
{ "type": "color", "id": "background-color", "label": "Button background Color", "default": "#168F30" }
]
}
{% endschema %}
Replies 0 (0)