> ## Documentation Index
> Fetch the complete documentation index at: https://docs.vchata.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Billing Services

> Payment processing, subscription management, and financial operations services

# Billing Services

The Billing Services provide comprehensive financial management capabilities including payment processing, subscription management, credit operations, and billing analytics for the VChata platform.

## Overview

The Billing Services layer includes:

* 💳 **Billing Service** - Core billing operations and organization setup
* 💰 **Balance Service** - Credit balance management and operations
* 🏦 **Stripe Service** - Payment processing and Stripe integration
* 💳 **Credit Service** - Credit purchasing and consumption tracking
* 🧾 **Invoice Service** - Invoice generation and management
* 📊 **Message Usage Service** - Usage tracking and billing calculations

## Billing Service

### Organization Billing Setup

The Billing Service handles the complete billing infrastructure setup for organizations.

#### Setup Billing

```typescript theme={null}
// Setup billing for a new organization
const organization = await billingService.setupBillingForOrganization(
  organizationId,
  "billing@acme.com",
  "Acme Corporation"
);
```

#### Add Payment Method

```typescript theme={null}
// Add a payment method to organization
await billingService.addPaymentMethod(
  organizationId,
  "pm_1234567890abcdef"
);
```

#### Create Subscription

```typescript theme={null}
// Create a subscription for the organization
const subscription = await billingService.createSubscription(
  organizationId,
  {
    planId: "plan_basic",
    paymentMethodId: "pm_1234567890abcdef",
    trialPeriodDays: 14
  }
);
```

### Available Methods

<Expandable title="setupBillingForOrganization(organizationId, email, name)">
  **Description**: Initializes billing infrastructure for an organization.

  **Parameters**:

  * `organizationId`: Organization ID
  * `email`: Billing email address
  * `name`: Organization name

  **Returns**: `Promise<Organization>` - Updated organization with billing info
</Expandable>

<Expandable title="addPaymentMethod(organizationId, paymentMethodId)">
  **Description**: Attaches a payment method to the organization.

  **Parameters**:

  * `organizationId`: Organization ID
  * `paymentMethodId`: Stripe payment method ID

  **Returns**: `Promise<void>`
</Expandable>

<Expandable title="createSubscription(organizationId, options)">
  **Description**: Creates a new subscription for the organization.

  **Parameters**:

  * `organizationId`: Organization ID
  * `options`: Subscription configuration

  **Returns**: `Promise<Subscription>` - Created subscription
</Expandable>

<Expandable title="updateSubscription(organizationId, updates)">
  **Description**: Updates an existing subscription.

  **Parameters**:

  * `organizationId`: Organization ID
  * `updates`: Subscription updates

  **Returns**: `Promise<Subscription>` - Updated subscription
</Expandable>

<Expandable title="cancelSubscription(organizationId, immediate?)">
  **Description**: Cancels the organization's subscription.

  **Parameters**:

  * `organizationId`: Organization ID
  * `immediate`: Cancel immediately or at period end

  **Returns**: `Promise<Subscription>` - Cancelled subscription
</Expandable>

## Balance Service

### Credit Balance Management

The Balance Service handles all credit balance operations and calculations.

#### Get Balance

```typescript theme={null}
// Get current credit balance
const balance = await balanceService.getBalance(organizationId);
// Returns: { credits: 1500, currency: "USD", lastUpdated: "2024-01-15T10:00:00Z" }
```

#### Update Balance

```typescript theme={null}
// Update credit balance
await balanceService.updateBalance(
  organizationId,
  2000, // new balance
  "credit_purchase", // reason
  { transactionId: "txn_123" } // metadata
);
```

#### Consume Credits

```typescript theme={null}
// Consume credits for usage
const consumed = await balanceService.consumeCredits(
  organizationId,
  100, // amount to consume
  "message_sent", // reason
  { messageId: "msg_123", recipientId: "user_456" } // metadata
);
```

### Balance Operations

<Expandable title="getBalance(organizationId)">
  **Description**: Retrieves the current credit balance for an organization.

  **Parameters**:

  * `organizationId`: Organization ID

  **Returns**: `Promise<BalanceInfo>` - Current balance information
