Cannot add product to the cart

Hi,

first a desclaimer - I’m a newby… :slight_smile:

I have only one product on my site that is customizable and the options affect the price. I created a set of 3 dropdowns with the various options.
The price calculation works well. However, when clicking the “add to cart” button, it redirects to the car page but the cart remains empty. there is no error in the console.
I see in the console that the options are collected correctly, but when I call the contents of the cart, the cart is empty.

I tried with another product that doesn’t have variables - nothing worked. I also found here a piece of code for a cart icon, that I tried to use separately from the button, to add a simple products (no variants) to the cart, and the cart consistently remains empty.

I’m using wix editor with velo.

This is my code:

// Velo API Reference: https://www.wix.com/velo/reference/api-overview/introduction

// Import Wix Store module for cart functionality
import { cart } from 'wix-stores';
import wixLocation from 'wix-location';

$w.onReady(function () {

  // default values
  $w("#lengthDropdown").value = "12"
  $w("#destinationDropdown").value = "DE"
  $w("#shippingDropdown").value = "monthly"

  // Initial price calculation
  calculatePrice();

     // set the price display
    // $w("#priceText").text = "96 €";

    $w("#destinationDropdown, #shippingDropdown, #lengthDropdown").onChange(() => {
          calculatePrice();
    });

    // Handle add to cart button click
    $w("#addToCartButton").onClick(() => {
        addToCart();
    });

});

/*********/
//cart icon - test with another product with no options

$w('#shoppingCartIcon1').addToCart("44551edc-f032-a489-5a78-fe403973bdcd", 1) 
.then( () => {     console.log("Product added"); } ) 
.catch( (error) => {     console.log(error); } );


/*********/


// Function to calculate and update the price
function calculatePrice() {

    let basePrice = 8; // Example base price
    let totalPrice = basePrice;

    let length = $w("#lengthDropdown").value;
    let destination = $w("#destinationDropdown").value;
    let shipping = $w("#shippingDropdown").value;
    
    // Adjust based on length
    switch(length) {
      case "1":
        totalPrice = (totalPrice * 1);
        break;
      case "6":
        totalPrice = (totalPrice * 6);
        break;
      case "12":
        totalPrice = (totalPrice * 12);
        break;
      case "24":
        totalPrice = (totalPrice * 24);
        break;
    }
    
    switch(destination) {
        case "DE":
          totalPrice += 0;
          break;
        case "EU":
        totalPrice += 2;
          break;
        case "ROW":
        totalPrice += 5;
          break;
      }    

    switch(shipping) {
        case "monthly":
          totalPrice += 0;
          break;
        case "first":
        totalPrice += 5;
          break;
        case "all":
        totalPrice += 5;
          break;
      }


    // Update the price display
    $w("#priceText").text = `${totalPrice.toFixed(2)} €`;

}

// Function to add selected product to cart
function addToCart() {
    let productId = "fc8f503e-fe0b-5dc5-773d-efa87fcf4008";
    let totalPrice = parseFloat($w("#priceText").text.replace('€', ''));

    // Get selected options
    let length = $w("#lengthDropdown").value;
    let destination = $w("#destinationDropdown").value;
    let shipping = $w("#shippingDropdown").value;

    // Define custom options
    let options = [
        {
            "optionName": "Length",  
            "selection": length
        },
        {
            "optionName": "Destination",  
            "selection": destination
        },
        {
            "optionName": "Shipping",  
            "selection": shipping
        }
    ];

    //print to the console
    console.log("Product ID: ", productId);
    console.log("Total Price: ", totalPrice);
    console.log("Options: ", options);
    console.log("Constructed Options: ", JSON.stringify(options, null, 2));

    // Add the item to the cart
    cart.addProducts([{
        //"_id": "b9d01463-ac47-4a19-a390-9a817ad6af5a", //cart id
        "productId" : productId, 
        "quantity": 1,
        
        "customTextFields": [
            {
                "title": "Total Price",
                "value": `${totalPrice.toFixed(2)} €`
            }
        ],
        "options": options
    }])
    .then(() => {
        // Check current cart state
        return cart.getCurrentCart();
    }) 
    .then((currentCart) => {
        console.log("Current cart contents: ", currentCart);
        console.log("Product added to cart");
        wixLocation.to("/cart-page");  
    })
    .catch((error) => {
        console.error("Error adding to cart: ", JSON.stringify(error, null, 2));
        if (error.response) {
            console.error("Response from server: ", error.response);
        }
    });
}


