#192 - Display a Members Current Subscription Plans v0.1

Display all of a member's active subscription plans in organized cards, with paid plans shown first.

Voir la démo


<!-- 💙 MEMBERSCRIPT #192 v0.1 💙 - DISPLAY A MEMBERS CURRENT SUBSCRIPTION PLANS INFORMATION -->

<script>

(function() {

  'use strict';

  document.addEventListener("DOMContentLoaded", async function() {

    try {

      // Wait for Memberstack to be ready

      await waitForMemberstack();

      

      const memberstack = window.$memberstackDom;

      if (!memberstack) {

        console.error('MemberScript #192: Memberstack DOM package is not loaded.');

        showError();

        return;

      }

      

      const memberResult = await memberstack.getCurrentMember();

      // Handle both { data: {...} } and direct member object formats

      const member = memberResult?.data || memberResult;

      

      // Check various possible locations for plan connections

      let planConnections = null;

      

      if (member && member.planConnections) {

        planConnections = member.planConnections;

      } else if (member && member.data && member.data.planConnections) {

        planConnections = member.data.planConnections;

      } else if (member && member.plans) {

        planConnections = member.plans;

      }

      

      if (!planConnections || planConnections.length === 0) {

        showNoPlanState();

        return;

      }

      

      // Prioritize paid plans over free plans

      // Sort plans: paid plans (with payment amount > 0) first, then free plans

      const sortedPlans = [...planConnections].sort((a, b) => {

        const aAmount = a.payment?.amount || 0;

        const bAmount = b.payment?.amount || 0;

        // Paid plans (amount > 0) come first

        if (aAmount > 0 && bAmount === 0) return -1;

        if (aAmount === 0 && bAmount > 0) return 1;

        // If both are paid, sort by amount descending

        if (aAmount > 0 && bAmount > 0) return bAmount - aAmount;

        // If both are free, maintain original order

        return 0;

      });

      

      // Display all plans

      await displayAllPlans(sortedPlans, memberstack);

      

    } catch (error) {

      console.error("MemberScript #192: Error loading plan information:", error);

      showError();

    }

  });

  

  function waitForMemberstack() {

    return new Promise((resolve) => {

      if (window.$memberstackDom && window.$memberstackReady) {

        resolve();

      } else {

        document.addEventListener('memberstack.ready', resolve);

        // Fallback timeout

        setTimeout(resolve, 2000);

      }

    });

  }

  

  async function displayAllPlans(planConnections, memberstack) {

    const loadingState = document.querySelector('[data-ms-code="loading-state"]');

    const noPlanState = document.querySelector('[data-ms-code="no-plan-state"]');

    

    // Look for template - can use data-ms-template attribute or data-ms-code="plan-card-template"

    let planCardTemplate = document.querySelector('[data-ms-template]') || document.querySelector('[data-ms-code="plan-card-template"]');

    

    // Determine the container

    let plansContainer = null;

    if (planCardTemplate) {

      // Check if the template element also has plan-container attribute

      const templateCodeAttr = planCardTemplate.getAttribute('data-ms-code') || '';

      if (templateCodeAttr.includes('plan-container')) {

        // Template is the same element as container, so use its parent as the container for multiple cards

        plansContainer = planCardTemplate.parentElement;

      } else {

        // Template is separate, find the container

        plansContainer = document.querySelector('[data-ms-code="plans-container"]') || document.querySelector('[data-ms-code="plan-container"]');

      }

    } else {

      // No template found, look for container

      plansContainer = document.querySelector('[data-ms-code="plans-container"]') || document.querySelector('[data-ms-code="plan-container"]');

    }

    

    // Hide loading and no-plan states

    if (loadingState) loadingState.style.display = 'none';

    if (noPlanState) noPlanState.style.display = 'none';

    

    // If no template found, look for the first card structure inside the container

    if (!planCardTemplate && plansContainer) {

      // Find the first card-like structure (one that has plan-name element)

      const firstCard = plansContainer.querySelector('[data-ms-code="plan-name"]')?.closest('.grid-list_item, .plan-details_list, [data-ms-code="plan-container"]');

      if (firstCard && firstCard !== plansContainer) {

        planCardTemplate = firstCard;

      }

    }

    

    if (!plansContainer) {

      console.error('MemberScript #192: Plans container not found. Add data-ms-code="plans-container" or data-ms-code="plan-container" to your container element.');

      showError();

      return;

    }

    

    if (!planCardTemplate) {

      console.error('MemberScript #192: Plan card template not found. Add data-ms-template attribute or data-ms-code="plan-card-template" to your card template element, or ensure your container has a card structure with plan details.');

      showError();

      return;

    }

    

    // Save original display state

    const originalDisplay = planCardTemplate.style.display || getComputedStyle(planCardTemplate).display;

    

    // Clear existing plan cards (except template) BEFORE hiding template

    const existingCards = plansContainer.querySelectorAll('[data-ms-code="plan-card"]');

    existingCards.forEach(card => {

      if (card !== planCardTemplate && !card.hasAttribute('data-ms-template')) {

        card.remove();

      }

    });

    

    // Also clear any cards that might have been created before (but not the template)

    const allCards = Array.from(plansContainer.querySelectorAll('.grid-list_item'));

    allCards.forEach(card => {

      if (card !== planCardTemplate && !card.hasAttribute('data-ms-template') && card.querySelector('[data-ms-code="plan-name"]')) {

        card.remove();

      }

    });

    

    // Mark template and hide it (but keep in DOM for cloning)

    planCardTemplate.setAttribute('data-ms-template', 'true');

    planCardTemplate.style.display = 'none';

    

    // Show container

    plansContainer.style.display = '';

    

    // Create a card for each plan

    for (let i = 0; i < planConnections.length; i++) {

      const planConnection = planConnections[i];

      const planId = planConnection.planId;

      

      if (!planId) continue;

      

      // Try to get the plan details

      let plan = null;

      try {

        if (memberstack.getPlan) {

          plan = await memberstack.getPlan({ planId });

        }

      } catch (e) {

        // Plan details will be extracted from planConnection

      }

      

      // Clone the template (deep clone to get all children)

      const planCard = planCardTemplate.cloneNode(true);

      

      // Remove template attribute and set card attribute

      planCard.removeAttribute('data-ms-template');

      planCard.setAttribute('data-ms-code', 'plan-card');

      

      // Set display - use original if it was visible, otherwise use 'block'

      planCard.style.display = (originalDisplay && originalDisplay !== 'none') ? originalDisplay : 'block';

      

      // Fill in plan information

      fillPlanCard(planCard, plan, planConnection);

      

      // Append to container

      plansContainer.appendChild(planCard);

    }

  }

  

  function fillPlanCard(card, plan, planConnection) {

    // Helper function to format plan ID into a readable name

    const formatPlanId = (planId) => {

      if (!planId) return 'Your Plan';

      // Convert "pln_premium-wabh0ux0" to "Premium"

      return planId

        .replace(/^pln_/, '')

        .replace(/-[a-z0-9]+$/, '')

        .split('-')

        .map(word => word.charAt(0).toUpperCase() + word.slice(1))

        .join(' ');

    };

    

    // Update plan name - try multiple sources

    let planName = null;

    if (plan) {

      planName = plan?.data?.name || plan?.data?.planName || plan?.data?.label || plan?.name || plan?.planName || plan?.label;

    }

    if (!planName) {

      planName = formatPlanId(planConnection.planId);

    }

    updateElementInCard(card, '[data-ms-code="plan-name"]', planName);

    

    // Update plan price - check payment object first, then plan data

    let priceValue = null;

    if (planConnection.payment && planConnection.payment.amount !== undefined && planConnection.payment.amount !== null) {

      priceValue = planConnection.payment.amount;

    } else if (plan?.data && plan.data.amount !== undefined && plan.data.amount !== null) {

      priceValue = plan.data.amount;

    } else if (plan && plan.amount !== undefined && plan.amount !== null) {

      priceValue = plan.amount;

    } else if (plan?.data && plan.data.price !== undefined && plan.data.price !== null) {

      // If price is in cents, convert

      priceValue = plan.data.price / 100;

    } else if (plan && plan.price !== undefined && plan.price !== null) {

      // If price is in cents, convert

      priceValue = plan.price / 100;

    }

    

    if (priceValue !== null && priceValue > 0) {

      const currency = planConnection.payment?.currency || plan?.data?.currency || plan?.currency || 'usd';

      const symbol = currency === 'usd' ? '$' : currency.toUpperCase();

      const formattedPrice = priceValue.toFixed(2);

      updateElementInCard(card, '[data-ms-code="plan-price"]', `${symbol}${formattedPrice}`);

    } else {

      updateElementInCard(card, '[data-ms-code="plan-price"]', 'Free');

    }

    

    // Update billing interval - use planConnection.type

    if (planConnection.type) {

      const type = planConnection.type.charAt(0).toUpperCase() + planConnection.type.slice(1).toLowerCase();

      updateElementInCard(card, '[data-ms-code="plan-interval"]', type);

    } else {

      updateElementInCard(card, '[data-ms-code="plan-interval"]', 'N/A');

    }

    

    // Update status

    const statusEl = card.querySelector('[data-ms-code="plan-status"]');

    if (statusEl) {

      const status = planConnection.status || 'Active';

      // Format status nicely (ACTIVE -> Active)

      const formattedStatus = status.charAt(0).toUpperCase() + status.slice(1).toLowerCase();

      statusEl.textContent = formattedStatus;

      

      // Add cancelled class for styling

      if (status && (status.toLowerCase() === 'canceled' || status.toLowerCase() === 'cancelled')) {

        statusEl.classList.add('cancelled');

      } else {

        statusEl.classList.remove('cancelled');

      }

    }

    

    // Update next billing date - use payment.nextBillingDate

    let billingDate = planConnection.payment?.nextBillingDate;

    

    if (billingDate) {

      // Handle Unix timestamp (in seconds, so multiply by 1000)

      const date = new Date(billingDate < 10000000000 ? billingDate * 1000 : billingDate);

      updateElementInCard(card, '[data-ms-code="plan-next-billing"]', formatDate(date));

    } else {

      updateElementInCard(card, '[data-ms-code="plan-next-billing"]', 'N/A');

    }

  }

  

  function updateElementInCard(card, selector, text) {

    const el = card.querySelector(selector);

    if (el) {

      el.textContent = text;

    }

  }

  

  function formatDate(date) {

    return date.toLocaleDateString('en-US', { 

      year: 'numeric', 

      month: 'long', 

      day: 'numeric' 

    });

  }

  

  function showNoPlanState() {

    const loadingState = document.querySelector('[data-ms-code="loading-state"]');

    const noPlanState = document.querySelector('[data-ms-code="no-plan-state"]');

    const plansContainer = document.querySelector('[data-ms-code="plans-container"]') || document.querySelector('[data-ms-code="plan-container"]');

    

    if (loadingState) loadingState.style.display = 'none';

    if (plansContainer) plansContainer.style.display = 'none';

    if (noPlanState) noPlanState.style.display = 'block';

  }

  

  function showError() {

    const noPlanState = document.querySelector('[data-ms-code="no-plan-state"]');

    const loadingState = document.querySelector('[data-ms-code="loading-state"]');

    const plansContainer = document.querySelector('[data-ms-code="plans-container"]') || document.querySelector('[data-ms-code="plan-container"]');

    

    if (loadingState) loadingState.style.display = 'none';

    if (plansContainer) plansContainer.style.display = 'none';

    if (noPlanState) {

      noPlanState.innerHTML = '<div class="empty-state"><div style="font-size: 3rem;">!</div><h3>Error Loading Plans</h3><p>Unable to load your plan information. Please try again later.</p></div>';

      noPlanState.style.display = 'block';

    }

  }

})();

