@digilogiclabs/saas-factory-payments
v1.2.9
Published
Modern cross-platform payments package for Next.js 15+ and React Native applications with multi-provider support (Stripe, PayPal, Apple Pay) and subscription analytics
Maintainers
Readme
@digilogiclabs/saas-factory-payments
A comprehensive multi-provider payments package for SaaS Factory that works seamlessly in both Next.js and React Native environments. Built with TypeScript and supporting Stripe, PayPal, and Apple Pay with advanced subscription analytics.
Features
- 🌐 Hybrid Support: Works in both Next.js web applications and React Native mobile apps
- 🔒 Type-Safe: Built with TypeScript for better developer experience
- 💳 Multi-Provider: Support for Stripe, PayPal, and Apple Pay payments
- 📊 Subscription Analytics: Advanced analytics hooks for revenue, churn, and growth metrics
- 🎨 UI Components: Pre-built components for subscription plans, billing management, and payment methods
- 🪝 React Hooks: Powerful hooks for payments, subscriptions, and analytics
- 🔧 Server Utilities: Complete server-side API and webhook handling
- 📱 Mobile-First: Native mobile payment flows with provider-specific implementations
- 🎯 Provider-Agnostic: Extensible architecture supporting multiple payment providers
- 🚀 CLI Integration: Works seamlessly with create-saas-app
- 💰 Complete SaaS Solution: Everything needed for subscription-based applications
- 🔄 Auto-Detection: Automatic provider detection based on environment variables
Installation
npm install @digilogiclabs/saas-factory-payments
# or
yarn add @digilogiclabs/saas-factory-payments
# or
pnpm add @digilogiclabs/saas-factory-paymentsPeer Dependencies
The package requires different peer dependencies based on your platform and payment providers:
For Web (Next.js):
# Required for all payment providers
npm install react react-dom
# Stripe (optional)
npm install @stripe/stripe-js @stripe/react-stripe-js stripe
# PayPal SDK is loaded dynamically - no additional installation required
# Apple Pay is native to Safari - no additional installation requiredFor React Native:
# Required for all payment providers
npm install react react-native
# Stripe (optional)
npm install @stripe/stripe-react-native stripe
# PayPal React Native (optional)
npm install react-native-paypal
# Apple Pay React Native (optional)
npm install @react-native-apple-pay/apple-payFor Server-side:
# Stripe (optional)
npm install stripe
# PayPal SDK (optional)
npm install @paypal/checkout-server-sdk
# Apple Pay server validation requires custom implementationQuick Start
1. Setup Providers
First, wrap your app with the PaymentsProvider and platform-specific StripeProvider:
Web (Next.js) - pages/_app.tsx:
import { PaymentsProvider } from '@digilogiclabs/saas-factory-payments';
import { StripeProvider } from '@digilogiclabs/saas-factory-payments/web';
export default function App({ Component, pageProps }) {
return (
<PaymentsProvider
config={{
provider: 'stripe',
publishableKey: process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!,
environment: process.env.NODE_ENV as 'development' | 'production',
}}
>
<StripeProvider>
<Component {...pageProps} />
</StripeProvider>
</PaymentsProvider>
);
}React Native - App.tsx:
import { PaymentsProvider } from '@digilogiclabs/saas-factory-payments';
import { StripeProvider } from '@digilogiclabs/saas-factory-payments/native';
export default function App() {
return (
<PaymentsProvider
config={{
provider: 'stripe',
publishableKey: process.env.EXPO_PUBLIC_STRIPE_PUBLISHABLE_KEY!,
environment: __DEV__ ? 'development' : 'production',
}}
>
<StripeProvider>
<MainApp />
</StripeProvider>
</PaymentsProvider>
);
}2. Use UI Components (v0.3.0)
Subscription Plans Component:
import { SubscriptionPlans } from '@digilogiclabs/saas-factory-payments/web';
const plans = [
{
id: 'basic',
name: 'Basic Plan',
price: 999, // $9.99 in cents
interval: 'month',
features: ['10 projects', 'Basic support', '1GB storage'],
stripePriceId: 'price_basic_monthly',
},
{
id: 'pro',
name: 'Pro Plan',
price: 1999, // $19.99 in cents
interval: 'month',
features: ['Unlimited projects', 'Priority support', '10GB storage'],
popular: true,
stripePriceId: 'price_pro_monthly',
},
];
export default function PricingPage() {
return (
<SubscriptionPlans
plans={plans}
onPlanSelect={(planId) => {
console.log('Selected plan:', planId);
// Handle plan selection
}}
currentPlan="basic" // Optional: highlight current plan
/>
);
}Subscription Manager Component:
import { SubscriptionManager } from '@digilogiclabs/saas-factory-payments/web';
const subscription = {
id: 'sub_123',
planId: 'pro',
planName: 'Pro Plan',
status: 'active',
currentPeriodStart: new Date('2024-01-01'),
currentPeriodEnd: new Date('2024-02-01'),
cancelAtPeriodEnd: false,
amount: 1999,
currency: 'usd',
interval: 'month',
};
export default function BillingPage() {
return (
<SubscriptionManager
subscription={subscription}
onSubscriptionChange={(action) => {
console.log('Subscription action:', action);
// Handle upgrade, downgrade, pause, resume
}}
onCancel={() => {
console.log('Cancel subscription');
// Handle cancellation
}}
/>
);
}Billing History Component:
import { BillingHistory } from '@digilogiclabs/saas-factory-payments/web';
const invoices = [
{
id: 'inv_123',
amount: 1999,
currency: 'usd',
status: 'paid',
date: new Date('2024-01-01'),
description: 'Pro Plan - Monthly',
downloadUrl: 'https://example.com/invoice.pdf',
invoiceNumber: 'INV-001',
},
];
export default function BillingHistoryPage() {
return (
<BillingHistory
invoices={invoices}
onInvoiceDownload={(invoiceId) => {
console.log('Download invoice:', invoiceId);
// Handle invoice download
}}
/>
);
}Payment Methods Component:
import { PaymentMethods } from '@digilogiclabs/saas-factory-payments/web';
const paymentMethods = [
{
id: 'pm_123',
type: 'card',
last4: '4242',
brand: 'visa',
expiryMonth: 12,
expiryYear: 2025,
isDefault: true,
},
];
export default function PaymentMethodsPage() {
return (
<PaymentMethods
paymentMethods={paymentMethods}
onAdd={() => console.log('Add payment method')}
onEdit={(methodId) => console.log('Edit method:', methodId)}
onDelete={(methodId) => console.log('Delete method:', methodId)}
onSetDefault={(methodId) => console.log('Set default:', methodId)}
/>
);
}3. Use Utilities and Hooks
Formatting Utilities:
import { formatCurrency, formatDate } from '@digilogiclabs/saas-factory-payments';
// Format currency amounts
const price = formatCurrency(1999, 'USD'); // "$19.99"
// Format dates
const date = formatDate(new Date()); // "January 1, 2024"Payment Hooks:
import { usePayments } from '@digilogiclabs/saas-factory-payments';
function SubscriptionStatus({ customerId }) {
const { customer, subscriptions, loading } = usePayments({ customerId });
if (loading) return <div>Loading...</div>;
return (
<div>
<h3>Customer: {customer?.name}</h3>
<p>Active Subscriptions: {subscriptions?.length || 0}</p>
</div>
);
}4. Multi-Provider Support (v1.1.0)
The package now supports multiple payment providers with automatic detection and unified components.
Environment Variables for Auto-Detection:
# Stripe (optional)
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
STRIPE_SECRET_KEY=sk_test_...
# PayPal (optional)
NEXT_PUBLIC_PAYPAL_CLIENT_ID=your_paypal_client_id
PAYPAL_CLIENT_SECRET=your_paypal_client_secret
PAYPAL_CURRENCY=USD
# Apple Pay (optional)
NEXT_PUBLIC_APPLE_PAY_MERCHANT_ID=merchant.yourapp.com
NEXT_PUBLIC_APPLE_PAY_MERCHANT_NAME=Your Store
NEXT_PUBLIC_APPLE_PAY_COUNTRY_CODE=US
NEXT_PUBLIC_APPLE_PAY_CURRENCY_CODE=USDMulti-Provider Payment Component:
import { MultiProviderPayment } from '@digilogiclabs/saas-factory-payments/web';
import { PaymentProviderFactory } from '@digilogiclabs/saas-factory-payments';
function CheckoutPage() {
const providers = {
stripe: {
provider: 'stripe' as const,
publishableKey: process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!,
environment: 'development' as const,
stripeConfig: {
publishableKey: process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!,
},
},
paypal: {
provider: 'paypal' as const,
environment: 'development' as const,
paypalConfig: {
clientId: process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID!,
environment: 'sandbox',
currency: 'USD',
},
},
applepay: {
provider: 'applepay' as const,
environment: 'development' as const,
applePayConfig: {
merchantId: process.env.NEXT_PUBLIC_APPLE_PAY_MERCHANT_ID!,
merchantName: 'Your Store',
countryCode: 'US',
currencyCode: 'USD',
environment: 'sandbox',
},
},
};
return (
<MultiProviderPayment
amount={1999} // $19.99 for one-time payments
currency="USD"
label="Complete Purchase"
description="Pro Plan - Monthly Subscription"
providers={providers}
preferredProvider="stripe"
allowProviderSelection={true}
layout="vertical"
showProviderLogos={true}
merchantValidationEndpoint="/api/apple-pay/validate" // Required for Apple Pay
onPaymentSuccess={(provider, details) => {
console.log(`Payment successful with ${provider}:`, details);
}}
onPaymentError={(provider, error) => {
console.error(`Payment failed with ${provider}:`, error);
}}
/>
);
}Provider-Specific Components:
import {
PayPalButton,
PayPalSubscriptionButton,
ApplePayButton,
ApplePaySubscriptionButton
} from '@digilogiclabs/saas-factory-payments/web';
// PayPal one-time payment
<PayPalButton
amount={1999}
currency="USD"
config={paypalConfig}
onSuccess={(details) => console.log('PayPal payment:', details)}
onError={(error) => console.error('PayPal error:', error)}
/>
// PayPal subscription
<PayPalSubscriptionButton
planId="P-5ML4271244454362WXNWU5NQ"
config={paypalConfig}
onSubscriptionSuccess={(subscriptionId, details) => {
console.log('PayPal subscription:', subscriptionId, details);
}}
/>
// Apple Pay one-time payment
<ApplePayButton
amount={1999}
currency="USD"
label="Buy Pro Plan"
config={applePayConfig}
merchantValidationEndpoint="/api/apple-pay/validate"
onPaymentSuccess={(payment) => console.log('Apple Pay:', payment)}
/>
// Apple Pay subscription
<ApplePaySubscriptionButton
subscriptionDescription="Pro Plan Monthly"
regularBilling={{ label: "Pro Plan", amount: 1999 }}
managementURL="https://yourapp.com/billing"
config={applePayConfig}
merchantValidationEndpoint="/api/apple-pay/validate"
onPaymentSuccess={(payment) => console.log('Apple Pay subscription:', payment)}
/>5. Subscription Analytics (v1.1.0)
Get insights into your subscription business with built-in analytics hooks.
Subscription Analytics Hook:
import { useSubscriptionAnalytics } from '@digilogiclabs/saas-factory-payments';
function DashboardPage({ subscriptions }) {
const analytics = useSubscriptionAnalytics(subscriptions, {
period: 'month',
realTime: true,
refreshInterval: 60000, // 1 minute
});
if (analytics.loading) return <div>Loading analytics...</div>;
return (
<div>
<h2>Subscription Analytics</h2>
{/* Key Metrics */}
<div className="metrics-grid">
<div>
<h3>Monthly Recurring Revenue</h3>
<p>${analytics.metrics?.monthlyRecurringRevenue.toFixed(2)}</p>
</div>
<div>
<h3>Active Subscribers</h3>
<p>{analytics.metrics?.activeSubscribers}</p>
</div>
<div>
<h3>Churn Rate</h3>
<p>{analytics.metrics?.monthlyChurnRate.toFixed(1)}%</p>
</div>
<div>
<h3>Growth Rate</h3>
<p>{analytics.metrics?.growthRate.toFixed(1)}%</p>
</div>
</div>
{/* Health Status */}
<div className={`status ${analytics.isHealthy ? 'healthy' : 'warning'}`}>
Status: {analytics.isHealthy ? 'Healthy' : 'Needs Attention'}
</div>
{/* Insights */}
<div className="insights">
<h3>Insights</h3>
{analytics.insights.map((insight, index) => (
<p key={index}>{insight}</p>
))}
</div>
{/* Alerts */}
{analytics.alerts.length > 0 && (
<div className="alerts">
<h3>Alerts</h3>
{analytics.alerts.map((alert, index) => (
<div key={index} className={`alert alert-${alert.type}`}>
<strong>{alert.title}</strong>: {alert.message}
</div>
))}
</div>
)}
</div>
);
}Revenue Analytics Hook:
import { useRevenueAnalytics } from '@digilogiclabs/saas-factory-payments';
function RevenuePage({ subscriptions }) {
const revenue = useRevenueAnalytics(subscriptions, {
period: 'month',
includeBreakdown: true,
includeForecasting: true,
currency: 'USD',
});
return (
<div>
<h2>Revenue Analytics</h2>
<div className="revenue-overview">
<div>
<h3>Total Revenue</h3>
<p>${revenue.totalRevenue.toFixed(2)}</p>
</div>
<div>
<h3>Recurring Revenue</h3>
<p>${revenue.recurringRevenue.toFixed(2)}</p>
</div>
<div>
<h3>Growth Rate</h3>
<p>{revenue.revenueGrowth.toFixed(1)}%</p>
</div>
<div>
<h3>Revenue Quality</h3>
<p>{revenue.revenueQuality}</p>
</div>
<div>
<h3>Predictability Score</h3>
<p>{revenue.predictability}/100</p>
</div>
</div>
{revenue.revenueBreakdown && (
<div className="revenue-breakdown">
<h3>Revenue Breakdown</h3>
<div>New Revenue: ${revenue.revenueBreakdown.newRevenue.toFixed(2)}</div>
<div>Expansion: ${revenue.revenueBreakdown.expansionRevenue.toFixed(2)}</div>
<div>Contraction: -${revenue.revenueBreakdown.contractionRevenue.toFixed(2)}</div>
<div>Churned: -${revenue.revenueBreakdown.churned.toFixed(2)}</div>
<div><strong>Net New: ${revenue.revenueBreakdown.netNewRevenue.toFixed(2)}</strong></div>
</div>
)}
{revenue.forecast && (
<div className="revenue-forecast">
<h3>6-Month Forecast</h3>
{revenue.forecast.map((forecast, index) => (
<div key={index}>
{forecast.period}: ${forecast.predictedRevenue.toFixed(2)}
(±${(forecast.confidenceInterval.high - forecast.confidenceInterval.low).toFixed(2)})
</div>
))}
</div>
)}
</div>
);
}6. Server-Side Integration
Create Checkout Session:
import { createStripeCheckoutSession } from '@digilogiclabs/saas-factory-payments/server';
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
export default async function handler(req, res) {
try {
const session = await createStripeCheckoutSession(stripe, {
priceId: 'price_pro_monthly',
successUrl: 'https://yourapp.com/success',
cancelUrl: 'https://yourapp.com/cancel',
customerId: 'cus_123', // optional
});
res.json({ sessionId: session.id });
} catch (error) {
res.status(500).json({ error: error.message });
}
}Process Payment:
import { processPayment } from '@digilogiclabs/saas-factory-payments/server';
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
export default async function handler(req, res) {
try {
const paymentIntent = await processPayment(stripe, {
amount: 1999, // $19.99 in cents
currency: 'usd',
paymentMethodId: 'pm_123',
customerId: 'cus_123',
description: 'Pro Plan Subscription',
});
res.json({ paymentIntent });
} catch (error) {
res.status(500).json({ error: error.message });
}
}Manage Subscriptions:
import {
createSubscription,
updateSubscription,
cancelSubscription
} from '@digilogiclabs/saas-factory-payments/server';
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
// Create subscription
const subscription = await createSubscription(stripe, {
customerId: 'cus_123',
priceId: 'price_pro_monthly',
paymentMethodId: 'pm_123',
});
// Update subscription
const updatedSubscription = await updateSubscription(stripe, {
subscriptionId: 'sub_123',
priceId: 'price_enterprise_monthly',
});
// Cancel subscription
const canceledSubscription = await cancelSubscription(stripe, 'sub_123', true);Webhook Handling:
import {
validateStripeSignature,
handleStripeWebhook
} from '@digilogiclabs/saas-factory-payments/server';
export default async function handler(req, res) {
const signature = req.headers['stripe-signature'];
try {
const event = validateStripeSignature(
req.body,
signature,
process.env.STRIPE_WEBHOOK_SECRET!
);
await handleStripeWebhook(event, {
onPaymentSucceeded: async (paymentIntent) => {
console.log('Payment succeeded:', paymentIntent.id);
// Update your database
},
onSubscriptionCreated: async (subscription) => {
console.log('Subscription created:', subscription.id);
// Update your database
},
onInvoicePaid: async (invoice) => {
console.log('Invoice paid:', invoice.id);
// Send confirmation email
},
});
res.json({ received: true });
} catch (error) {
res.status(400).json({ error: error.message });
}
}API Reference
UI Components (v0.3.0)
SubscriptionPlans
Display pricing plans with selection functionality.
Props:
plans(PricingPlan[]): Array of pricing plansonPlanSelect(function): Callback when plan is selectedcurrentPlan?(string): Currently active plan IDloading?(boolean): Loading stateclassName?(string): Additional CSS classes
SubscriptionManager
Manage subscription status and actions.
Props:
subscription(Subscription): Current subscription objectonSubscriptionChange(function): Handle subscription actionsonCancel(function): Handle subscription cancellationclassName?(string): Additional CSS classes
BillingHistory
Display invoice history with download functionality.
Props:
invoices(Invoice[]): Array of invoice objectsloading?(boolean): Loading stateonInvoiceDownload?(function): Handle invoice downloadsclassName?(string): Additional CSS classes
PaymentMethods
Manage payment methods with CRUD operations.
Props:
paymentMethods(PaymentMethod[]): Array of payment methodsonAdd(function): Add new payment methodonEdit(function): Edit existing payment methodonDelete(function): Delete payment methodonSetDefault(function): Set default payment methodloading?(boolean): Loading stateclassName?(string): Additional CSS classes
Legacy Components
CheckoutButton
A button component that handles subscription or one-time payment checkout.
Props:
priceId(string): Stripe price IDcustomerId?(string): Existing customer IDcustomerEmail?(string): Customer email for new customerssuccessUrl?(string): Redirect URL after successful paymentcancelUrl?(string): Redirect URL after cancelled paymentonSuccess?(function): Callback for successful paymentonError?(function): Callback for payment errorschildren(ReactNode): Button content
PricingTable
A responsive pricing table component with multiple plans.
Props:
plans(PricingPlan[]): Array of pricing planscustomerId?(string): Customer ID for checkoutshowFeatures?(boolean): Whether to show plan featureslayout?('grid' | 'list' | 'carousel'): Layout styleonPlanSelect?(function): Callback when plan is selected
PaymentForm
An inline payment form for direct payment processing.
Props:
clientSecret?(string): Payment intent client secretamount?(number): Payment amount in centscurrency?(string): Payment currencyonSuccess?(function): Success callbackonError?(function): Error callback
BillingPortal (Web only)
A button that opens the Stripe Customer Portal for subscription management.
Props:
customerId(string): Customer IDreturnUrl?(string): Return URL after portal sessiononSuccess?(function): Success callbackonError?(function): Error callback
Hooks
usePayments
High-level hook that combines customer and subscription management.
const {
customer,
subscriptions,
activeSubscription,
loading,
createCustomer,
subscribe,
cancelSubscription,
hasActiveSubscription,
isSubscribedToPlan,
} = usePayments({ customerId });useSubscription
Hook for managing customer subscriptions.
const {
subscription,
subscriptions,
loading,
error,
refetch,
cancel,
reactivate,
updatePaymentMethod,
} = useSubscription({ customerId });useCheckout
Hook for handling checkout processes.
const {
loading,
error,
createCheckoutSession,
redirectToCheckout,
createPaymentIntent,
} = useCheckout({
onSuccess: (sessionId) => console.log('Success:', sessionId),
onError: (error) => console.error('Error:', error),
});useCustomer
Hook for customer management.
const {
customer,
paymentMethods,
loading,
error,
createCustomer,
updateCustomer,
fetchPaymentMethods,
} = useCustomer({ customerId });Utilities
Formatting Functions
import { formatCurrency, formatDate } from '@digilogiclabs/saas-factory-payments';
// Format currency with proper symbols and decimals
const price = formatCurrency(1999, 'USD'); // "$19.99"
const euroPrice = formatCurrency(2499, 'EUR'); // "€24.99"
// Format dates in user-friendly format
const date = formatDate(new Date()); // "January 1, 2024"
const shortDate = formatDate(new Date(), { short: true }); // "Jan 1, 2024"Validation Functions
import { validateAmount, validateEmail, validatePricingPlan } from '@digilogiclabs/saas-factory-payments';
// Validate payment amounts
const isValidAmount = validateAmount(1999); // true
const isInvalidAmount = validateAmount(-100); // false
// Validate email addresses
const isValidEmail = validateEmail('[email protected]'); // true
// Validate pricing plan structure
const isValidPlan = validatePricingPlan({
id: 'basic',
name: 'Basic Plan',
price: 999,
interval: 'month',
features: ['Feature 1'],
stripePriceId: 'price_123',
}); // trueConstants
import {
BILLING_INTERVALS,
CURRENCY_SYMBOLS,
SUBSCRIPTION_STATUS
} from '@digilogiclabs/saas-factory-payments';
// Available billing intervals
console.log(BILLING_INTERVALS); // ['day', 'week', 'month', 'year']
// Currency symbols
console.log(CURRENCY_SYMBOLS.USD); // '$'
console.log(CURRENCY_SYMBOLS.EUR); // '€'
// Subscription statuses
console.log(SUBSCRIPTION_STATUS.ACTIVE); // 'active'
console.log(SUBSCRIPTION_STATUS.CANCELED); // 'canceled'Server-Side Utilities
Stripe Integration Helpers
import {
createStripeCheckoutSession,
processPayment,
createSubscription,
updateSubscription,
cancelSubscription,
validateStripeSignature,
handleStripeWebhook,
} from '@digilogiclabs/saas-factory-payments/server';All server utilities require a Stripe instance as the first parameter:
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);Configuration
Environment Variables
Create a .env.local file (Next.js) or configure your environment:
# Stripe Configuration
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
# For React Native (Expo)
EXPO_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...PaymentsProvider Configuration
interface PaymentsConfig {
provider: 'stripe'; // More providers coming soon
publishableKey: string;
secretKey?: string; // Server-side only
webhookSecret?: string; // Server-side only
environment: 'development' | 'production';
}Type Definitions
interface PricingPlan {
id: string;
name: string;
description?: string;
price: number; // In cents
currency?: string;
interval: 'day' | 'week' | 'month' | 'year';
stripePriceId?: string;
features: string[];
popular?: boolean;
trialPeriodDays?: number;
}
interface Subscription {
id: string;
planId: string;
planName: string;
status: 'active' | 'canceled' | 'past_due' | 'unpaid' | 'incomplete';
currentPeriodStart: Date;
currentPeriodEnd: Date;
cancelAtPeriodEnd: boolean;
amount: number;
currency: string;
interval: 'month' | 'year';
}
interface Invoice {
id: string;
amount: number;
currency: string;
status: 'paid' | 'pending' | 'failed' | 'draft' | 'open';
date: Date;
description: string;
downloadUrl?: string;
invoiceNumber?: string;
}
interface PaymentMethod {
id: string;
type: 'card' | 'bank_account';
last4: string;
brand?: string;
expiryMonth?: number;
expiryYear?: number;
isDefault: boolean;
bankName?: string;
accountType?: 'checking' | 'savings';
}CLI Integration
This package is designed to work seamlessly with create-saas-app:
npx @digilogiclabs/create-saas-app create web ui-auth-payments my-saas-appThe CLI will generate a complete SaaS application with:
- ✅ Home page with success confirmation
- ✅ Checkout page with 3-tier pricing (Basic $9.99, Pro $19.99, Enterprise $49.99)
- ✅ Billing page with subscription management and payment methods
- ✅ Responsive design that works on all devices
- ✅ TypeScript support with full type safety
- ✅ Working payment flows using v0.3.0 utilities
Generated Features
When using the ui-auth-payments template, you get:
- Complete Pricing Page: Three-tier subscription plans with "Most Popular" highlighting
- Subscription Management: Current plan display with upgrade/downgrade options
- Payment Methods: Multiple payment method support with default selection
- Billing History: Invoice history with download functionality
- Responsive Design: Mobile-first design that works on all screen sizes
- Error Handling: Proper loading states and error management
- TypeScript Integration: Full type safety throughout the application
Examples
Complete SaaS Application Structure
my-saas-app/
├── pages/
│ ├── index.tsx # Home page with feature overview
│ ├── checkout.tsx # Pricing plans and subscription
│ ├── billing.tsx # Subscription management
│ └── api/
│ ├── checkout.ts # Create checkout sessions
│ └── webhooks/
│ └── stripe.ts # Handle Stripe webhooks
├── components/
│ ├── SubscriptionPlans.tsx
│ ├── BillingHistory.tsx
│ └── PaymentMethods.tsx
└── lib/
└── stripe.ts # Stripe configurationReal-World Implementation
Based on successful implementation in create-saas-app:
// pages/checkout.tsx
import { SubscriptionPlans } from '@digilogiclabs/saas-factory-payments/web';
import { formatCurrency } from '@digilogiclabs/saas-factory-payments';
const plans = [
{
id: 'basic',
name: 'Basic Plan',
price: 999,
interval: 'month',
features: [
'Up to 10 projects',
'Basic support',
'1GB storage',
'Standard templates',
],
stripePriceId: 'price_basic_monthly',
},
{
id: 'pro',
name: 'Pro Plan',
price: 1999,
interval: 'month',
features: [
'Unlimited projects',
'Priority support',
'10GB storage',
'Premium templates',
'Advanced analytics',
],
popular: true,
stripePriceId: 'price_pro_monthly',
},
{
id: 'enterprise',
name: 'Enterprise Plan',
price: 4999,
interval: 'month',
features: [
'Everything in Pro',
'Custom integrations',
'100GB storage',
'Dedicated support',
'White-label options',
],
stripePriceId: 'price_enterprise_monthly',
},
];
export default function CheckoutPage() {
return (
<div className="min-h-screen bg-gray-50 py-12">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="text-center">
<h1 className="text-3xl font-extrabold text-gray-900 sm:text-4xl">
Choose Your Plan
</h1>
<p className="mt-4 text-xl text-gray-600">
Start building your SaaS application today
</p>
</div>
<div className="mt-12">
<SubscriptionPlans
plans={plans}
onPlanSelect={(planId) => {
// Handle plan selection
window.location.href = `/api/checkout?priceId=${plans.find(p => p.id === planId)?.stripePriceId}`;
}}
className="max-w-5xl mx-auto"
/>
</div>
</div>
</div>
);
}TypeScript Support
This package is built with TypeScript and provides full type safety:
import type {
PricingPlan,
Subscription,
Customer,
PaymentsConfig,
Invoice,
PaymentMethod,
SubscriptionStatus,
SubscriptionAction,
} from '@digilogiclabs/saas-factory-payments';
// All components and hooks are fully typed
const subscription: Subscription = {
id: 'sub_123',
planId: 'pro',
planName: 'Pro Plan',
status: 'active',
currentPeriodStart: new Date(),
currentPeriodEnd: new Date(),
cancelAtPeriodEnd: false,
amount: 1999,
currency: 'usd',
interval: 'month',
};Contributing
We welcome contributions! Please see our Contributing Guide for details.
License
MIT License - see LICENSE file for details.
Support
- 📧 Email: [email protected]
- 💬 Discord: Join our community
- 📖 Documentation: docs.digilogiclabs.com
- 🐛 Issues: GitHub Issues
Built with ❤️ by DigiLogicLabs