When I add the product directly from the product page to the cart, it works, but the price is not calculated.

I appreciate your help!

  1. Check Product ID: Ensure the productId is correct and matches the product in your Wix Store.

  2. Verify Option Names: Make sure the option names in the options array (“Length”, “Destination”, “Shipping”) exactly match those defined in your product settings.

  3. Simplify addToCart: Temporarily remove options and custom fields to see if the product adds to the cart:

    function addToCart() {
        let productId = "fc8f503e-fe0b-5dc5-773d-efa87fcf4008";
        cart.addProducts([{ "productId": productId, "quantity": 1 }])
        .then(() => cart.getCurrentCart())
        .then(currentCart => {
            console.log("Current cart contents: ", currentCart);
            wixLocation.to("/cart-page");  
        })
        .catch(error => console.error("Error adding to cart: ", error));
    }
    
  4. Debugging Logs: Check the console for the output of your log statements to ensure expected values.

  5. Test with Another Product: Ensure the other product is published and properly configured.

  6. Support: If issues persist, consider contacting Wix Support or an expert for assistance.

These steps should help you identify and resolve the issue with the cart not populating. Let me know if you have further questions or need help!

Many thanks for your message Muhammad. Unfortunately, non of this worked. the productid and the option names are correct, the simplified add to cart also didn’t add anything to the cart. the only way I can add the product to the cart is from the built-in product page, but hten the price is not calculated properly.

I checked the network logs, and it is very clear to see (even for a newby like me :smiley: ) that the POST query does not include the product at all (compared to the POST query from the product page, that transfers the correct parameters).

from the default product page:

