How to efficiently retrieve subscription plan names through the Memberstack API for a growing user database? Answered

Post author
Hamza Nasim

Is there a way/attribute to get the current plan name?

Comments

10 comments

  • Comment author
    Memberstack Team
    • Official comment

    The script #186 is a more relevant solution for your use case. Instead of manually trying to fetch plan names (which gets messy when you’re adding multiple new plans every week), this script automatically displays the member’s active plan details — including the plan name, price, billing interval, and even the next billing date.

    That way, you don’t need to build complex logic to pull plan names yourself. The script ties directly into Memberstack’s data attributes, ensuring the correct plan information is shown consistently and efficiently, no matter how many plans you add. It’s a cleaner, scalable approach to keeping your pricing tables and plan lists accurate for logged‑in users.

  • Comment author
    Chukwudi

    Hi Hamza,

    At the moment, this is not possible yet but it's on the roadmap, no ETA. You can upvote it here.

    However, I came up with a workaround that works.

    <script>
    window.$memberstackDom.getCurrentMember().then((member) => {
    if (member.data) {
    var currentPlan = document.getElementById('current-plan'); //I'm assuming you have a div or span on your website with ID current-plan
    const planConnections = member.data["planConnections"];
    if (planConnections && planConnections.length > 0) {
    const proPlan = "pln_fffff-ki110f6e"; // Replace with the Plan ID of the ProPlan
    const ultraPlan = "pln_blahblah-ultra-oaiz0sdk"; // Replace with the Plan ID of the Ultra plan
    const planIds = planConnections.map(connection => connection.planId);

    if (planIds.includes(proPlan) || planIds.includes(ultraPlan)) {
    if (planIds.includes(proPlan)) {
    currentPlan.innerText = "Pro";
    }
    if (planIds.includes(ultraPlan)) {
    currentPlan.innerText = "Ultra";
    }
    } else {
    currentPlan.innerText = "Free"; }
    } else {
    console.log('no plan connections');
    }
    } else {
    window.location.href = '/login';
    }
    })
    </script>
    This code fetches the current member's subscription plan information and dynamically updates a specific HTML element (current-plan) to show the name of the active plan. It also handles cases where the member is not logged in or does not have a subscription plan. You have to place this before the closing </body> tag on the page where you want to show the current plan.
     
    0
  • Comment author
    Hamza Nasim

    Thank you so much Chukwudi you’re a champ!

    0
  • Comment author
    Aurélien Gallier undefined

    Hi!
    Isn't it possible to retrieve plan names via the Memberstack API?

    0
  • Comment author
    Chukwudi

    We don't have an out-of-the-box feature for this, but I do have a workaround 🙂

    To display the plan name, you can set the text content of an element (like a span or div) to the name of the plan associated with the current user. Here’s how you can do it:

    1. Add an Element to Display the Plan Name: Create a span or div element in your HTML where the plan name will be displayed.
    2. Modify the JavaScript to Display the Plan Name: Update the script to change the text content of the span or div based on the plan ID.

    HTML Example:
    Add a span element to display the plan name:

    <div> 
    <span id="planName">Loading your plan...</span>
    </div>
    Javascript code
    The script below sets the text content of the planName element.
    <script> 
    document.addEventListener("DOMContentLoaded", function () {
    const planNameElement = document.querySelector('#planName');

    window.$memberstackDom.getCurrentMember().then((member) => {
    if (member) {
    const planConnections = member.data["planConnections"];

    if (planConnections && planConnections.length > 0) {
    const priceA = "prc_IDForPriceA"; // Replace with the Price ID of Price A
    const priceB = "prc_IDForPriceB"; // Replace with the Price ID of Price B
    const planA = "pln_IDForPlanA"; // Replace with the Plan ID of Plan A
    const planB = "pln_IDForPlanB"; // Replace with the Plan ID of Plan B

    // Filter out planConnections where payment or planId is null or undefined
    const priceIds = planConnections
    .filter(connection => connection.payment) // Ensure payment exists
    .map(connection => connection.payment.priceId);

    const planIds = planConnections
    .filter(connection => connection.planId) // Ensure planId exists
    .map(connection => connection.planId);

    let planName = "No active plan or price";

    // Default message // Check for price IDs and set the plan name
    if (priceIds.includes(priceA)) { planName = 'Monthly Plan'; }
    if (priceIds.includes(priceB)) { planName = 'Annual Plan'; }

    // Check for plan IDs and set the plan name
    if (planIds.includes(planA)) { planName = 'Plan A'; }
    if (planIds.includes(planB)) { planName = 'Plan B'; }

    // Update the element with the plan name
    planNameElement.textContent = planName;

    } else {
    planNameElement.textContent = "No active plan or price";
    }
    }
    }).catch(() => {
    console.error('Failed to load Memberstack data.');
    planNameElement.textContent = "Unable to load plan details";
    });
    });
    </script>
    Explanation:
    • planNameElement: The DOM element where the plan name will be displayed.
    • planName: A variable to hold the name of the plan. It starts with a default message that gets updated based on the user’s plan.
    • Setting Text Content: Depending on which price ID or plan ID is found, the planName variable is updated, and its value is then set as the text content of the planNameElement.
    0
  • Comment author
    Raquel Lopez

    Hi, depends on what you need to use the plan names.

    There's a call to the api that would throw a list of the plans that you have (as an owner) in Memberstack. $memberstackDom.getPlans();

    If you need to show your logged in user the list of plans he is subscribed to, then you would use Chukwudi's answer.

    If none of the answers are good enough, please elaborate a little bit more on what's your end result to give you a better direction.

    0
  • Comment author
    Michelle You

    I'm so glad I found this thread! I'm working on displaying a list of plans that a logged-in user is subscribed to. The challenge is that we have a lot of plans (3+ added every week). Does anyone have an idea how to fetch the plan name efficiently?

    0
  • Comment author
    Chukwudi

    At the moment, we do not have a feature to fetch them effectively. In the meantime, you'd have to modify the code I shared in the thread each time you add a new plan.

    0
  • Comment author
    Raquel Lopez

    Hi Michelle You, If by "effectively" you mean not having to modify the code each time you create a new plan, then I think I can help. Not to disregard Chukwudi's answer, but there's actually a way to fetch all the plans 😅

    You can use $memberstackDom.getPlans() method to fetch all the plans that you have available in Memberstack. And with that information you can create a relation with the plan you member's are subscribed to to get the name of the plans.

    I worked on a little script that might be able to help you. And you can assign the attribute data-ms-planlist to the div or wrapper where you want to fill the list of plans

    async function init() {
    const {data: plans} = await $memberstackDom.getPlans()
    const memberData = JSON.parse(localStorage.getItem('_ms-mem'));
    if (memberData) {
    const memberPlans = memberData.planConnections;
    const planNames = memberPlans.map(memberPlan => {
    const index = plans.findIndex(plan => plan.id ===
    memberPlan.planId);
    return plans[index].name
    })

    let html = planNames.map(plan => `<span>${plan}</span>`).join('');
    $('[data-ms-planlist]').append(html);
    }

    }

    if (window.$memberstackReady) {
    // Run the code immediately if Memberstack is already ready
    init();
    } else {
    // Wait for Memberstack to be ready if it's not already
    document.addEventListener("memberstack.ready", init);
    }

    I hope it works for you, if you need to display paid members plans then the logic would have to change. With this base you should be able to tweak it around with help of Rey

    0
  • Comment author
    Michelle You

    Raquel Lopez Thanks so much! I was able to get it to work using $memberstackDom.getPlans(). Appreciate the help! Chukwudi

    0

Please sign in to leave a comment.