#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.

View demo


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

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