#172 - Capture Stripe Checkout Session v0.1

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

Ver demostración

<!-- 💙 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>

Creación del escenario Make.com

1. Descargue el proyecto JSON a continuación para empezar.

2. Navegue hasta Make.com y Cree un nuevo escenario...

3. Haga clic en el pequeño cuadro con 3 puntos y luego Importar Blueprint...

4. Sube tu archivo y ¡voilá! Ya está listo para vincular sus propias cuentas.

¿Necesitas ayuda con este MemberScript?

Todos los clientes de Memberstack pueden solicitar asistencia en el Slack 2.0. Tenga en cuenta que no se trata de funciones oficiales y que no se puede garantizar la asistencia.

Únete al Slack 2.0
Notas de la versión
Atributos
Descripción
Atributo
No se han encontrado artículos.
Guías / Tutoriales
No se han encontrado artículos.
Tutorial
¿Qué es Memberstack?

Autenticación y pagos para sitios Webflow

Añada inicios de sesión, suscripciones, contenido cerrado y mucho más a su sitio Webflow: fácil y totalmente personalizable.

Más información

"Hemos estado utilizando Memberstack durante mucho tiempo, y nos ha ayudado a lograr cosas que nunca hubiéramos creído posible usando Webflow. Nos ha permitido construir plataformas con gran profundidad y funcionalidad y el equipo que hay detrás siempre ha sido súper servicial y receptivo a los comentarios"

Jamie Debnam
39 Digital

"He estado construyendo un sitio de membresía con Memberstack y Jetboost para un cliente. Se siente como magia construir con estas herramientas. Como alguien que ha trabajado en una agencia donde algunas de estas aplicaciones fueron codificadas desde cero, finalmente entiendo el bombo ahora. Esto es mucho más rápido y mucho más barato."

Félix Meens
Estudio Webflix

"Uno de los mejores productos para iniciar un sitio de membresía - Me gusta la facilidad de uso de Memberstack. Yo era capaz de mi sitio de membresía en marcha y funcionando dentro de un día. No hay nada más fácil que eso. También proporciona la funcionalidad que necesito para hacer la experiencia del usuario más personalizada."

Eric McQuesten
Nerds de la tecnología sanitaria
Depósito Off World

"Mi negocio no sería lo que es sin Memberstack. Si crees que 30 $/mes es caro, prueba a contratar a un desarrollador para que integre recomendaciones personalizadas en tu sitio por ese precio. Increíblemente flexible conjunto de herramientas para aquellos dispuestos a poner en algunos esfuerzos mínimos para ver su documentación bien elaborado."

Riley Brown
Depósito Off World

"La comunidad de Slack es una de las más activas que he visto y los clientes están dispuestos a responder preguntas y ofrecer soluciones. He realizado evaluaciones en profundidad de herramientas alternativas y siempre volvemos a Memberstack: ahórrate el tiempo y dale una oportunidad"."

Abadía Burtis
Nerds de la tecnología sanitaria
Slack

¿Necesitas ayuda con este MemberScript? ¡Únete a nuestra comunidad Slack!

Únete al Slack de la comunidad Memberstack y ¡pregunta! Espera una respuesta rápida de un miembro del equipo, un experto de Memberstack o un compañero de la comunidad.

Únete a nuestro Slack