</Expandable>

<Expandable title="updateBalance(organizationId, newBalance, reason, metadata?)">
  **Description**: Updates the credit balance for an organization.

  **Parameters**:

  * `organizationId`: Organization ID
  * `newBalance`: New balance amount
  * `reason`: Reason for the update
  * `metadata`: Optional metadata

  **Returns**: `Promise<void>`
</Expandable>

<Expandable title="consumeCredits(organizationId, amount, reason, metadata?)">
  **Description**: Consumes credits from the organization's balance.

  **Parameters**:

  * `organizationId`: Organization ID
  * `amount`: Amount of credits to consume
  * `reason`: Reason for consumption
  * `metadata`: Optional metadata

  **Returns**: `Promise<boolean>` - Success status
</Expandable>

<Expandable title="addCredits(organizationId, amount, reason, metadata?)">
  **Description**: Adds credits to the organization's balance.

  **Parameters**:

  * `organizationId`: Organization ID
  * `amount`: Amount of credits to add
  * `reason`: Reason for adding credits
  * `metadata`: Optional metadata

  **Returns**: `Promise<void>`
</Expandable>

## Stripe Service

### Payment Processing Integration

The Stripe Service handles all Stripe API interactions and payment processing.

#### Create Customer

```typescript theme={null}
// Create a Stripe customer
const customer = await stripeService.createCustomer({
  email: "billing@acme.com",
  name: "Acme Corporation",
  organizationId: "org_123"
});
```

#### Create Payment Intent

```typescript theme={null}
// Create a payment intent for credit purchase
const paymentIntent = await stripeService.createPaymentIntent({
  amount: 5000, // $50.00 in cents
  currency: "usd",
  customerId: "cus_123",
  paymentMethodId: "pm_123",
  metadata: {
    type: "credit_purchase",
    organizationId: "org_123"
  }
});
```

#### Handle Webhook

```typescript theme={null}
// Process Stripe webhook events
const result = await stripeService.handleWebhook(
  webhookPayload,
  signature,
  webhookSecret
);
```

### Stripe Operations

<Expandable title="createCustomer(customerData)">
  **Description**: Creates a new Stripe customer.

  **Parameters**:

  * `customerData`: Customer information (email, name, organizationId)

  **Returns**: `Promise<StripeCustomer>` - Created customer
</Expandable>

<Expandable title="createPaymentIntent(intentData)">
  **Description**: Creates a payment intent for processing payments.

  **Parameters**:

  * `intentData`: Payment intent configuration

  **Returns**: `Promise<StripePaymentIntent>` - Created payment intent
</Expandable>

<Expandable title="createSetupIntent(customerId)">
  **Description**: Creates a setup intent for saving payment methods.

  **Parameters**:

  * `customerId`: Stripe customer ID

  **Returns**: `Promise<StripeSetupIntent>` - Created setup intent
</Expandable>

<Expandable title="attachPaymentMethod(paymentMethodId, customerId)">
  **Description**: Attaches a payment method to a customer.

  **Parameters**:

  * `paymentMethodId`: Payment method ID
  * `customerId`: Customer ID

  **Returns**: `Promise<StripePaymentMethod>` - Attached payment method
</Expandable>

<Expandable title="listPaymentMethods(customerId)">
  **Description**: Lists all payment methods for a customer.

  **Parameters**:

  * `customerId`: Customer ID

  **Returns**: `Promise<StripePaymentMethod[]>` - List of payment methods
</Expandable>

<Expandable title="deletePaymentMethod(paymentMethodId)">
  **Description**: Deletes a payment method.

  **Parameters**:

  * `paymentMethodId`: Payment method ID

  **Returns**: `Promise<void>`
</Expandable>

## Credit Service

### Credit Operations

The Credit Service handles credit purchasing, consumption tracking, and auto-refill operations.

#### Purchase Credits

```typescript theme={null}
// Purchase credits
const transaction = await creditService.purchaseCredits(
  organizationId,
  {
    amount: 5000, // $50.00 worth of credits
    paymentMethodId: "pm_123",
    description: "Credit purchase"
  }
);
```

