Skip to main content

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

POST /billing/setup
Authorization: Bearer <token>
Content-Type: application/json

{
  "email": "[email protected]",
  "name": "Acme Corporation"
}
{
  "success": true,
  "stripeCustomerId": "cus_1234567890",
  "billingEmail": "[email protected]",
  "organizationId": "org_abc123",
  "message": "Billing has been successfully configured for your organization"
}
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
body
object

Payment Methods

Add Payment Method

POST /billing/payment-method
Authorization: Bearer <token>
Content-Type: application/json

{
  "paymentMethodId": "pm_1234567890abcdef"
}
{
  "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"
}
Description: Attaches a payment method to the organization’s Stripe customer.
body
object

List Payment Methods

GET /billing/payment-methods
Authorization: Bearer <token>
{
  "paymentMethods": [
    {
      "id": "pm_1234567890abcdef",
      "type": "card",
      "card": {
        "brand": "visa",
        "last4": "4242",
        "expiryMonth": 12,
        "expiryYear": 2025,
        "funding": "credit",
        "country": "US"
      },
      "billingDetails": {
        "name": "John Doe",
        "email": "[email protected]",
        "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
}
Description: Retrieves all payment methods associated with the organization.

Delete Payment Method

DELETE /billing/payment-methods/pm_1234567890abcdef
Authorization: Bearer <token>
{
  "success": true,
  "message": "Payment method deleted successfully"
}
Description: Removes a payment method from the organization.

Set Default Payment Method

PUT /billing/payment-methods/pm_1234567890abcdef/default
Authorization: Bearer <token>
{
  "success": true,
  "message": "Default payment method updated successfully"
}
Description: Sets a payment method as the default for future charges.

Setup Intents

Create Setup Intent

POST /billing/setup-intent
Authorization: Bearer <token>
Content-Type: application/json

{}
{
  "success": true,
  "clientSecret": "seti_1234567890_secret_abcdef...",
  "message": "Setup intent created successfully"
}
Description: Creates a Stripe setup intent for adding payment methods without processing a charge.

Subscriptions

Get Subscription

GET /billing/subscription
Authorization: Bearer <token>
{
  "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"
}
Description: Retrieves the current subscription details for the organization.

Create Subscription

POST /billing/subscription
Authorization: Bearer <token>
Content-Type: application/json

{
  "planId": "plan_basic",
  "paymentMethodId": "pm_1234567890abcdef"
}
{
  "success": true,
  "subscription": {
    "id": "sub_1234567890",
    "status": "active",
    "currentPeriodStart": "2024-01-01T00:00:00Z",
    "currentPeriodEnd": "2024-02-01T00:00:00Z"
  },
  "message": "Subscription created successfully"
}
Description: Creates a new subscription for the organization.

Cancel Subscription

DELETE /billing/subscription
Authorization: Bearer <token>
{
  "success": true,
  "message": "Subscription will be cancelled at the end of the current period"
}
Description: Cancels the current subscription at the end of the billing period.

Pause Subscription

POST /billing/subscription/pause
Authorization: Bearer <token>
{
  "success": true,
  "message": "Subscription paused successfully"
}
Description: Pauses the current subscription.

Resume Subscription

POST /billing/subscription/resume
Authorization: Bearer <token>
{
  "success": true,
  "message": "Subscription resumed successfully"
}
Description: Resumes a paused subscription.

Credit Management

Get Balance

GET /billing/balance
Authorization: Bearer <token>
{
  "balance": {
    "credits": 1500,
    "currency": "USD",
    "lastUpdated": "2024-01-15T10:00:00Z"
  },
  "autoRefill": {
    "enabled": true,
    "threshold": 100,
    "amount": 500
  },
  "message": "Balance retrieved successfully"
}
Description: Retrieves the current credit balance and auto-refill settings.

Purchase Credits

POST /billing/credits/purchase
Authorization: Bearer <token>
Content-Type: application/json

{
  "amount": 1000,
  "paymentMethodId": "pm_1234567890abcdef"
}
{
  "success": true,
  "transaction": {
    "id": "txn_1234567890",
    "amount": 1000,
    "credits": 1000,
    "status": "succeeded"
  },
  "message": "Credits purchased successfully"
}
Description: Purchases credits using the organization’s payment method.

Usage Analytics

Get Usage

GET /billing/usage
Authorization: Bearer <token>
{
  "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"
}
Description: Retrieves detailed usage analytics for the current and previous billing periods.

Generate Usage Report

POST /billing/reports/usage
Authorization: Bearer <token>
Content-Type: application/json

{
  "startDate": "2024-01-01",
  "endDate": "2024-01-31",
  "format": "csv"
}
{
  "success": true,
  "reportUrl": "https://api.vchata.com/reports/usage_20240101_20240131.csv",
  "expiresAt": "2024-02-15T10:00:00Z",
  "message": "Usage report generated successfully"
}
Description: Generates a detailed usage report for the specified date range.

Transaction History

Get Transactions

GET /billing/transactions
Authorization: Bearer <token>
{
  "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"
}
Description: Retrieves transaction history for the organization.

Get Invoices

GET /billing/invoices
Authorization: Bearer <token>
{
  "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"
}
Description: Retrieves invoice history for the organization.

Auto-Refill Settings

Configure Auto-Refill

POST /billing/auto-refill/settings
Authorization: Bearer <token>
Content-Type: application/json

{
  "enabled": true,
  "threshold": 100,
  "amount": 500
}
{
  "success": true,
  "autoRefill": {
    "enabled": true,
    "threshold": 100,
    "amount": 500
  },
  "message": "Auto-refill settings updated successfully"
}
Description: Configures automatic credit refill settings.

Get Auto-Refill Settings

GET /billing/auto-refill/settings
Authorization: Bearer <token>
{
  "autoRefill": {
    "enabled": true,
    "threshold": 100,
    "amount": 500,
    "lastRefill": "2024-01-10T10:00:00Z",
    "nextRefill": null
  },
  "message": "Auto-refill settings retrieved successfully"
}
Description: Retrieves current auto-refill configuration.

Error Responses

Common Errors

{
  "success": false,
  "statusCode": 403,
  "message": "Only owners and admins can setup billing",
  "error": "Forbidden"
}
{
  "success": false,
  "statusCode": 409,
  "message": "Billing is already configured for this organization",
  "error": "Conflict"
}
{
  "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"
}
{
  "success": false,
  "statusCode": 502,
  "message": "Payment service temporarily unavailable. Please try again later.",
  "error": "Bad Gateway"
}

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