Automatic discount on products when adding them to cart

Automatic discount on products when adding them to cart

TrendBlend
Trailblazer
355 0 37

Hello I got this logic for adding products to cart, but when adding them I want to change the price of the products because I'm trying to create like a volume bundle offer. URL: Glow Curtain: 400 LED Lights for a Magical Ambiance – InteriorGlows. I tried doing cart_level_discount_applications: [
{
type: 'percentage',
amount: 1349, // This is the discount amount (for example, 10% of the product price)
description: '10PERCENT Applied', // Description of the discount
}
] in the body, but that did not apply an extra discount. Does anyone know how I can do this?

function addProductsToCart() {
  console.log("triggered");

  const productsToAdd = [];
  // Select the currently selected row

  const selectedRow = document.querySelector('.volume-bundle__row.selected');
if (!selectedRow) {
  console.error("No selected row found.");
  return;
}

selectedRow.querySelectorAll('[data-variant-picker]').forEach(pickerContainer => {
  const pickers = pickerContainer.querySelectorAll('.variant-selector');
  const selectedValues = Array.from(pickers).map(picker => picker.value);

  console.log("Selected Values:", selectedValues);

  const variantId = getVariantIdFromSelectedValues(selectedValues, product);
  if (variantId) {
    productsToAdd.push({ id: variantId, quantity: 1 });
  }
});


if (productsToAdd.length) {
  console.log("Try to add");
  
//setTimeout(() => {
  fetch('/cart/add.js', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ 
      items: productsToAdd,
      
      /*cart_level_discount_applications: [
      {
        type: 'percentage',
        amount: 1349, // This is the discount amount (for example, 10% of the product price)
        description: '10PERCENT Applied', // Description of the discount
      }
    ]*/
      
    }),
  })
  .then(response => {
    if (!response.ok) {
      throw new Error("Failed to add products to cart");
    }
    return response.json();
  })
  .then(data => {
    console.log("Products added to cart:", data);
  })
  .catch(error => {
    console.error("Error:", error);
  });
//}, 100); // Add a short delay (e.g., 100ms)

} else {
  console.error("No valid products to add.");
}
  
}

 

 

Replies 4 (4)

tobebuilds
Shopify Partner
582 42 157

Hi TrendBlend,

 

You can't use the AJAX Cart API to apply discounts to individual line items. Secondly, `cart.cart_level_discount_applications` is a Liquid variable. It's not one of the accepted arguments for `add.js`.

 

While you can definitely use the AJAX API to add products to the cart, you'll need to create the discount separately. You can either use Shopify's built-in automatic discounts (your use case sounds simple enough for built-in discounts to cover it), or an app, such as ours, Regios Discounts (4.8 stars, 77 reviews, Built for Shopify), if your needs are more complex.

 

If you have any questions about the latter option, let me know.

 

Hope this helps,

Tobe

Founder, Regios Discounts app (4.8 stars, 91 reviews, Built for Shopify)
- Custom discounts made simple
- "Just about any discount you'll ever need"
- Built by an ex-Google software engineer
- Often imitated, never duplicated
TrendBlend
Trailblazer
355 0 37

But wouldn’t it be quite easy to achieve using code?

tobebuilds
Shopify Partner
582 42 157

Here is the AJAX Cart API reference:

 

https://shopify.dev/docs/api/ajax/reference/cart

 

As you can see, there's no mention of apply discounts there. The discounting system in Shopify is separate from the AJAX Cart API.

 

In theory, it could be easy to do this with code, but it's not possible to apply discounts through the Cart API. As mentioned in my previous comment, you might be able to create a discount that meets your needs using just Shopify's built-in discounts.

Founder, Regios Discounts app (4.8 stars, 91 reviews, Built for Shopify)
- Custom discounts made simple
- "Just about any discount you'll ever need"
- Built by an ex-Google software engineer
- Often imitated, never duplicated

Ellie-BOGOS
Shopify Partner
418 34 64

Hi @TrendBlend 😊

 

I am Ellie from BOGOS: Free gifts, Discounts & Bundles. I will recommend you use a third party app like BOGOS, which can help you set things up no-code and less than 5 minutes! Here is how it may look on your store.

 

EllieBOGOS_0-1736925942625.png

 

 

To create your volume discount bundle, add multiple tiers in the discount (e.g., buy 2, 3, or 4 curtains). Then for each tier, specify the quantity required and the discount amount (percentage or fixed amount). The app also allows you to style the colors, texts and layouts of the widget so it matches your branding

 

EllieBOGOS_1-1736926133173.png

 

What is more, besides from volume discount bundle, you can have other types of sales promotion all in one app, such as free gifts, BOGO, mix and match bundle, product bundle and so on.

 

Install BOGOS here to try on your end! (4.9 overall rating, 2,400 reviews)

If my post is helpful, let me know by giving a Like or Accept solution.
Use BOGOS to create powerful promotions on your Shopify stores: free gifts, discounts, bundles, upsells!
Have a nice day ^^