</script>

Customer Showcase

Have you used a Memberscript in your project? We’d love to highlight your work and share it with the community!

Création du scénario Make.com

1. Téléchargez le modèle JSON ci-dessous pour commencer.

2. Naviguez jusqu'à Make.com et créez un nouveau scénario...

3. Cliquez sur la petite boîte avec trois points, puis sur Import Blueprint...

4. Téléchargez votre fichier et voilà ! Vous êtes prêt à relier vos propres comptes.

Besoin d'aide avec ce MemberScript ?

Tous les clients de Memberstack peuvent demander de l'aide dans le Slack 2.0. Veuillez noter qu'il ne s'agit pas de fonctionnalités officielles et que le support ne peut être garanti.

Rejoignez le Slack 2.0
Notes de version
Attributs
Description
Attribut
Aucun élément n'a été trouvé.
Guides / Tutoriels
Aucun élément n'a été trouvé.
Tutoriel
Qu'est-ce que Memberstack ?

Auth & paiements pour les sites Webflow

Ajoutez des logins, des abonnements, du contenu à accès limité, et plus encore à votre site Webflow - facile et entièrement personnalisable.

En savoir plus

"Nous utilisons Memberstack depuis longtemps et il nous a aidé à réaliser des choses que nous n'aurions jamais imaginées avec Webflow. Il nous a aidé à réaliser des choses que nous n'aurions jamais cru possibles en utilisant Webflow. Il nous a permis de construire des plateformes avec beaucoup de profondeur et de fonctionnalité et l'équipe derrière lui a toujours été super utile et réceptif à la rétroaction"

