# @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

```bash
npm install @digilogiclabs/saas-factory-payments
# or
yarn add @digilogiclabs/saas-factory-payments
# or
pnpm add @digilogiclabs/saas-factory-payments
```

### Peer Dependencies

The package requires different peer dependencies based on your platform and payment providers:

**For Web (Next.js):**

```bash
# 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 required
```

**For React Native:**

```bash
# 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-pay
```

**For Server-side:**

```bash
# Stripe (optional)
npm install stripe

# PayPal SDK (optional)
npm install @paypal/checkout-server-sdk

# Apple Pay server validation requires custom implementation
```

## Quick Start

### 1. Setup Providers

First, wrap your app with the PaymentsProvider and platform-specific StripeProvider:

**Web (Next.js) - `pages/_app.tsx`:**

```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`:**

```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:**

```tsx
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:**

```tsx
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:**

```tsx
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:**

```tsx
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:**

```tsx
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:**

```tsx
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:**

```bash
# 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=USD
```

**Multi-Provider Payment Component:**

```tsx
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:**

```tsx
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:**

```tsx
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:**

```tsx
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:**

```tsx
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:**

```tsx
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:**

```tsx
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:**

```tsx
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 plans
- `onPlanSelect` (function): Callback when plan is selected
- `currentPlan?` (string): Currently active plan ID
- `loading?` (boolean): Loading state
- `className?` (string): Additional CSS classes

#### SubscriptionManager

Manage subscription status and actions.

**Props:**

- `subscription` (Subscription): Current subscription object
- `onSubscriptionChange` (function): Handle subscription actions
- `onCancel` (function): Handle subscription cancellation
- `className?` (string): Additional CSS classes

#### BillingHistory

Display invoice history with download functionality.

**Props:**

- `invoices` (Invoice[]): Array of invoice objects
- `loading?` (boolean): Loading state
- `onInvoiceDownload?` (function): Handle invoice downloads
- `className?` (string): Additional CSS classes

#### PaymentMethods

Manage payment methods with CRUD operations.

**Props:**

- `paymentMethods` (PaymentMethod[]): Array of payment methods
- `onAdd` (function): Add new payment method
- `onEdit` (function): Edit existing payment method
- `onDelete` (function): Delete payment method
- `onSetDefault` (function): Set default payment method
- `loading?` (boolean): Loading state
- `className?` (string): Additional CSS classes

### Legacy Components

#### CheckoutButton

A button component that handles subscription or one-time payment checkout.

**Props:**

- `priceId` (string): Stripe price ID
- `customerId?` (string): Existing customer ID
- `customerEmail?` (string): Customer email for new customers
- `successUrl?` (string): Redirect URL after successful payment
- `cancelUrl?` (string): Redirect URL after cancelled payment
- `onSuccess?` (function): Callback for successful payment
- `onError?` (function): Callback for payment errors
- `children` (ReactNode): Button content

#### PricingTable

A responsive pricing table component with multiple plans.

**Props:**

- `plans` (PricingPlan[]): Array of pricing plans
- `customerId?` (string): Customer ID for checkout
- `showFeatures?` (boolean): Whether to show plan features
- `layout?` ('grid' | 'list' | 'carousel'): Layout style
- `onPlanSelect?` (function): Callback when plan is selected

#### PaymentForm

An inline payment form for direct payment processing.

**Props:**

- `clientSecret?` (string): Payment intent client secret
- `amount?` (number): Payment amount in cents
- `currency?` (string): Payment currency
- `onSuccess?` (function): Success callback
- `onError?` (function): Error callback

#### BillingPortal (Web only)

A button that opens the Stripe Customer Portal for subscription management.

**Props:**

- `customerId` (string): Customer ID
- `returnUrl?` (string): Return URL after portal session
- `onSuccess?` (function): Success callback
- `onError?` (function): Error callback

### Hooks

#### usePayments

High-level hook that combines customer and subscription management.

```tsx
const {
  customer,
  subscriptions,
  activeSubscription,
  loading,
  createCustomer,
  subscribe,
  cancelSubscription,
  hasActiveSubscription,
  isSubscribedToPlan,
} = usePayments({ customerId });
```

#### useSubscription

Hook for managing customer subscriptions.

```tsx
const {
  subscription,
  subscriptions,
  loading,
  error,
  refetch,
  cancel,
  reactivate,
  updatePaymentMethod,
} = useSubscription({ customerId });
```

#### useCheckout

Hook for handling checkout processes.

```tsx
const {
  loading,
  error,
  createCheckoutSession,
  redirectToCheckout,
  createPaymentIntent,
} = useCheckout({
  onSuccess: sessionId => console.log('Success:', sessionId),
  onError: error => console.error('Error:', error),
});
```

#### useCustomer

Hook for customer management.

```tsx
const {
  customer,
  paymentMethods,
  loading,
  error,
  createCustomer,
  updateCustomer,
  fetchPaymentMethods,
} = useCustomer({ customerId });
```

### Utilities

#### Formatting Functions

```tsx
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

```tsx
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('user@example.com'); // true

// Validate pricing plan structure
const isValidPlan = validatePricingPlan({
  id: 'basic',
  name: 'Basic Plan',
  price: 999,
  interval: 'month',
  features: ['Feature 1'],
  stripePriceId: 'price_123',
}); // true
```

#### Constants

```tsx
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

```tsx
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:

```tsx
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:

```bash
# 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

```tsx
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

```tsx
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`:

```bash
npx @digilogiclabs/create-saas-app create web ui-auth-payments my-saas-app
```

The 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:

1. **Complete Pricing Page**: Three-tier subscription plans with "Most Popular" highlighting
2. **Subscription Management**: Current plan display with upgrade/downgrade options
3. **Payment Methods**: Multiple payment method support with default selection
4. **Billing History**: Invoice history with download functionality
5. **Responsive Design**: Mobile-first design that works on all screen sizes
6. **Error Handling**: Proper loading states and error management
7. **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 configuration
```

### Real-World Implementation

Based on successful implementation in `create-saas-app`:

```tsx
// 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:

```tsx
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](CONTRIBUTING.md) for details.

## License

MIT License - see [LICENSE](LICENSE) file for details.

## Support

- 📧 Email: support@digilogiclabs.com
- 💬 Discord: [Join our community](https://discord.gg/digilogiclabs)
- 📖 Documentation: [docs.digilogiclabs.com](https://docs.digilogiclabs.com)
- 🐛 Issues: [GitHub Issues](https://github.com/DigiLogicLabs/saas-factory-payments/issues)

---

Built with ❤️ by [DigiLogicLabs](https://digilogiclabs.com)
