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!

Reply 1 (1)

Small_Task_Help
Shopify Partner
807 26 71

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, E-mail - hi@ecommercesmalltask.com
About Us - We are Shopify Expert Agency
At Google My Business - Ecommerce Small Task - Hire Shopify Developers Ahmedabad