Jamie Debnam
39 Numérique

"J'ai construit un site d'adhésion avec Memberstack et Jetboost pour un client. On a l'impression de construire quelque chose de magique avec ces outils. J'ai travaillé dans une agence où certaines de ces applications ont été codées à partir de zéro, je comprends enfin l'engouement suscité par ces outils. C'est beaucoup plus rapide et beaucoup moins cher."

Félix Meens
Studio Webflix

"L'un des meilleurs produits pour lancer un site d'adhésion - J'aime la facilité d'utilisation de Memberstack. J'ai pu mettre en place mon site d'adhésion en l'espace d'une journée.. Il n'y a rien de plus facile. Il fournit également les fonctionnalités dont j'ai besoin pour rendre l'expérience de l'utilisateur plus personnalisée."

Eric McQuesten
Nerds des technologies de la santé
Off World Depot

"Mon entreprise ne serait pas ce qu'elle est sans Memberstack. Si vous pensez que 30 $/mois c'est cher, essayez d'engager un développeur pour intégrer des recommandations personnalisées à votre site pour ce prix-là. Un ensemble d'outils incroyablement flexibles pour ceux qui sont prêts à faire quelques efforts minimes pour regarder leur documentation bien faite."

Riley Brown
Off World Depot

"La communauté Slack est l'une des plus actives que j'ai vues et les autres clients sont prêts à intervenir pour répondre aux questions et proposer des solutions. J'ai effectué des évaluations approfondies d'outils alternatifs et nous revenons toujours à Memberstack - gagnez du temps et tentez votre chance."

Abbey Burtis
Nerds des technologies de la santé
Slack

Besoin d'aide avec ce MemberScript ? Rejoignez notre communauté Slack !

Rejoignez le Slack de la communauté Memberstack et posez vos questions ! Attendez-vous à une réponse rapide d'un membre de l'équipe, d'un expert Memberstack ou d'un autre membre de la communauté.

Rejoignez notre Slack