#### Track Usage

```typescript theme={null}
// Track credit usage
await creditService.trackUsage(
  organizationId,
  {
    service: "messaging",
    action: "send_message",
    creditsUsed: 1,
    metadata: {
      messageId: "msg_123",
      recipientId: "user_456"
    }
  }
);
```

#### Configure Auto-Refill

```typescript theme={null}
// Configure automatic credit refill
await creditService.configureAutoRefill(
  organizationId,
  {
    enabled: true,
    threshold: 100, // Refill when balance drops below 100
    amount: 500, // Refill with 500 credits
    paymentMethodId: "pm_123"
  }
);
```

### Credit Operations

<Expandable title="purchaseCredits(organizationId, purchaseData)">
  **Description**: Purchases credits for an organization.

  **Parameters**:

  * `organizationId`: Organization ID
  * `purchaseData`: Purchase configuration

  **Returns**: `Promise<CreditTransaction>` - Purchase transaction
</Expandable>

<Expandable title="trackUsage(organizationId, usageData)">
  **Description**: Tracks credit usage for billing.

  **Parameters**:

  * `organizationId`: Organization ID
  * `usageData`: Usage information

  **Returns**: `Promise<void>`
</Expandable>

<Expandable title="configureAutoRefill(organizationId, config)">
  **Description**: Configures automatic credit refill.

  **Parameters**:

  * `organizationId`: Organization ID
  * `config`: Auto-refill configuration

  **Returns**: `Promise<void>`
</Expandable>

<Expandable title="getUsageHistory(organizationId, dateRange)">
  **Description**: Retrieves credit usage history.

  **Parameters**:

  * `organizationId`: Organization ID
  * `dateRange`: Date range for history

  **Returns**: `Promise<UsageHistory[]>` - Usage history
</Expandable>

## Invoice Service

### Invoice Management

The Invoice Service handles invoice generation, management, and retrieval.

#### Generate Invoice

```typescript theme={null}
// Generate invoice for billing period
const invoice = await invoiceService.generateInvoice(
  organizationId,
  {
    startDate: "2024-01-01",
    endDate: "2024-01-31",
    includeUsage: true,
    includeCredits: true
  }
);
```

#### Get Invoice

```typescript theme={null}
// Get invoice by ID
const invoice = await invoiceService.getInvoice(invoiceId);
```

#### List Invoices

```typescript theme={null}
// List all invoices for organization
const invoices = await invoiceService.listInvoices(organizationId, {
  page: 1,
  limit: 10,
  status: "paid"
});
```

### Invoice Operations

<Expandable title="generateInvoice(organizationId, options)">
  **Description**: Generates an invoice for a billing period.

  **Parameters**:

  * `organizationId`: Organization ID
  * `options`: Invoice generation options

  **Returns**: `Promise<Invoice>` - Generated invoice
</Expandable>

<Expandable title="getInvoice(invoiceId)">
  **Description**: Retrieves a specific invoice.

  **Parameters**:

  * `invoiceId`: Invoice ID

  **Returns**: `Promise<Invoice>` - Invoice details
</Expandable>

<Expandable title="listInvoices(organizationId, filters)">
  **Description**: Lists invoices for an organization.

  **Parameters**:

  * `organizationId`: Organization ID
  * `filters`: Filtering options

  **Returns**: `Promise<Invoice[]>` - List of invoices
</Expandable>

<Expandable title="sendInvoice(invoiceId, email?)">
  **Description**: Sends an invoice via email.

  **Parameters**:

  * `invoiceId`: Invoice ID
  * `email`: Optional email address

  **Returns**: `Promise<void>`
</Expandable>

## Message Usage Service

### Usage Tracking

The Message Usage Service tracks message usage and calculates billing costs.

#### Track Message

```typescript theme={null}
// Track message usage
await messageUsageService.trackMessage(
  organizationId,
  {
    messageId: "msg_123",
    type: "direct_message",
    platform: "facebook",
    recipientId: "user_456",
    creditsUsed: 1
  }
);
```

