Home Projects Portfolio Dashboard Export PDF Log in

Implementing Subscription-Based Billing and Soft-Locking in lokal-turnos-salud

The Challenge

In our project, lokal-turnos-salud, we needed to transition to a subscription-based model. The core requirement was to manage user access levels dynamically: users with active subscriptions should have full functionality, while those with expired or unpaid accounts should trigger a "soft-lock" state. This state restricts access to the main dashboard while allowing users to manage their billing settings.

Designing the Subscription Lifecycle

We implemented a state machine pattern to handle account statuses. By treating account states as pure functions based on payment events, we ensure consistency across the application. We integrated with Mercado Pago to handle checkouts and utilized a robust webhook handler with idempotency keys to ensure that every payment event is processed exactly once, regardless of network retries.

Soft-Lock Implementation

To enforce the soft-lock, we created a centralized guard that checks the user's subscription status. If the account is flagged as "VENCIDO" (expired), the middleware redirects the user to the billing management section.

function checkSubscriptionGuard(user: User): boolean {
  if (user.status === 'ACTIVE') return true;
  
  // Allow access only to billing route for expired accounts
  if (currentRoute === '/panel/plan') return true;
  
  return false;
}

This logic acts as a primary filter, ensuring that users are prompted to resolve payment issues without breaking their ability to access the payment portal.

Automation and Maintenance

A key part of this feature was the implementation of a cron job to manage trial periods. The system now automatically notifies users via email at 3-day and 1-day intervals before their trial expires. This proactive communication, combined with the soft-lock, significantly reduces the friction of forced transitions.

Key Takeaways

  • Idempotency is non-negotiable: When dealing with external payment webhooks, always implement idempotency to prevent duplicate transaction processing.
  • Pure State Logic: Decouple account state transitions from the UI. Representing states as pure functions makes unit testing significantly easier.
  • Graceful Degradation: A "soft-lock" provides a better user experience than a hard cut-off, keeping users within the ecosystem while prompting them to renew.

Generated with Gitvlg.com

Implementing Subscription-Based Billing and Soft-Locking in lokal-turnos-salud
J

Julio Cesar Junior Deglise Cardenas

Author

Share: