npm package: @saas-toolkit/payment-kit
Description: Universal payment service abstraction supporting multiple providers (Stripe, Razorpay, PayPal)
Author: Your Name
Latest version: 0.1.0

# @saas-toolkit/payment-kit

Universal payment service abstraction supporting multiple providers (Stripe, Razorpay, PayPal) with a consistent API.

## Features

- **Multiple Providers**: Stripe, Razorpay (more coming soon)
- **Unified API**: Same interface regardless of provider
- **Type Safety**: Full TypeScript support
- **Error Handling**: Comprehensive error handling with retry logic
- **Subscription Management**: Full subscription lifecycle
- **One-time Payments**: Support for single transactions
- **Webhook Handling**: Secure webhook verification
- **Health Checks**: Built-in monitoring

## Installation

```bash
npm install @saas-toolkit/payment-kit @saas-toolkit/service-layer
```

### Provider Dependencies

Install the SDK for your chosen provider:

```bash
# For Stripe
npm install stripe

# For Razorpay
npm install razorpay
```

## Quick Start

### Basic Usage

```typescript
import { PaymentServiceFactory } from '@saas-toolkit/payment-kit';

// Create from environment variables
const paymentService = PaymentServiceFactory.createFromEnvironment();

// Or create with specific provider
const stripeService = PaymentServiceFactory.create('stripe', {
  apiKey: 'sk_test_...',
  mode: 'test',
});
```

### Environment Variables

```bash
PAYMENT_PROVIDER=stripe          # or razorpay
PAYMENT_API_KEY=sk_test_...     # Your provider API key
PAYMENT_WEBHOOK_SECRET=whsec_... # Webhook signing secret
PAYMENT_MODE=test               # test or live
```

### Creating Checkout Sessions

```typescript
// Create a checkout session for a subscription
const session = await paymentService.createCheckoutSession(
  'pro_monthly', // plan ID
  'user_123', // user ID
  {
    successUrl: 'https://yourapp.com/success',
    cancelUrl: 'https://yourapp.com/cancel',
    customerEmail: 'user@example.com',
  }
);

// Redirect user to session.url
window.location.href = session.url;
```

### Managing Subscriptions

```typescript
// Create a subscription
const subscription = await paymentService.createSubscription(
  'cus_customer123', // customer ID
  'pro_monthly', // plan ID
  {
    trialDays: 14,
    metadata: { source: 'website' },
  }
);

// Cancel a subscription
await paymentService.cancelSubscription('sub_123', false); // at period end
await paymentService.cancelSubscription('sub_123', true); // immediately
```

### Customer Management

```typescript
// Create a customer
const customerId = await paymentService.createCustomer(
  'user_123', // internal user ID
  'user@example.com', // email
  'John Doe', // name (optional)
  { source: 'signup' } // metadata (optional)
);

// Get customer details
const customer = await paymentService.getCustomer(customerId);
```

### Webhook Handling

```typescript
// Verify and process webhooks
app.post(
  '/webhooks/payment',
  express.raw({ type: 'application/json' }),
  async (req, res) => {
    const signature =
      req.headers['stripe-signature'] || req.headers['x-razorpay-signature'];

    try {
      const event = paymentService.verifyWebhook(req.body, signature);
      await paymentService.handleWebhookEvent(event);

      res.json({ received: true });
    } catch (error) {
      console.error('Webhook error:', error);
      res.status(400).send('Webhook verification failed');
    }
  }
);
```

## API Reference

### PaymentServiceFactory

Static factory methods for creating payment services.

#### Methods

- `create(provider, config)` - Create service with specific provider
- `createFromEnvironment()` - Create from environment variables
- `detectProvider(apiKey)` - Auto-detect provider from API key format
- `createFromApiKey(apiKey, config?)` - Create by auto-detecting provider

### PaymentService

Base class with methods all providers implement.

#### Checkout & Sessions

- `createCheckoutSession(planId, userId, options?)` - Create payment session
- `getCheckoutSession(sessionId)` - Get session details

#### Subscription Management

- `createSubscription(customerId, planId, options?)` - Create subscription
- `getSubscription(subscriptionId)` - Get subscription details
- `updateSubscription(subscriptionId, updates)` - Update subscription
- `cancelSubscription(subscriptionId, immediately?)` - Cancel subscription
- `getCustomerSubscriptions(customerId)` - List customer subscriptions

#### Customer Management

- `createCustomer(userId, email, name?, metadata?)` - Create customer
- `getCustomer(customerId)` - Get customer details
- `updateCustomer(customerId, updates)` - Update customer
- `findCustomerByUserId(userId)` - Find customer by internal user ID

#### Plans & Pricing

- `getPlans()` - List all available plans
- `getPlan(planId)` - Get specific plan details

#### Webhooks

- `verifyWebhook(payload, signature)` - Verify webhook signature
- `handleWebhookEvent(event)` - Process webhook event
- `getSupportedWebhookEvents()` - List supported webhook types

## Supported Providers

### Stripe

- ✅ Checkout Sessions
- ✅ Plans & Pricing
- 🔄 Subscriptions (in progress)
- 🔄 Customers (in progress)
- 🔄 Webhooks (in progress)

### Razorpay

- 🔄 Full implementation (coming soon)
- Focus on Indian market
- INR currency support

### PayPal

- 📋 Planned for future release

## Error Handling

The package provides structured error handling:

```typescript
import { PaymentError } from '@saas-toolkit/payment-kit';

try {
  const session = await paymentService.createCheckoutSession(planId, userId);
} catch (error) {
  if (error instanceof PaymentError) {
    console.error('Payment error:', error.code, error.message);
    console.error('Error type:', error.type);
    console.error('Status code:', error.statusCode);
    console.error('Details:', error.details);
  }
}
```

## Health Checks

```typescript
// Check if payment service is healthy
const isHealthy = await paymentService.isHealthy();

// Get service capabilities
const capabilities = paymentService.getCapabilities();
console.log('Supported currencies:', capabilities.supportedCurrencies);
```

## Examples

See the [examples directory](../../examples) for complete usage examples including:

- Basic checkout flow
- Subscription management
- Webhook handling
- Error handling patterns

## License

MIT