Redirecting MS Accounts Pending Payment Answered

Post author
Sarkis Buniatyan

Script for Redirecting Memberstack Accounts Pending Payment

When users sign up for a paid account and don’t go through with the payment, the account is created nonetheless without a subscription plan applied to it. You can set up various contingencies to deal with this edge case. I took a simpler approach by writing a script that checks if the logged in user has a plan. If not, they get redirected to an activation page. Hope this might be useful.

<script>
(function() {
  // Define the page where users should be redirected to activate their account
  const ACTIVATE_PAGE = '/account/activate';

  // Function to check if the user has an active plan
  function checkUserPlan(member) {
    const currentPath = window.location.pathname;
    
    // If the user is already on the activation page, do nothing
    if (currentPath === ACTIVATE_PAGE) {
      return;
    }

    // Check if the user has any active plan connections
    const hasActivePlan = member.planConnections && member.planConnections.length > 0;
    
    // If the user doesn't have an active plan, redirect them to the activation page
    if (!hasActivePlan) {
      window.location.href = ACTIVATE_PAGE;
    }
  }

  // Function to get the current member using MemberStack's API
  function getCurrentMember() {
    // Check if the MemberStack DOM object and the getCurrentMember method are available
    if (window.$memberstackDom && window.$memberstackDom.getCurrentMember) {
      // Fetch the current member details
      window.$memberstackDom.getCurrentMember()
        .then(({ data: member }) => {
          // If member data is available, check their plan status
          if (member) {
            checkUserPlan(member);
          }
        })
        .catch(() => {
          // Handle any potential errors silently
        });
    }
  }

  // Function to set up the script to run after the page loads
  function setup() {
    // If the document is already loaded or interactive, fetch the current member immediately
    if (document.readyState === 'complete' || document.readyState === 'interactive') {
      getCurrentMember();
    } else {
      // Otherwise, wait for the page to fully load before fetching the current member
      window.addEventListener('load', getCurrentMember);
    }
  }

  // Initialize the script by calling the setup function
  setup();
})();
</script>

Comments

1 comment

  • Comment author
    Josh Lopez

    Hey Sarkis Buniatyan

    Thank you for posting! I hope this helps some people. :) 

    0

Please sign in to leave a comment.