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

> Complete billing, subscription, and payment management API endpoints

# Billing Controller

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

## Base Path

```
/billing
```

## Overview

This controller provides complete financial management capabilities:

* 💳 **Subscription Management** - Start, pause, cancel, and modify subscriptions
* 💰 **Credit Operations** - Purchase, refill, and auto-refill credit balances
* 🔒 **Payment Methods** - Secure payment method management (add, update, remove)
* 📊 **Usage Analytics** - Detailed usage analytics and reporting
* 🧾 **Transaction History** - Complete transaction and invoice history
* 📈 **Billing Insights** - Real-time billing insights and forecasting

## Authentication & Authorization

* 🔐 All endpoints require valid JWT authentication token
* 👥 Most operations restricted to OWNER or ADMIN roles
* 🏢 All operations scoped to user's current organization

## Rate Limiting

* 📊 Standard endpoints: 100 requests/minute per user
* 📈 Reporting endpoints: 20 requests/minute per user
* 💳 Payment operations: 10 requests/minute per user

## Billing Setup

### Setup Billing

<RequestExample>
  ```http theme={null}
  POST /billing/setup
  Authorization: Bearer <token>
  Content-Type: application/json

  {
    "email": "billing@acmecorp.com",
    "name": "Acme Corporation"
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "stripeCustomerId": "cus_1234567890",
    "billingEmail": "billing@acmecorp.com",
    "organizationId": "org_abc123",
    "message": "Billing has been successfully configured for your organization"
  }
  ```
</ResponseExample>

**Description**: Initializes billing infrastructure for an organization including Stripe customer creation.

**Requirements**:

* User must have OWNER or ADMIN role in the organization
* Organization must not already have billing setup
* Valid email and name are required for Stripe customer creation

<ParamField path="body" type="object">
  <Expandable title="Request Body">
    <ParamField path="email" type="string" required>
      Billing email address for the organization
    </ParamField>

    <ParamField path="name" type="string" required>
      Organization name for billing
    </ParamField>
  </Expandable>
</ParamField>

## Payment Methods

### Add Payment Method

<RequestExample>
  ```http theme={null}
  POST /billing/payment-method
  Authorization: Bearer <token>
  Content-Type: application/json

  {
    "paymentMethodId": "pm_1234567890abcdef"
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "paymentMethodId": "pm_1234567890abcdef",
    "brand": "visa",
    "last4": "4242",
    "expiryMonth": 12,
    "expiryYear": 2025,
    "isDefault": true,
    "message": "Payment method has been successfully added and set as default"
  }
  ```
</ResponseExample>

**Description**: Attaches a payment method to the organization's Stripe customer.

<ParamField path="body" type="object">
  <Expandable title="Request Body">
    <ParamField path="paymentMethodId" type="string" required>
      Stripe payment method ID (from PaymentElement)
    </ParamField>
  </Expandable>
</ParamField>

### List Payment Methods

<RequestExample>
  ```http theme={null}
  GET /billing/payment-methods
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "paymentMethods": [
      {
        "id": "pm_1234567890abcdef",
        "type": "card",
        "card": {
          "brand": "visa",
          "last4": "4242",
          "expiryMonth": 12,
          "expiryYear": 2025,
          "funding": "credit",
          "country": "US"
        },
        "billingDetails": {
          "name": "John Doe",
          "email": "john@acme.com",
          "phone": "+1234567890",
          "address": {
            "city": "San Francisco",
            "country": "US",
            "line1": "123 Main St",
            "line2": "Apt 4B",
            "postalCode": "94105",
            "state": "CA"
          }
        },
        "created": "2024-03-01T10:30:00Z",
        "isDefault": true
      }
    ],
    "defaultPaymentMethodId": "pm_1234567890abcdef",
    "total": 1
  }
  ```
</ResponseExample>

**Description**: Retrieves all payment methods associated with the organization.

### Delete Payment Method

<RequestExample>
  ```http theme={null}
  DELETE /billing/payment-methods/pm_1234567890abcdef
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "message": "Payment method deleted successfully"
  }
  ```
</ResponseExample>

**Description**: Removes a payment method from the organization.

### Set Default Payment Method

<RequestExample>
  ```http theme={null}
  PUT /billing/payment-methods/pm_1234567890abcdef/default
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "message": "Default payment method updated successfully"
  }
  ```
</ResponseExample>

**Description**: Sets a payment method as the default for future charges.

## Setup Intents

### Create Setup Intent