#### Get Usage Stats

```typescript theme={null}
// Get usage statistics
const stats = await messageUsageService.getUsageStats(
  organizationId,
  {
    startDate: "2024-01-01",
    endDate: "2024-01-31",
    groupBy: "day"
  }
);
```

#### Calculate Costs

```typescript theme={null}
// Calculate usage costs
const costs = await messageUsageService.calculateCosts(
  organizationId,
  {
    messageCount: 1000,
    messageType: "direct_message",
    platform: "facebook"
  }
);
```

### Usage Operations

<Expandable title="trackMessage(organizationId, messageData)">
  **Description**: Tracks a message for usage billing.

  **Parameters**:

  * `organizationId`: Organization ID
  * `messageData`: Message information

  **Returns**: `Promise<void>`
</Expandable>

<Expandable title="getUsageStats(organizationId, options)">
  **Description**: Retrieves usage statistics.

  **Parameters**:

  * `organizationId`: Organization ID
  * `options`: Statistics options

  **Returns**: `Promise<UsageStats>` - Usage statistics
</Expandable>

<Expandable title="calculateCosts(organizationId, usage)">
  **Description**: Calculates costs for usage.

  **Parameters**:

  * `organizationId`: Organization ID
  * `usage`: Usage information

  **Returns**: `Promise<CostCalculation>` - Cost calculation
</Expandable>

<Expandable title="getUsageHistory(organizationId, dateRange)">
  **Description**: Retrieves usage history.

  **Parameters**:

  * `organizationId`: Organization ID
  * `dateRange`: Date range

  **Returns**: `Promise<UsageHistory[]>` - Usage history
</Expandable>

## Integration Examples

### Complete Billing Setup Flow

```typescript theme={null}
// Complete billing setup workflow
async function setupCompleteBilling(organizationId: string, billingInfo: any) {
  try {
    // 1. Setup billing infrastructure
    const organization = await billingService.setupBillingForOrganization(
      organizationId,
      billingInfo.email,
      billingInfo.name
    );

    // 2. Add payment method
    await billingService.addPaymentMethod(
      organizationId,
      billingInfo.paymentMethodId
    );

    // 3. Create subscription
    const subscription = await billingService.createSubscription(
      organizationId,
      {
        planId: billingInfo.planId,
        paymentMethodId: billingInfo.paymentMethodId
      }
    );

    // 4. Configure auto-refill
    await creditService.configureAutoRefill(
      organizationId,
      {
        enabled: true,
        threshold: 100,
        amount: 500,
        paymentMethodId: billingInfo.paymentMethodId
      }
    );

    return {
      organization,
      subscription,
      success: true
    };
  } catch (error) {
    // Handle billing setup errors
    await billingService.cleanupBillingSetup(organizationId);
    throw error;
  }
}
```

### Credit Purchase Flow

```typescript theme={null}
// Credit purchase workflow
async function purchaseCredits(organizationId: string, purchaseData: any) {
  try {
    // 1. Create payment intent
    const paymentIntent = await stripeService.createPaymentIntent({
      amount: purchaseData.amount,
      currency: "usd",
      customerId: organization.stripeCustomerId,
      paymentMethodId: purchaseData.paymentMethodId,
      metadata: {
        type: "credit_purchase",
        organizationId
      }
    });

    // 2. Confirm payment
    const confirmedIntent = await stripeService.confirmPaymentIntent(
      paymentIntent.id
    );

    // 3. Add credits to balance
    await creditService.purchaseCredits(organizationId, {
      amount: purchaseData.amount,
      paymentMethodId: purchaseData.paymentMethodId,
      transactionId: confirmedIntent.id
    });

    // 4. Generate invoice
    const invoice = await invoiceService.generateInvoice(organizationId, {
      type: "credit_purchase",
      transactionId: confirmedIntent.id
    });

    return {
      transaction: confirmedIntent,
      invoice,
      success: true
    };
  } catch (error) {
    // Handle payment errors
    throw error;
  }
}
```

### Usage Tracking Flow

