Skip to main content

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

// Setup billing for a new organization
const organization = await billingService.setupBillingForOrganization(
  organizationId,
  "[email protected]",
  "Acme Corporation"
);

Add Payment Method

// Add a payment method to organization
await billingService.addPaymentMethod(
  organizationId,
  "pm_1234567890abcdef"
);

Create Subscription

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

Available Methods

Balance Service

Credit Balance Management

The Balance Service handles all credit balance operations and calculations.

Get Balance

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

Update Balance

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

Consume Credits

// 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

Stripe Service

Payment Processing Integration

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

Create Customer

// Create a Stripe customer
const customer = await stripeService.createCustomer({
  email: "[email protected]",
  name: "Acme Corporation",
  organizationId: "org_123"
});

Create Payment Intent

// 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

// Process Stripe webhook events
const result = await stripeService.handleWebhook(
  webhookPayload,
  signature,
  webhookSecret
);

Stripe Operations

Credit Service

Credit Operations

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

Purchase Credits

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

Track Usage

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

Configure Auto-Refill

// 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

Invoice Service

Invoice Management

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

Generate Invoice

// 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

// Get invoice by ID
const invoice = await invoiceService.getInvoice(invoiceId);

List Invoices

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

Invoice Operations

Message Usage Service

Usage Tracking

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

Track Message

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

Get Usage Stats

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

Calculate Costs

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

Usage Operations

Integration Examples

Complete Billing Setup Flow

// 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

// 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

// 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

Monitoring and Analytics

Billing Metrics

// 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

// 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

// 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

// 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);