<RequestExample>
  ```http theme={null}
  POST /billing/setup-intent
  Authorization: Bearer <token>
  Content-Type: application/json

  {}
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "clientSecret": "seti_1234567890_secret_abcdef...",
    "message": "Setup intent created successfully"
  }
  ```
</ResponseExample>

**Description**: Creates a Stripe setup intent for adding payment methods without processing a charge.

## Subscriptions

### Get Subscription

<RequestExample>
  ```http theme={null}
  GET /billing/subscription
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "subscription": {
      "id": "sub_1234567890",
      "status": "active",
      "currentPeriodStart": "2024-01-01T00:00:00Z",
      "currentPeriodEnd": "2024-02-01T00:00:00Z",
      "plan": {
        "id": "plan_basic",
        "name": "Basic Plan",
        "amount": 2900,
        "currency": "usd",
        "interval": "month"
      },
      "nextBillingDate": "2024-02-01T00:00:00Z",
      "trialEnd": null,
      "cancelAtPeriodEnd": false
    },
    "message": "Subscription retrieved successfully"
  }
  ```
</ResponseExample>

**Description**: Retrieves the current subscription details for the organization.

### Create Subscription

<RequestExample>
  ```http theme={null}
  POST /billing/subscription
  Authorization: Bearer <token>
  Content-Type: application/json

  {
    "planId": "plan_basic",
    "paymentMethodId": "pm_1234567890abcdef"
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "subscription": {
      "id": "sub_1234567890",
      "status": "active",
      "currentPeriodStart": "2024-01-01T00:00:00Z",
      "currentPeriodEnd": "2024-02-01T00:00:00Z"
    },
    "message": "Subscription created successfully"
  }
  ```
</ResponseExample>

**Description**: Creates a new subscription for the organization.

### Cancel Subscription

<RequestExample>
  ```http theme={null}
  DELETE /billing/subscription
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "message": "Subscription will be cancelled at the end of the current period"
  }
  ```
</ResponseExample>

**Description**: Cancels the current subscription at the end of the billing period.

### Pause Subscription

<RequestExample>
  ```http theme={null}
  POST /billing/subscription/pause
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "message": "Subscription paused successfully"
  }
  ```
</ResponseExample>

**Description**: Pauses the current subscription.

### Resume Subscription

<RequestExample>
  ```http theme={null}
  POST /billing/subscription/resume
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "message": "Subscription resumed successfully"
  }
  ```
</ResponseExample>

**Description**: Resumes a paused subscription.

## Credit Management

### Get Balance

<RequestExample>
  ```http theme={null}
  GET /billing/balance
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "balance": {
      "credits": 1500,
      "currency": "USD",
      "lastUpdated": "2024-01-15T10:00:00Z"
    },
    "autoRefill": {
      "enabled": true,
      "threshold": 100,
      "amount": 500
    },
    "message": "Balance retrieved successfully"
  }
  ```
</ResponseExample>

**Description**: Retrieves the current credit balance and auto-refill settings.

### Purchase Credits

<RequestExample>
  ```http theme={null}
  POST /billing/credits/purchase
  Authorization: Bearer <token>
  Content-Type: application/json

  {
    "amount": 1000,
    "paymentMethodId": "pm_1234567890abcdef"
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "transaction": {
      "id": "txn_1234567890",
      "amount": 1000,
      "credits": 1000,
      "status": "succeeded"
    },
    "message": "Credits purchased successfully"
  }
  ```
</ResponseExample>

**Description**: Purchases credits using the organization's payment method.

## Usage Analytics

### Get Usage

<RequestExample>
  ```http theme={null}
  GET /billing/usage
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "usage": {
      "currentPeriod": {
        "startDate": "2024-01-01T00:00:00Z",
        "endDate": "2024-02-01T00:00:00Z",
        "messagesSent": 1250,
        "creditsUsed": 1250,
        "cost": 12.50
      },
      "previousPeriod": {
        "startDate": "2023-12-01T00:00:00Z",
        "endDate": "2024-01-01T00:00:00Z",
        "messagesSent": 980,
        "creditsUsed": 980,
        "cost": 9.80
      },
      "trends": {
        "messagesChange": "+27.6%",
        "costChange": "+27.6%"
      }
    },
    "message": "Usage data retrieved successfully"
  }
  ```
</ResponseExample>

**Description**: Retrieves detailed usage analytics for the current and previous billing periods.

### Generate Usage Report