```typescript theme={null}
// Usage tracking workflow
async function trackMessageUsage(organizationId: string, messageData: any) {
  try {
    // 1. Check if organization has sufficient credits
    const balance = await balanceService.getBalance(organizationId);
    if (balance.credits < messageData.creditsRequired) {
      throw new InsufficientCreditsError("Not enough credits");
    }

    // 2. Track the message usage
    await messageUsageService.trackMessage(organizationId, messageData);

    // 3. Consume credits
    const consumed = await balanceService.consumeCredits(
      organizationId,
      messageData.creditsRequired,
      "message_sent",
      {
        messageId: messageData.messageId,
        platform: messageData.platform
      }
    );

    // 4. Check if auto-refill is needed
    const newBalance = await balanceService.getBalance(organizationId);
    if (newBalance.credits < 100) { // Auto-refill threshold
      await creditService.triggerAutoRefill(organizationId);
    }

    return {
      consumed,
      newBalance,
      success: true
    };
  } catch (error) {
    // Handle usage tracking errors
    throw error;
  }
}
```

## Error Handling

### Common Error Scenarios

<Expandable title="Payment Failures">
  ```typescript theme={null}
  try {
    const paymentIntent = await stripeService.createPaymentIntent(data);
  } catch (error) {
    if (error.code === 'card_declined') {
      throw new PaymentFailedError('Card was declined');
    } else if (error.code === 'insufficient_funds') {
      throw new PaymentFailedError('Insufficient funds');
    }
  }
  ```
</Expandable>

<Expandable title="Insufficient Credits">
  ```typescript theme={null}
  try {
    await balanceService.consumeCredits(organizationId, amount, reason);
  } catch (error) {
    if (error.code === 'INSUFFICIENT_CREDITS') {
      // Trigger auto-refill or notify user
      await creditService.triggerAutoRefill(organizationId);
      throw new InsufficientCreditsError('Credits refilled automatically');
    }
  }
  ```
</Expandable>

<Expandable title="Subscription Errors">
  ```typescript theme={null}
  try {
    const subscription = await billingService.createSubscription(orgId, data);
  } catch (error) {
    if (error.code === 'subscription_exists') {
      throw new ConflictError('Subscription already exists');
    } else if (error.code === 'invalid_plan') {
      throw new BadRequestError('Invalid plan selected');
    }
  }
  ```
</Expandable>

## Monitoring and Analytics

### Billing Metrics

```typescript theme={null}
// Track billing metrics
const metrics = {
  totalRevenue: await billingService.getTotalRevenue(organizationId),
  monthlyRecurringRevenue: await billingService.getMRR(organizationId),
  churnRate: await billingService.getChurnRate(organizationId),
  averageRevenuePerUser: await billingService.getARPU(organizationId),
  creditUtilization: await creditService.getUtilizationRate(organizationId)
};

await analyticsService.track('billing_metrics_updated', metrics);
```

### Usage Analytics

```typescript theme={null}
// Track usage analytics
const usageAnalytics = {
  totalMessages: await messageUsageService.getTotalMessages(organizationId),
  averageCostPerMessage: await messageUsageService.getAverageCost(organizationId),
  topPlatforms: await messageUsageService.getTopPlatforms(organizationId),
  peakUsageHours: await messageUsageService.getPeakUsageHours(organizationId)
};

await analyticsService.track('usage_analytics_updated', usageAnalytics);
```

## Security Considerations

### Payment Security

```typescript theme={null}
// Secure payment processing
const securePayment = await stripeService.createPaymentIntent({
  amount: amount,
  currency: 'usd',
  customerId: customerId,
  paymentMethodId: paymentMethodId,
  confirmationMethod: 'manual',
  confirm: true,
  returnUrl: 'https://app.vchata.com/payment/success'
});
```

### Data Protection

```typescript theme={null}
// Protect sensitive billing data
const protectedData = {
  organizationId: organizationId,
  amount: amount,
  currency: 'usd',
  // Never log sensitive payment information
  // paymentMethodId: '[REDACTED]'
};

await loggerService.log('payment_processed', protectedData);
```
