Issue with Cart API Implementation - Products Not Being Added to Cart
I am writing to report an issue I'm experiencing with the Cart API implementation. I have tried multiple approaches to add products to a customer's cart programmatically, but I'm encountering difficulties.
API Request Approach
Headers:
- Cookie: 2-9e3fd03229afdb64895d0b07bce24969d3b7abbd417ae3d075cb4f68d5856f107200da65b0a26079343686901f2d60c0
- domain-name: tiendasalud.synapsis.holdings
Request Body:
- {
- "product_variant_id": "4509902000001524005",
- "quantity": 5
- }
While the API returns a success message with the product details, the products are not actually being added to the cart when I check the cart page (/cart
).
HTML Components Approach
I have also attempted to implement this using the HTML components and JavaScript in my Commerce headers code:
- <script>
- function LocalStorage_CartItems() {
- const cartDetails = "4509902000003924347/4&4509902000003924345/2"
- if (cartDetails) {
- const products = cartDetails.split("&");
-
- products.forEach((product) => {
- const [productId, quantity] = product.split("/");
- for (let i = 0; i < quantity; i++) {
- addProductToCart(productId);
- }
- });
- }
- }
- function addProductToCart(productId) {
- const addToCartBtn = document.querySelector(
- `[data-zs-add-to-cart][data-zs-product-variant-id="${productId}"]`
- );
-
- if (addToCartBtn) {
- addToCartBtn.click();
- }
- }
- </script>
The format "4509902000003924347/4&4509902000003924345/2" represents:
- The product ID (first set of numbers).
- The quantity separated by a slash (/).
- Multiple products separated by an ampersand (&).
But the problem is that the addToCartBtn returns null, so I think I'm trying to access to a component that doesn't exists in the /cart page.
Questions:
- Is there a recommended way to programmatically add products to a customer's cart?
- Are there any additional headers or authentication requirements for the Cart API that I might be missing?
- Could you provide an example of a successful implementation?
I would greatly appreciate any guidance on resolving this issue. Our goal is to implement a solution that allows us to programmatically add products to our customers' carts when they scan a QR code, using the Local Storage to save the string with the ID and quantity product.