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
Show setupBillingForOrganization(organizationId, email, name)
Show setupBillingForOrganization(organizationId, email, name)
organizationId: Organization IDemail: Billing email addressname: Organization name
Promise<Organization> - Updated organization with billing infoShow addPaymentMethod(organizationId, paymentMethodId)
Show addPaymentMethod(organizationId, paymentMethodId)
organizationId: Organization IDpaymentMethodId: Stripe payment method ID
Promise<void>Show createSubscription(organizationId, options)
Show createSubscription(organizationId, options)
organizationId: Organization IDoptions: Subscription configuration
Promise<Subscription> - Created subscriptionShow updateSubscription(organizationId, updates)
Show updateSubscription(organizationId, updates)
organizationId: Organization IDupdates: Subscription updates
Promise<Subscription> - Updated subscriptionShow cancelSubscription(organizationId, immediate?)
Show cancelSubscription(organizationId, immediate?)
organizationId: Organization IDimmediate: Cancel immediately or at period end
Promise<Subscription> - Cancelled subscriptionBalance 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
Show getBalance(organizationId)
Show getBalance(organizationId)
organizationId: Organization ID
Promise<BalanceInfo> - Current balance informationShow updateBalance(organizationId, newBalance, reason, metadata?)
Show updateBalance(organizationId, newBalance, reason, metadata?)
organizationId: Organization IDnewBalance: New balance amountreason: Reason for the updatemetadata: Optional metadata
Promise<void>Show consumeCredits(organizationId, amount, reason, metadata?)
Show consumeCredits(organizationId, amount, reason, metadata?)
organizationId: Organization IDamount: Amount of credits to consumereason: Reason for consumptionmetadata: Optional metadata
Promise<boolean> - Success statusShow addCredits(organizationId, amount, reason, metadata?)
Show addCredits(organizationId, amount, reason, metadata?)
organizationId: Organization IDamount: Amount of credits to addreason: Reason for adding creditsmetadata: Optional metadata
Promise<void>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
Show createCustomer(customerData)
Show createCustomer(customerData)
customerData: Customer information (email, name, organizationId)
Promise<StripeCustomer> - Created customerShow createPaymentIntent(intentData)
Show createPaymentIntent(intentData)
intentData: Payment intent configuration
Promise<StripePaymentIntent> - Created payment intentShow createSetupIntent(customerId)
Show createSetupIntent(customerId)
customerId: Stripe customer ID
Promise<StripeSetupIntent> - Created setup intentShow attachPaymentMethod(paymentMethodId, customerId)
Show attachPaymentMethod(paymentMethodId, customerId)
paymentMethodId: Payment method IDcustomerId: Customer ID
Promise<StripePaymentMethod> - Attached payment methodShow listPaymentMethods(customerId)
Show listPaymentMethods(customerId)
customerId: Customer ID
Promise<StripePaymentMethod[]> - List of payment methodsShow deletePaymentMethod(paymentMethodId)
Show deletePaymentMethod(paymentMethodId)
paymentMethodId: Payment method ID
Promise<void>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
Show purchaseCredits(organizationId, purchaseData)
Show purchaseCredits(organizationId, purchaseData)
organizationId: Organization IDpurchaseData: Purchase configuration
Promise<CreditTransaction> - Purchase transactionShow trackUsage(organizationId, usageData)
Show trackUsage(organizationId, usageData)
organizationId: Organization IDusageData: Usage information
Promise<void>Show configureAutoRefill(organizationId, config)
Show configureAutoRefill(organizationId, config)
organizationId: Organization IDconfig: Auto-refill configuration
Promise<void>Show getUsageHistory(organizationId, dateRange)
Show getUsageHistory(organizationId, dateRange)
organizationId: Organization IDdateRange: Date range for history
Promise<UsageHistory[]> - Usage historyInvoice 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
Show generateInvoice(organizationId, options)
Show generateInvoice(organizationId, options)
organizationId: Organization IDoptions: Invoice generation options
Promise<Invoice> - Generated invoiceShow getInvoice(invoiceId)
Show getInvoice(invoiceId)
invoiceId: Invoice ID
Promise<Invoice> - Invoice detailsShow listInvoices(organizationId, filters)
Show listInvoices(organizationId, filters)
organizationId: Organization IDfilters: Filtering options
Promise<Invoice[]> - List of invoicesShow sendInvoice(invoiceId, email?)
Show sendInvoice(invoiceId, email?)
invoiceId: Invoice IDemail: Optional email address
Promise<void>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
Show trackMessage(organizationId, messageData)
Show trackMessage(organizationId, messageData)
organizationId: Organization IDmessageData: Message information
Promise<void>Show getUsageStats(organizationId, options)
Show getUsageStats(organizationId, options)
organizationId: Organization IDoptions: Statistics options
Promise<UsageStats> - Usage statisticsShow calculateCosts(organizationId, usage)
Show calculateCosts(organizationId, usage)
organizationId: Organization IDusage: Usage information
Promise<CostCalculation> - Cost calculationShow getUsageHistory(organizationId, dateRange)
Show getUsageHistory(organizationId, dateRange)
organizationId: Organization IDdateRange: Date range
Promise<UsageHistory[]> - Usage historyIntegration 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
Show Payment Failures
Show Payment Failures
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');
}
}
Show Insufficient Credits
Show Insufficient Credits
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');
}
}
Show Subscription Errors
Show Subscription Errors
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');
}
}
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);