{
  "cart": {
    "addToCart": {
      "errors": [],
      "cart": {
        "cartId": "b9d01463-ac47-4a19-a390-9a817ad6af5a",
        "checkoutId": null,
        "ecomId": "c00b5ed7-681b-493b-936c-653115ed112d",
        "storeId": "4fc3fd5a-a4e6-4666-b8b6-2d4f14c5d58b",
        "buyerNote": null,
        "items": [
          {
            "cartItemId": 1,
            "catalogAppId": "215238eb-22a5-4c36-9e7b-e7c08025e04e",
            "product": {
              "id": "fc8f503e-fe0b-5dc5-773d-efa87fcf4008",
              "productType": "physical",
              "urlPart": "dein-gewählter-plan",
              "pageUrl": "https://efratyahav2.wixsite.com/iggy-reist/product-page/dein-gew%C3%A4hlter-plan",
              "weight": 0,
              "name": "DeinPlan",
              "price": 8,
              "comparePrice": 0,
              "customTextFields": [],
              "media": [],
              "digitalProductFileItems": []
            },
            "optionsSelectionsValues": [
              {
                "id": 0,
                "title": "Length",
                "value": "1"
              },
              {
                "id": 1,
                "title": "Destination",
                "value": "DE"
              },
              {
                "id": 2,
                "title": "Shipping",
                "value": "first"
              }
            ],
            "freeText": [],
            "sku": "",
            "quantity": 1,
            "inventoryQuantity": null,
            "convertedPrices": {
              "formattedComparePrice": "",
              "formattedPrice": "8,00 €",
              "formattedTotalPrice": "8,00 €",
              "totalPrice": 8,
              "formattedPriceBeforeDiscount": "",
              "price": 8,
              "depositAmount": 0,
              "formattedDepositAmount": null
            },
            "formattedPriceBeforeDiscount": null,
            "discountRules": [],
            "formattedDepositAmount": null,
            "depositAmount": 0,
            "renderingConfig": {
              "hidePrice": false,
              "hideQuantity": false
            },
            "paymentType": "FULL_PAYMENT_ONLINE",
            "selectedMembership": null,
            "savePaymentMethod": false
          }
        ],
        "appliedCoupon": null,
        "currencyFormat": {
          "code": "EUR"
        },
        "convertedCurrencyFormat": {
          "code": "EUR"
        },
        "additionalFees": [],
        "totals": {
          "subTotal": 8,
          "total": 8,
          "shipping": 0,
          "discount": 0,
          "itemsTotal": 8,
          "tax": 0,
          "formattedSubTotal": "8,00 €",
          "formattedShipping": "0,00 €",
          "additionalFeesTotal": 0,
          "formattedItemsTotal": "8,00 €",
          "formattedDiscount": "0,00 €",
          "formattedTax": "0,00 €",
          "formattedTotal": "8,00 €",
          "formattedAdditionalFeesTotal": "0,00 €",
          "formattedPayNow": "8,00 €",
          "formattedPayLater": "0,00 €",
          "payNow": 8,
          "payLater": 0
        },
        "convertedTotals": {
          "subTotal": 8,
          "total": 8,
          "discount": 0,
          "shipping": 0,
          "itemsTotal": 8,
          "tax": 0,
          "formattedSubTotal": "8,00 €",
          "formattedShipping": "0,00 €",
          "formattedDiscount": "0,00 €",
          "formattedTax": "0,00 €",
          "formattedTotal": "8,00 €",
          "formattedItemsTotal": "8,00 €",
          "formattedPayNow": "8,00 €",
          "formattedPayLater": "0,00 €",
          "formattedAdditionalFeesTotal": "0,00 €",
          "payNow": 8,
          "payLater": 0,
          "additionalFeesTotal": 0
        },
        "destination": {
          "country": "EGY",
          "subdivision": null,
          "zipCode": null,
          "countryName": "Ägypten",
          "subdivisionName": null
        },
        "selectedShippingOption": {
          "id": "00000000-0000-0000-0000-000000000001"
        },
        "destinationCompleteness": [],
        "shippingRuleInfo": {
          "status": "OK",
          "canShipToDestination": true,
          "shippingRule": {
            "id": "00000000-0000-0000-0000-000000000002",
            "options": [
              {
                "id": "00000000-0000-0000-0000-000000000001",
                "title": "Kostenloser Versand",
                "rate": 0,
                "formattedRate": "0,00 €",
                "deliveryTime": "",
                "pickupInfo": null,
                "deliveryTimeSlot": null
              }
            ]
          }
        },
        "purchaseFlowId": "f8a3dce0-359e-4fdd-9102-aa5c53c750f2",
        "minimumOrderAmount": {
          "reached": true,
          "diff": 0,
          "value": 0,
          "convertedDiff": 0,
          "convertedValue": 0,
          "formattedConvertedDiff": "",
          "formattedConvertedValue": ""
        },
        "violations": []
      }
    }
  }
}

from the custom page:

