/lovable-prompts

Lovable Prompts for Building Subscription system

Build a robust subscription system with our expert prompt guide. Fast-track billing, user management & secure access control.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

Lovable Prompts for Building Subscription system

 
Setting Up Project Files & Dependencies
 

  • Create the main file app.lov to host routes, middleware, and core logic.
  • Add dependency installation within your code. Include the following modules for handling database operations, authentication, subscriptions, and payment processing:

// Import modules for Subscription System functionality
import "lovable-db"           // For database operations and persistent storage
import "lovable-auth"         // For user authentication and session management
import "lovable-subscription" // For managing subscription plans and user subscriptions
import "lovable-payment"      // For secure payment processing and transactions
  • Ensure these modules are loaded at the beginning of your file for seamless integration.

 
Defining the Database Schema for Subscriptions
 

  • Create a schema for subscription plans and user subscriptions to track plan details, status, and expiry dates.
  • Define models for both plans and user subscriptions with necessary fields such as plan name, price, duration, and user ID.

// Define a SubscriptionPlan model
model SubscriptionPlan {
  id           string   // Unique identifier for the subscription plan
  name         string   // Name of the plan (e.g., Basic, Premium)
  price        float    // Cost of the subscription
  duration     int      // Subscription duration in days
  features     [string] // List of features included in this plan
}

// Define a UserSubscription model
model UserSubscription {
  id          string    // Unique identifier for the user subscription
  userId      string    // Identifier for the user
  planId      string    // SubscriptionPlan id reference
  startDate   date      // Date when the subscription started
  endDate     date      // Calculated end date based on duration
  status      string    // Subscription status (active, canceled, expired)
}
  • Ensure relational integrity between UserSubscription and SubscriptionPlan.

 
Creating Subscription Logic & API Routes
 

  • Define API routes to handle subscription operations including subscribing, canceling, and upgrading plans.
  • Ensure that each route handles authentication and proper validation of user input.

// Example route for subscribing to a plan
route "/subscribe" {
  method "POST"
  
  // Authenticate the user
  middleware "auth.verifyToken"
  
  // Handler for subscription process
  handle (req, res) {
    // Extract plan and user information
    let planId = req.body.planId
    let userId = req.user.id
    
    // Verify the subscription plan exists
    let plan = SubscriptionPlan.find(planId)
    if (!plan) {
      return res.error("Invalid subscription plan")
    }
    
    // Calculate subscription dates based on the plan duration
    let startDate = date.now() 
    let endDate = startDate.addDays(plan.duration)
    
    // Create a new user subscription
    let subscription = new UserSubscription({
      userId: userId,
      planId: planId,
      startDate: startDate,
      endDate: endDate,
      status: "active"
    })
    subscription.save()
    
    return res.success("Subscription successful", subscription)
  }
}

// Example route for canceling a subscription
route "/cancel-subscription" {
  method "POST"
  
  middleware "auth.verifyToken"
  
  handle (req, res) {
    let userId = req.user.id
    
    // Retrieve the active subscription for the user
    let subscription = UserSubscription.findOne({ userId: userId, status: "active" })
    if (!subscription) {
      return res.error("No active subscription found")
    }
    
    // Set subscription status to canceled
    subscription.status = "canceled"
    subscription.save()
    
    return res.success("Subscription canceled successfully")
  }
}
  • Include additional routes as needed for plan upgrades and downgrades, ensuring proper validation and billing adjustments.

 
Integrating Secure Payment Processing
 

  • Integrate the payment module to process subscription payments securely.
  • Embed the payment route into your subscription flow to charge users before activating subscriptions.

// Route to process payment and activate subscription
route "/process-payment" {
  method "POST"
  
  middleware "auth.verifyToken"
  
  handle (req, res) {
    let userId = req.user.id
    let planId = req.body.planId
    let paymentDetails = req.body.paymentDetails
    
    // Retrieve selected plan information
    let plan = SubscriptionPlan.find(planId)
    if (!plan) {
      return res.error("Invalid plan selected")
    }
    
    // Process the payment using the payment module
    let paymentResult = Payment.process({
      userId: userId,
      amount: plan.price,
      paymentDetails: paymentDetails
    })
    
    if (!paymentResult.success) {
      return res.error("Payment failed: " + paymentResult.error)
    }
    
    // Initiate subscription creation on successful payment
    let startDate = date.now()
    let endDate = startDate.addDays(plan.duration)
    
    let subscription = new UserSubscription({
      userId: userId,
      planId: planId,
      startDate: startDate,
      endDate: endDate,
      status: "active"
    })
    subscription.save()
    
    return res.success("Payment processed and subscription activated", subscription)
  }
}
  • Ensure the payment module handles security best practices, including tokenization and encryption of sensitive data.

 
Designing User Flow & Notifications
 

  • Implement intuitive user flow: users select a plan, enter payment details, and receive confirmation upon successful subscription.
  • Set up middleware to protect subscription endpoints and notify users via email or in-app notifications when statuses change.

// Middleware to enforce authenticated access for subscription endpoints
middleware "auth.verifyToken" {
  handle (req, res, next) {
    if (!req.user) {
      return res.error("Authentication required")
    }
    next()
  }
}

// Sample function for triggering notification after subscription updates
function notifyUser(userId, message) {
  // Utilize in-app notification systems or external services
  Notification.send({ userId: userId, message: message })
}

// Example usage: notify user on subscription creation
// This should be integrated into the subscription creation route as shown above
  • Ensure that all notifications are clear about subscription status, renewal dates, and any changes in plans.

 
Error Handling and Logging
 

  • Implement robust error handling and logging throughout the subscription process for easier maintenance and debugging.
  • Ensure errors related to payment processing, database operations, and authentication are caught and handled appropriately.

// Global error handling in routes
onError (err, req, res) {
  // Log the error details for debugging purposes
  Log.error("Subscription System Error: ", err)
  
  // Return a generic error message to the user
  res.error("An error occurred, please try again later.")
}

// Attach the error handler globally
app.onError = onError
  • Maintain logs for payment transactions and subscription changes for audit purposes.

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022