#172 - Capture Stripe Checkout Session v0.1

Track Memberstack Stripe checkouts and sends member + transaction data to your webhook.

View demo

<!-- 💙 MEMBERSCRIPT #172 v0.1 💙 - CAPTURE STRIPE CHECKOUT SESSION -->
<script>
(function() {
  'use strict';

  // Configuration object for webhook URL and debugging options
  const CONFIG = {
    WEBHOOK_URL: 'https://hook.eu2.make.com/ld2ovhwaw6fo9ufvq20lfcocmsjhr6zc', // REPLACE THIS WITH YOUR WEBHOOK URL
    TRACK_FAILURES: true,
    DEBUG: true
  };

  // Event listener to execute code once the DOM content is fully loaded
  document.addEventListener('DOMContentLoaded', async () => {
    if (CONFIG.DEBUG) console.log('Webhook-only checkout tracker initialized');

    // Fetch current member data from Memberstack
    const member = await getCurrentMember();

    // Check if the checkout was successful
    if (isCheckoutSuccess()) {
      onCheckoutSuccess(member);
    } else {
      onCheckoutFailure(member);
    }
  });

  // Function to retrieve current member data from Memberstack
  async function getCurrentMember() {
    try {
      const { data } = await window.$memberstackDom.getCurrentMember();
      if (!data) return {};
      const fn = data.customFields?.['first-name'] || data.customFields?.['first_name'] || '';
      return {
        ms_member_id: data.id || '',
        ms_email: data.auth?.email || '',
        ms_first_name: fn
      };
    } catch (e) {
      if (CONFIG.DEBUG) console.warn('Memberstack fetch error', e);
      return {};
    }
  }

  // Function to determine if the checkout was successful based on URL parameters
  function isCheckoutSuccess() {
    const p = new URLSearchParams(window.location.search);
    return p.get('fromCheckout') === 'true' && (p.has('msPriceId') || p.has('stripePriceId'));
  }

  // Function to handle successful checkout
  function onCheckoutSuccess(member) {
    if (CONFIG.DEBUG) console.log('Checkout success detected');
    const data = extractUrlData();
    sendToWebhook({ ...data, ...member }, 'checkout_success');
    setTimeout(cleanUrl, 2000);
  }

  // Function to generate or retrieve GA4 client ID
  function getGA4ClientId() {
    // Try to get existing client ID from localStorage
    let clientId = localStorage.getItem('ga4_client_id');
    
    if (!clientId) {
      // Generate new client ID if none exists
      clientId = 'GA1.1.' + Math.random().toString(36).substring(2, 15) + '.' + Date.now();
      localStorage.setItem('ga4_client_id', clientId);
    }
    
    return clientId;
  }

  // Function to extract relevant data from the URL query parameters
  function extractUrlData() {
    const p = new URLSearchParams(window.location.search);
    return {
      fromCheckout: p.get('fromCheckout'),
      msPriceId: p.get('msPriceId'),
      stripePriceId: p.get('stripePriceId'),
      planId: p.get('planId'),
      memberId: p.get('memberId'),
      transactionId: `ms_checkout_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,
      timestamp: new Date().toISOString(),
      successUrl: window.location.href,
      checkout_session_id: p.get('checkout_session_id'),
      payment_intent: p.get('payment_intent'),
      amount: p.get('amount'),
      currency: p.get('currency') || 'USD',
      email: p.get('customer_email') || p.get('email'),
      subscription_id: p.get('subscription_id'),
      customer_id: p.get('customer_id'),
      payment_status: p.get('payment_status'),
      ga4_client_id: getGA4ClientId() // Add GA4 client ID
    };
  }

  // Function to send the collected data to a specified webhook URL
  async function sendToWebhook(data, type) {
    const fd = new FormData();
    fd.append('event_type', type);
    Object.entries(data).forEach(([k,v]) => v != null && fd.append(k, v));
    try {
      await fetch(CONFIG.WEBHOOK_URL, { method: 'POST', body: fd });
      if (CONFIG.DEBUG) console.log(`Data sent: ${type}`, data);
    } catch (e) {
      console.error('Webhook error', e);
    }
  }

  // Function to clean up the URL by removing specific query parameters
  function cleanUrl() {
    const url = new URL(window.location);
    ['fromCheckout','msPriceId','stripePriceId','planId','memberId','amount','currency'].forEach(p => url.searchParams.delete(p));
    window.history.replaceState({}, document.title, url.toString());
    if (CONFIG.DEBUG) console.log('URL cleaned');
  }

  // Function to handle checkout failure
  function onCheckoutFailure(member) {
    if (!CONFIG.TRACK_FAILURES) return;
    const p = new URLSearchParams(window.location.search);
    const failed = p.get('payment_status') === 'failed' || p.get('error');
    if (!failed) return;
    const data = {
      failure_url: window.location.href,
      payment_status: p.get('payment_status'),
      error: p.get('error'),
      msPriceId: p.get('msPriceId'),
      stripePriceId: p.get('stripePriceId'),
      timestamp: new Date().toISOString()
    };
    sendToWebhook({ ...data, ...member }, 'checkout_failure');
  }

})();
</script>

Creating the Make.com Scenario

1. Download the JSON blueprint below to get stated.

2. Navigate to Make.com and Create a New Scenario...

3. Click the small box with 3 dots and then Import Blueprint...

4. Upload your file and voila! You're ready to link your own accounts.

Need help with this MemberScript?

All Memberstack customers can ask for assistance in the 2.0 Slack. Please note that these are not official features and support cannot be guaranteed.

Join the 2.0 Slack
Version notes
Attributes
Description
Attribute
No items found.
Guides / Tutorials
No items found.
Tutorial
What is Memberstack?

Auth & payments for Webflow sites

Add logins, subscriptions, gated content, and more to your Webflow site - easy, and fully customizable.

Learn more

"We've been using Memberstack for a long time, and it has helped us achieve things we would have never thought possible using Webflow. It's allowed us to build platforms with great depth and functionality and the team behind it has always been super helpful and receptive to feedback"

Jamie Debnam
39 Digital

"Been building a membership site with Memberstack and Jetboost for a client. Feels like magic building with these tools. As someone who’s worked in an agency where some of these apps were coded from scratch, I finally get the hype now. This is a lot faster and a lot cheaper."

Félix Meens
Webflix Studio

"One of the best products to start a membership site - I like the ease of use of Memberstack. I was able to my membership site up and running within a day. Doesn't get easier than that. Also provides the functionality I need to make the user experience more custom."

Eric McQuesten
Health Tech Nerds
Off World Depot

"My business wouldn't be what it is without Memberstack. If you think $30/month is expensive, try hiring a developer to integrate custom recommendations into your site for that price. Incredibly flexible set of tools for those willing to put in some minimal efforts to watch their well put together documentation."

Riley Brown
Off World Depot

"The Slack community is one of the most active I've seen and fellow customers are willing to jump in to answer questions and offer solutions. I've done in-depth evaluations of alternative tools and we always come back to Memberstack - save yourself the time and give it a shot."

Abbey Burtis
Health Tech Nerds
Slack

Need help with this MemberScript? Join our Slack community!

Join the Memberstack community Slack and ask away! Expect a prompt reply from a team member, a Memberstack expert, or a fellow community member.

Join our Slack