{
  "cart": {
    "addToCart": {
      "errors": [],
      "cart": {
        "cartId": "b9d01463-ac47-4a19-a390-9a817ad6af5a",
        "checkoutId": null,
        "ecomId": "c00b5ed7-681b-493b-936c-653115ed112d",
        "storeId": "4fc3fd5a-a4e6-4666-b8b6-2d4f14c5d58b",
        "buyerNote": null,
        "items": [],
        "appliedCoupon": null,
        "currencyFormat": {
          "code": "EUR"
        },
        "convertedCurrencyFormat": {
          "code": "EUR"
        },
        "additionalFees": [],
        "totals": {
          "subTotal": 0,
          "total": 0,
          "shipping": 0,
          "discount": 0,
          "itemsTotal": 0,
          "tax": 0,
          "formattedSubTotal": "0,00 €",
          "formattedShipping": "0,00 €",
          "additionalFeesTotal": 0,
          "formattedItemsTotal": "0,00 €",
          "formattedDiscount": "0,00 €",
          "formattedTax": "0,00 €",
          "formattedTotal": "0,00 €",
          "formattedAdditionalFeesTotal": "0,00 €",
          "formattedPayNow": "0,00 €",
          "formattedPayLater": "0,00 €",
          "payNow": 0,
          "payLater": 0
        },
        "convertedTotals": {
          "subTotal": 0,
          "total": 0,
          "discount": 0,
          "shipping": 0,
          "itemsTotal": 0,
          "tax": 0,
          "formattedSubTotal": "0,00 €",
          "formattedShipping": "0,00 €",
          "formattedDiscount": "0,00 €",
          "formattedTax": "0,00 €",
          "formattedTotal": "0,00 €",
          "formattedItemsTotal": "0,00 €",
          "formattedPayNow": "0,00 €",
          "formattedPayLater": "0,00 €",
          "formattedAdditionalFeesTotal": "0,00 €",
          "payNow": 0,
          "payLater": 0,
          "additionalFeesTotal": 0
        },
        "destination": {
          "country": "EGY",
          "subdivision": null,
          "zipCode": null,
          "countryName": "Ägypten",
          "subdivisionName": null
        },
        "selectedShippingOption": null,
        "destinationCompleteness": [],
        "shippingRuleInfo": null,
        "purchaseFlowId": "f8a3dce0-359e-4fdd-9102-aa5c53c750f2",
        "minimumOrderAmount": {
          "reached": true,
          "diff": 0,
          "value": 0,
          "convertedDiff": 0,
          "convertedValue": 0,
          "formattedConvertedDiff": "",
          "formattedConvertedValue": ""
        },
        "violations": []
      }
    }
  }
}

I will try to contact support. Thank you again for your advise!

Hi, need your help on the same topic again (trying to add a custom product to the cart). I tried 3 different variations of code, and each time I managed to get to the same situation: there are no errors, I get the confirmation htat the product was added to the cart - but the cart remains empty.
A thought occured to me - could it be because (for now) I am still using the free version of wix? I still didn’t purchase a plan because there are still many things to work on.
Could it be the reason?

Thanks for any help I can get!

Hi @Efrat_Yahav!
I’m pretty sure I’m getting a similar behaviour - I’m using a slightly different API (using the backend function method, like here), but still I thought it might be related.
Did you make any progress on this? Would really appreciate any knowledge you’ve gathered… (BTW I’m also still on the free version, though I’d expect that to only be an issue for actual payments, not adding to cart).

Hi! unfortunately, I couldn’t solve it. I did pay for a package eventually, so it cannot be related to the free version. I tried with various methods, inclusing add_to_current_cart. nothing worked. In the logs I could see the correct data, but the cart remained empty, no matter what I did.
I tried Wix support and they were not very helpful. Eventually I used the built in wix products.
If you find a solution, I’d be very happy to hear what you did!
Good luck!

This is exactly what I’m seeing, and I’ve also purchased a subscription - just to validate that’s not the issue…
It’s almost like there’s not connection between what the API returns for all the currentCart calls and what actually gets shown on the site itself.
Did you just manage without this functionality? I really can’t… may need to go for the money back guarantee and look for a better solution if I can’t work around this…

Yes, I could change the concept a bit and use the built in products. Not ideal for user experience, but it works for me. I’m not an experienced developer and at some point it just got too much. Sorry that I can’t help…! Must admit that it comforts me to know it’s not just me :rofl:

1 Like

Hi, I have the same issue, unfortunately I noticed that in order to design your own product page with an add to cart button you have to pay for premium, like you said it should only be when it comes to payments but you should be able to design your own products page :frowning: they should fix this