<RequestExample>
  ```http theme={null}
  POST /billing/reports/usage
  Authorization: Bearer <token>
  Content-Type: application/json

  {
    "startDate": "2024-01-01",
    "endDate": "2024-01-31",
    "format": "csv"
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "reportUrl": "https://api.vchata.com/reports/usage_20240101_20240131.csv",
    "expiresAt": "2024-02-15T10:00:00Z",
    "message": "Usage report generated successfully"
  }
  ```
</ResponseExample>

**Description**: Generates a detailed usage report for the specified date range.

## Transaction History

### Get Transactions

<RequestExample>
  ```http theme={null}
  GET /billing/transactions
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "transactions": [
      {
        "id": "txn_1234567890",
        "type": "credit_purchase",
        "amount": 1000,
        "currency": "USD",
        "status": "succeeded",
        "description": "Credit purchase - 1000 credits",
        "createdAt": "2024-01-15T10:00:00Z",
        "paymentMethod": {
          "id": "pm_1234567890abcdef",
          "brand": "visa",
          "last4": "4242"
        }
      }
    ],
    "pagination": {
      "total": 1,
      "page": 1,
      "limit": 10,
      "hasMore": false
    },
    "message": "Transactions retrieved successfully"
  }
  ```
</ResponseExample>

**Description**: Retrieves transaction history for the organization.

### Get Invoices

<RequestExample>
  ```http theme={null}
  GET /billing/invoices
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "invoices": [
      {
        "id": "in_1234567890",
        "number": "INV-2024-001",
        "status": "paid",
        "amount": 29.00,
        "currency": "USD",
        "periodStart": "2024-01-01T00:00:00Z",
        "periodEnd": "2024-02-01T00:00:00Z",
        "dueDate": "2024-01-15T00:00:00Z",
        "paidAt": "2024-01-15T10:00:00Z",
        "downloadUrl": "https://api.vchata.com/invoices/in_1234567890.pdf"
      }
    ],
    "message": "Invoices retrieved successfully"
  }
  ```
</ResponseExample>

**Description**: Retrieves invoice history for the organization.

## Auto-Refill Settings

### Configure Auto-Refill

<RequestExample>
  ```http theme={null}
  POST /billing/auto-refill/settings
  Authorization: Bearer <token>
  Content-Type: application/json

  {
    "enabled": true,
    "threshold": 100,
    "amount": 500
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "autoRefill": {
      "enabled": true,
      "threshold": 100,
      "amount": 500
    },
    "message": "Auto-refill settings updated successfully"
  }
  ```
</ResponseExample>

**Description**: Configures automatic credit refill settings.

### Get Auto-Refill Settings

<RequestExample>
  ```http theme={null}
  GET /billing/auto-refill/settings
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "autoRefill": {
      "enabled": true,
      "threshold": 100,
      "amount": 500,
      "lastRefill": "2024-01-10T10:00:00Z",
      "nextRefill": null
    },
    "message": "Auto-refill settings retrieved successfully"
  }
  ```
</ResponseExample>

**Description**: Retrieves current auto-refill configuration.

## Error Responses

### Common Errors

<ResponseExample status="403">
  ```json theme={null}
  {
    "success": false,
    "statusCode": 403,
    "message": "Only owners and admins can setup billing",
    "error": "Forbidden"
  }
  ```
</ResponseExample>

<ResponseExample status="409">
  ```json theme={null}
  {
    "success": false,
    "statusCode": 409,
    "message": "Billing is already configured for this organization",
    "error": "Conflict"
  }
  ```
</ResponseExample>

<ResponseExample status="404">
  ```json theme={null}
  {
    "success": false,
    "statusCode": 404,
    "message": "Stripe customer not found. Please complete billing setup first.",
    "error": "Not Found",
    "suggestion": "Call POST /billing/setup to configure billing"
  }
  ```
</ResponseExample>

<ResponseExample status="502">
  ```json theme={null}
  {
    "success": false,
    "statusCode": 502,
    "message": "Payment service temporarily unavailable. Please try again later.",
    "error": "Bad Gateway"
  }
  ```
</ResponseExample>

## Integration Notes

* 💎 **Powered by Stripe** - Secure payment processing
* 🔢 **USD Currency** - All monetary amounts in USD with 2 decimal precision
* 📅 **ISO 8601 Timestamps** - All timestamps in UTC format
* 🏷️ **Metadata Tracking** - Comprehensive tracking for all operations
* 💯 **Atomic Operations** - All financial operations are atomic
* 🔄 **Automatic Retry** - Built-in retry mechanisms for transient failures
* 📝 **Audit Trails** - Complete audit trails for all billing activities
