mirror of
https://github.com/SamyRai/turash.git
synced 2025-12-26 23:01:33 +00:00
9.7 KiB
9.7 KiB
Paywall and Subscription System
Overview
Complete subscription and paywall system for monetizing features and managing user access based on subscription plans.
Architecture
1. Subscription Types (types/subscription.ts)
Subscription Plans:
free- Free tier with basic featuresbasic- Basic paid planprofessional- Professional plan (most popular)enterprise- Enterprise plan with all features
Subscription Status:
active- Active subscriptioncanceled- Canceled but still active until period endpast_due- Payment failed, needs attentiontrialing- In trial periodexpired- Subscription expirednone- No subscription
Features:
- Unlimited organizations
- Advanced analytics
- API access
- Custom domain
- SSO
- Priority/Dedicated support
- Team collaboration
- White label
Limits:
- Organizations count
- Users/team members
- Storage (MB)
- API calls per month
- Custom domains
2. Subscription Context (SubscriptionContext)
Location: contexts/SubscriptionContext.tsx
Features:
- Subscription state management
- Feature checking
- Limit checking
- Auto-refresh subscription data
- Defaults to free plan if no subscription
Usage:
import { useSubscription } from '@/contexts/SubscriptionContext';
const {
subscription,
isLoading,
refreshSubscription,
hasFeature,
hasActiveSubscription,
canAccessFeature,
isWithinLimits,
getRemainingLimit,
} = useSubscription();
3. Paywall Components
Paywall
Location: components/paywall/Paywall.tsx
Features:
- Blocks access to premium features
- Shows upgrade dialog
- Displays plan comparison
- Customizable messaging
Usage:
<Paywall
feature="advanced_analytics"
title="Upgrade for Advanced Analytics"
description="Get detailed insights and reports"
>
<AdvancedAnalytics />
</Paywall>
FeatureGate
Location: components/paywall/FeatureGate.tsx
Features:
- Conditionally renders based on subscription
- Can show paywall or fallback
- Lighter weight than Paywall
Usage:
<FeatureGate
feature="api_access"
showPaywall={true}
paywallTitle="API Access Required"
>
<ApiDashboard />
</FeatureGate>
LimitWarning
Location: components/paywall/LimitWarning.tsx
Features:
- Warns when approaching limits
- Shows remaining quota
- Upgrade button
- Different alerts for warning vs. limit reached
Usage:
<LimitWarning
limitType="organizations"
current={organizations.length}
threshold={80}
/>
4. Subscription Hooks
useSubscription()
Location: hooks/useSubscription.ts
Features:
- Enhanced subscription hook
- Convenience methods for plan checks
- Quick feature checks
Usage:
import { useSubscription } from '@/hooks/useSubscription';
const {
isFreePlan,
isProfessionalPlan,
hasUnlimitedOrgs,
hasAdvancedAnalytics,
hasApiAccess,
canAccessFeature,
} = useSubscription();
Integration with Permissions
The subscription system works alongside the permissions system:
- Permissions = What you CAN do (role-based)
- Subscriptions = What features you HAVE ACCESS TO (plan-based)
Example:
// User has permission to update organizations (admin role)
// But subscription limits how many organizations they can have
<PermissionGate permission="organizations:update">
<LimitWarning limitType="organizations" current={count} />
<CreateOrganizationButton disabled={!isWithinLimits('organizations', count)} />
</PermissionGate>
Usage Examples
Example 1: Feature Paywall
import { Paywall } from '@/components/paywall';
const AnalyticsPage = () => {
return (
<Paywall
feature="advanced_analytics"
title="Upgrade for Advanced Analytics"
description="Get detailed insights, custom reports, and data exports"
>
<AdvancedAnalyticsDashboard />
</Paywall>
);
};
Example 2: Conditional Feature Rendering
import { FeatureGate } from '@/components/paywall';
const OrganizationPage = () => {
return (
<div>
<BasicInfo />
<FeatureGate
feature="advanced_analytics"
showPaywall={false}
fallback={<BasicAnalytics />}
>
<AdvancedAnalytics />
</FeatureGate>
</div>
);
};
Example 3: Limit Warnings
import { LimitWarning } from '@/components/paywall';
import { useSubscription } from '@/hooks/useSubscription';
const OrganizationsList = () => {
const { organizations } = useOrganizations();
const { isWithinLimits } = useSubscription();
return (
<div>
<LimitWarning
limitType="organizations"
current={organizations.length}
threshold={80}
/>
<Button
disabled={!isWithinLimits('organizations', organizations.length)}
onClick={createOrganization}
>
Create Organization
</Button>
</div>
);
};
Example 4: Plan-Based UI
import { useSubscription } from '@/hooks/useSubscription';
const SettingsPage = () => {
const { hasCustomDomain, hasSSO, isProfessionalPlan } = useSubscription();
return (
<div>
<BasicSettings />
{hasCustomDomain && (
<CustomDomainSettings />
)}
{hasSSO && (
<SSOSettings />
)}
{!isProfessionalPlan && (
<UpgradePrompt feature="advanced_settings" />
)}
</div>
);
};
Example 5: Combined Permissions and Subscriptions
import { PermissionGate } from '@/components/auth';
import { FeatureGate } from '@/components/paywall';
const AdminOrganizationsPage = () => {
return (
<PermissionGate permission="organizations:read">
<FeatureGate feature="unlimited_organizations" showPaywall={true}>
<UnlimitedOrganizationsList />
</FeatureGate>
<LimitWarning limitType="organizations" current={count} />
</PermissionGate>
);
};
Backend Integration
Required API Endpoints
GET /api/v1/subscription # Get current subscription
POST /api/v1/subscription # Create/update subscription
GET /api/v1/subscription/plans # Get available plans
POST /api/v1/subscription/upgrade # Upgrade subscription
POST /api/v1/subscription/cancel # Cancel subscription
GET /api/v1/subscription/invoices # Get invoices
GET /api/v1/subscription/payment-methods # Get payment methods
POST /api/v1/subscription/payment-methods # Add payment method
Subscription Data Model
interface Subscription {
id: string;
userId: string;
plan: SubscriptionPlan;
status: SubscriptionStatus;
billingPeriod: BillingPeriod;
currentPeriodStart: Date;
currentPeriodEnd: Date;
cancelAtPeriodEnd: boolean;
trialEnd?: Date;
features: SubscriptionFeature[];
limits: {
organizations?: number;
users?: number;
storage?: number;
apiCalls?: number;
customDomains?: number;
};
}
Payment Integration
Recommended Providers
- Stripe - Most popular, comprehensive
- Paddle - Merchant of record, handles taxes
- LemonSqueezy - Simple, good for SaaS
Implementation Steps
-
Backend:
- Create subscription service
- Integrate payment provider
- Webhook handlers for payment events
- Subscription status management
-
Frontend:
- Billing page
- Payment method management
- Invoice history
- Subscription management UI
-
Database:
- Subscriptions table
- Invoices table
- Payment methods table
- Usage tracking table
Feature Gating Strategy
Tier-Based Features
- Free: Basic features, limited usage
- Basic: More features, higher limits
- Professional: Advanced features, high limits
- Enterprise: All features, unlimited
Usage-Based Limits
- Track usage in real-time
- Show warnings at thresholds (80%, 90%, 100%)
- Block actions when limits reached
- Offer upgrade prompts
Feature Flags
- Use subscription features as feature flags
- Easy to enable/disable features per plan
- Can be combined with other feature flags
Testing
Test Cases
-
Free Plan:
- Can access basic features
- Cannot access premium features
- Shows paywall for premium features
- Respects limits
-
Paid Plans:
- Can access all features for their plan
- Respects plan-specific limits
- Can upgrade/downgrade
-
Subscription States:
- Active subscription works normally
- Trial period grants access
- Expired subscription blocks premium features
- Past due shows warning
-
Limits:
- Warnings show at threshold
- Actions blocked at limit
- Upgrade prompts appear
Security Considerations
- Backend Validation: Always validate subscription on backend
- Client-Side Only: UI gating only, never trust for security
- Rate Limiting: Enforce limits server-side
- Webhook Security: Verify webhook signatures
- Payment Security: Never store full payment details
Future Enhancements
- Usage Analytics: Track feature usage per plan
- A/B Testing: Test different pricing strategies
- Promotional Codes: Support discount codes
- Referral Program: Reward referrals
- Usage-Based Billing: Pay-per-use options
- Team Plans: Shared subscriptions
- Annual Discounts: Yearly billing discounts
- Trial Extensions: Extend trials for specific users
Migration Path
Phase 1: Foundation
- ✅ Subscription types and context
- ✅ Paywall components
- ✅ Feature gating
Phase 2: Backend
- ⏳ Subscription API endpoints
- ⏳ Payment provider integration
- ⏳ Webhook handlers
Phase 3: UI
- ⏳ Billing page
- ⏳ Payment method management
- ⏳ Invoice history
Phase 4: Analytics
- ⏳ Usage tracking
- ⏳ Conversion tracking
- ⏳ Revenue analytics