# Stripe Payment Utils

A comprehensive Stripe payment utility package for handling payment intents, splits, refunds, and transfers with configurable split percentages.

## Installation

```bash
npm install stripe-payment-utils
```

## Setup

```javascript
const StripePaymentUtils = require('stripe-payment-utils');

// Initialize with your Stripe secret key
const stripeUtils = new StripePaymentUtils('sk_test_your_stripe_secret_key');

// Or initialize with environment variable
const stripeUtils = new StripePaymentUtils(process.env.STRIPE_SECRET_KEY);
```

## Features

- ✅ Payment Intent Creation
- ✅ Payment Capture with Split
- ✅ Refund Processing
- ✅ Transfer Management
- ✅ Configurable Split Percentages
- ✅ Error Handling
- ✅ TypeScript Support

## API Reference

### 1. Create Payment Intent

```javascript
const paymentIntent = await stripeUtils.createPaymentIntent({
  amount: 5000, // Amount in cents
  currency: 'usd',
  customerId: 'cus_xxxxxxxxxxxxx',
  paymentMethodId: 'pm_xxxxxxxxxxxxx',
  metadata: {
    bookingId: 'booking_123',
    customerId: 'user_123',
    receiverId: 'videographer_456'
  }
});
```

### 2. Capture Payment with Split

```javascript
const result = await stripeUtils.capturePaymentWithSplit({
  paymentIntentId: 'pi_xxxxxxxxxxxxx',
  totalAmount: 5000, // Amount in cents
  receiverId: 'acct_xxxxxxxxxxxxx', // Receiver's Stripe account
  adminAccountId: 'acct_admin_xxxxx', // Admin's Stripe account
  splitConfig: {
    receiverPercentage: 80, // 80% to receiver
    adminPercentage: 20     // 20% to admin
  },
  metadata: {
    bookingId: 'booking_123',
    type: 'completed_booking'
  }
});
```

### 3. Process Refund

```javascript
const refund = await stripeUtils.processRefund({
  paymentIntentId: 'pi_xxxxxxxxxxxxx',
  amount: 5000, // Amount in cents (optional - full refund if not specified)
  reason: 'requested_by_customer',
  metadata: {
    bookingId: 'booking_123',
    refundReason: 'Customer cancellation'
  }
});
```

### 4. Handle No-Show Payment

```javascript
const noShowResult = await stripeUtils.handleNoShow({
  paymentIntentId: 'pi_xxxxxxxxxxxxx',
  totalAmount: 5000, // Amount in cents
  receiverId: 'acct_xxxxxxxxxxxxx',
  noShowPercentage: 15, // 15% to receiver
  refundPercentage: 85,  // 85% refunded to customer
  metadata: {
    bookingId: 'booking_123',
    type: 'no_show_payment'
  }
});
```

### 5. Cancel Payment Intent

```javascript
const cancelled = await stripeUtils.cancelPaymentIntent({
  paymentIntentId: 'pi_xxxxxxxxxxxxx',
  reason: 'requested_by_customer'
});
```

## Configuration Options

### Split Configuration

```javascript
// Default split configuration
const defaultSplit = {
  receiverPercentage: 80,
  adminPercentage: 20
};

// Custom split for different scenarios
const customSplit = {
  receiverPercentage: 100, // 100% to receiver (no admin split)
  adminPercentage: 0
};
```

### Transfer Configuration

```javascript
const transferConfig = {
  currency: 'usd',
  description: 'Payment for booking',
  metadata: {
    bookingId: 'booking_123',
    type: 'payment_split'
  }
};
```

## Error Handling

The package provides comprehensive error handling:

```javascript
try {
  const result = await stripeUtils.capturePaymentWithSplit({
    paymentIntentId: 'pi_xxxxxxxxxxxxx',
    totalAmount: 5000,
    receiverId: 'acct_xxxxxxxxxxxxx',
    adminAccountId: 'acct_admin_xxxxx',
    splitConfig: {
      receiverPercentage: 80,
      adminPercentage: 20
    }
  });
  
  console.log('Payment captured successfully:', result);
} catch (error) {
  console.error('Payment capture failed:', error.message);
  
  // Error types
  if (error.type === 'StripeCardError') {
    // Handle card errors
  } else if (error.type === 'StripeInvalidRequestError') {
    // Handle invalid request errors
  } else if (error.type === 'StripeAPIError') {
    // Handle API errors
  }
}
```

## Response Format

### Success Response

```javascript
{
  success: true,
  data: {
    paymentIntentId: 'pi_xxxxxxxxxxxxx',
    receiverTransferId: 'tr_xxxxxxxxxxxxx',
    adminTransferId: 'tr_admin_xxxxx',
    receiverAmount: 4000,
    adminAmount: 1000,
    totalAmount: 5000,
    status: 'succeeded'
  }
}
```

### Error Response

```javascript
{
  success: false,
  error: {
    type: 'StripeCardError',
    message: 'Your card was declined.',
    code: 'card_declined'
  }
}
```

## Environment Variables

```env
STRIPE_SECRET_KEY=sk_test_your_stripe_secret_key
STRIPE_PUBLISHABLE_KEY=pk_test_your_stripe_publishable_key
ADMIN_STRIPE_ACCOUNT_ID=acct_admin_xxxxx
```

## Examples

### Complete Booking Flow

```javascript
const StripePaymentUtils = require('stripe-payment-utils');

const stripeUtils = new StripePaymentUtils(process.env.STRIPE_SECRET_KEY);

// 1. Create payment intent
const paymentIntent = await stripeUtils.createPaymentIntent({
  amount: 5000,
  currency: 'usd',
  customerId: 'cus_xxxxxxxxxxxxx',
  paymentMethodId: 'pm_xxxxxxxxxxxxx',
  metadata: {
    bookingId: 'booking_123',
    customerId: 'user_123',
    receiverId: 'videographer_456'
  }
});

// 2. Capture payment with split when booking is completed
const captureResult = await stripeUtils.capturePaymentWithSplit({
  paymentIntentId: paymentIntent.id,
  totalAmount: 5000,
  receiverId: 'acct_xxxxxxxxxxxxx',
  adminAccountId: process.env.ADMIN_STRIPE_ACCOUNT_ID,
  splitConfig: {
    receiverPercentage: 80,
    adminPercentage: 20
  },
  metadata: {
    bookingId: 'booking_123',
    type: 'completed_booking'
  }
});

console.log('Payment captured and split:', captureResult);
```

### No-Show Handling

```javascript
// Handle no-show scenario
const noShowResult = await stripeUtils.handleNoShow({
  paymentIntentId: 'pi_xxxxxxxxxxxxx',
  totalAmount: 5000,
  receiverId: 'acct_xxxxxxxxxxxxx',
  noShowPercentage: 15,
  refundPercentage: 85,
  metadata: {
    bookingId: 'booking_123',
    type: 'no_show_payment'
  }
});

console.log('No-show payment processed:', noShowResult);
```

## Contributing

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. 