2021-08-28

JavaScript, Google Tags, and Stripe Checkout - How to insert the value from stripe checkout into a gtag?

I am a JavaScript newbie but have general programming experience. I've been able to successfully hack together a website that accepts stripe checkout using Netlify Serverless functions (similar to AWS Lambda). The final step is to include Google Ads to track conversions.

For google ads conversion tracking, the event snippet on the success.html page is something like:

<!-- Event snippet for Subscribe conversion page -->
<script>
  gtag('event', 'conversion', {
      'send_to': 'AW-6543546/4_DFSJKHJFKEHESH',
      'value': 1.0,
      'currency': 'USD'
  });
</script>

In the above code, 'value': should be set to the checkout price from the successfully completed stripe checkout. There are two relevant files making all of this work:

  1. /success?session_id={CHECKOUT_SESSION_ID}= - redirected to this page after completing a purchase
<html>
<head>

  <script async src="https://www.googletagmanager.com/gtag/js?id=AW-6543546"></script>
  <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());

    gtag('config', 'AW-6543546');
  </script>
  <!-- Event snippet for Subscribe conversion page -->
  <script>
    gtag('event', 'conversion', {
        'send_to': 'AW-6543546/4_DFSJKHJFKEHESH',
        'value': 1.0,
        'currency': 'USD'
    });
  </script>

</head>

<body>
  <div class="css">
     <session_email></session_email>
  </div>
</body>

<footer>
</footer>

<script src="https://js.stripe.com/v3"></script>
  <script>
    var urlParams = new URLSearchParams(window.location.search);
    var sessionId = urlParams.get('session_id');
    
    if (sessionId) {
      const data = {
        sessionId: sessionId,
      };

      async function loadSuccess() {   

      const response = await fetch('/.netlify/functions/success', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      }).then((res) => res.json());

      console.log(response.session.amount_total/100);
      document.querySelector('session_email').textContent = response.session.customer_details.email;
      }

      loadSuccess();
    } 
  </script>

</html>
  1. success.js (for retrieving the transaction details of a successful stripe checkout payment)
const stripe = require('stripe')(process.env.TEST_STRIPE_SECRET_KEY);

exports.handler = async (event) => {

  const { sessionId } = JSON.parse(event.body);
  
  const session = await stripe.checkout.sessions.retrieve(sessionId);
  // const customer = await stripe.customers.retrieve(session.customer);
  console.log(session);

  return {
    statusCode: 200,
    body: JSON.stringify({
      session: session,
    }),
  };
};

The loadSuccess() function returns json for the entire transaction, and response.session.amount_total/100 is the value that I need to insert into the google conversion tag.

In the google tag, I tried 'value': response.session.amount_total/100 but in the resulting html, it sets the string value to response.session.amount_total/100, instead of actually calculating what response.session.amount_total/100 is equal to.

I think it is because the google tag is loading before the function that retrieves response.session.amount_total. Or the google tag isn't able to get the values from response.session.amount_total from the other function at all. Chrome debugging says Uncaught ReferenceError: response is not defined

I tried changing the location from footer to header for the entire script that gets the amount, but no luck. Any other ideas?

EDIT: From https://medium.com/geekculture/how-to-measure-purchases-with-gtag-js-from-iframe-309932c19b6 it looks like an event listener can be added to the gtag script that will dynamically set the "value" parameter. From the website's example:

<script>
  window.addEventListener("message", (event) => {
    if (event.data && event.data.event === "purchase") {
      var data = event.data;
      dataLayer.push({ ecommerce: null });
      gtag('event', 'purchase', {
        "transaction_id": data.data.transaction_id,
        "value": data.data.value,
        "currency": "EUR",
        "coupon": data.data.coupon,
        "items":data.data.items
      });
    }
  });
</script>

Can this example be applied to my own case, or is there an easier way? Can anyone please help me with how it would be coded?



from Recent Questions - Stack Overflow https://ift.tt/38hdst5
https://ift.tt/eA8V8J

No comments:

Post a Comment