We're moving the community! Starting July 7, the current community will be read-only for approx. 2 weeks. You can browse content, but posting will be temporarily unavailable. Learn more

Get cart total value in Shopify Custom Pixel product_added_to_cart Event

Get cart total value in Shopify Custom Pixel product_added_to_cart Event

shopmonster
Shopify Partner
1 0 0

Hi! Im currently working on implementing some tracking pixel with the new Web Pixels API.

 

When the product_added_to_cart (as well as removed) event is called I need to get the new total cart value.

 

How can I do this?

 

Thank you!

Replies 2 (2)

Small_Task_Help
Shopify Partner
1144 55 112

Hi,

 

It can be done by setting up custom event listeners and making requests to the /cart.js endpoint whenever a product is added or removed from the cart.

 

Use the total_price property from the fetched cart data to get the total value and incorporate it into your tracking pixels as needed.

 

Define the Event Listener and Fetch Cart Data code example

// Define your pixel script
(() => {
  // Listen for `product_added_to_cart` event
  Shopify.CustomerEvents.subscribe('product_added_to_cart', async (event) => {
    console.log("Product added to cart:", event);
    // Fetch cart details
    const cart = await getCartDetails();
    console.log("Updated Cart Total:", cart.total_price / 100); // Cart total in dollars
  });

  // Listen for `product_removed_from_cart` event
  Shopify.CustomerEvents.subscribe('product_removed_from_cart', async (event) => {
    console.log("Product removed from cart:", event);
    // Fetch cart details
    const cart = await getCartDetails();
    console.log("Updated Cart Total:", cart.total_price / 100); // Cart total in dollars
  });

  // Function to fetch cart details
  async function getCartDetails() {
    try {
      const response = await fetch('/cart.js'); // Shopify's default cart endpoint
      const cart = await response.json();
      return cart;
    } catch (error) {
      console.error("Error fetching cart details:", error);
    }
  }
})();
To Get Shopify Experts Help, Click Here or E-mail - hi@ecommercesmalltask.com
About Us - We are Shopify Developers India
At Google My Business - Ecommerce Small Task - Hire Shopify Developers Ahmedabad
Webstollen
Shopify Partner
9 1 0

Hi, im doing the same, except i use

"analytics.subscribe('product_added_to_cart', async (event) =>..." cause i use the remix shopify app template , which i think should be fine? and my app is running in development.

i keep getting the error saying "requests are not allowed from the same origin", do you happen to know how to fix it?