saas-platform-billing-client
v1.3.1
Published
Billing client for SaaS platform billing-service
Maintainers
Readme
@saas-platform/billing-client
TypeScript/JavaScript client for SaaS platform billing service.
Features
- 💳 Payment Processing - Stripe and PayPal integration
- 🧾 Invoice Management - Create, send, and track invoices
- 👥 Customer Management - Customer data and payment methods
- 📊 Analytics - Payment and invoice reporting
- 🔐 Secure - JWT token authentication with automatic refresh
- 📦 TypeScript Support - Full type safety with Zod validation
Installation
npm install @saas-platform/billing-client @saas-platform/core-client @saas-platform/auth-clientBasic Usage
import { AuthClient } from '@saas-platform/auth-client';
import { BillingClient } from '@saas-platform/billing-client';
// Setup authentication
const authClient = new AuthClient({
saasId: 'your-saas-id',
authServiceUrl: 'http://localhost:8000'
});
// Login to get tokens
await authClient.login({
email: '[email protected]',
password: 'password123',
saasId: 'your-saas-id'
});
// Create billing client with auth manager
const billingClient = new BillingClient({
saasId: 'your-saas-id',
authServiceUrl: 'http://localhost:8000',
billingServiceUrl: 'http://localhost:8002'
}, authClient.authManager);Payment Management
Create Payment
const payment = await billingClient.createPayment({
amount: 29.99,
currency: 'USD',
description: 'Monthly subscription',
provider: 'stripe',
metadata: {
subscriptionId: 'sub-123',
planName: 'Premium'
}
});
if (payment.success) {
console.log('Payment created:', payment.data?.id);
}Process Payment
const processed = await billingClient.processPayment({
paymentId: 'payment-uuid',
paymentMethodId: 'pm_1234567890'
});
if (processed.success) {
console.log('Payment status:', processed.data?.status);
}Get Payments
const payments = await billingClient.getPayments({
status: 'completed',
startDate: '2024-01-01',
endDate: '2024-12-31',
page: 1,
pageSize: 20,
sortBy: 'createdAt',
sortOrder: 'desc'
});
if (payments.success) {
console.log('Total payments:', payments.data?.pagination.totalItems);
payments.data?.items.forEach(payment => {
console.log(`${payment.description}: ${payment.amount} ${payment.currency}`);
});
}Invoice Management
Create Invoice
const invoice = await billingClient.createInvoice({
customerId: 'customer-uuid',
amount: 199.99,
currency: 'USD',
description: 'Annual subscription',
dueDate: '2024-02-01T00:00:00Z',
items: [
{
description: 'Annual Premium Plan',
quantity: 1,
unitPrice: 199.99,
total: 199.99
}
]
});
if (invoice.success) {
console.log('Invoice created:', invoice.data?.invoiceNumber);
}Send Invoice
const sent = await billingClient.sendInvoice('invoice-uuid');
if (sent.success) {
console.log('Invoice sent to customer');
}Download Invoice PDF
const pdf = await billingClient.downloadInvoicePdf('invoice-uuid');
if (pdf.success) {
// Handle PDF blob
const url = URL.createObjectURL(pdf.data);
window.open(url);
}Customer Management
Create Customer
const customer = await billingClient.createCustomer({
email: '[email protected]',
name: 'John Doe',
phone: '+1234567890',
address: {
street: '123 Main St',
city: 'New York',
state: 'NY',
country: 'US',
zipCode: '10001'
},
paymentMethods: [],
isActive: true
});Get Customers
const customers = await billingClient.getCustomers(1, 50);
if (customers.success) {
customers.data?.items.forEach(customer => {
console.log(`${customer.name} (${customer.email})`);
});
}Analytics
Payment Summary
const summary = await billingClient.getPaymentSummary(
'2024-01-01',
'2024-12-31'
);
if (summary.success) {
console.log('Total Revenue:', summary.data?.totalRevenue);
console.log('Successful Payments:', summary.data?.successfulPayments);
console.log('Average Payment:', summary.data?.averagePaymentAmount);
}Invoice Summary
const invoiceSummary = await billingClient.getInvoiceSummary(
'2024-01-01',
'2024-12-31'
);
if (invoiceSummary.success) {
console.log('Total Invoices:', invoiceSummary.data?.totalInvoices);
console.log('Paid Amount:', invoiceSummary.data?.paidAmount);
console.log('Overdue Amount:', invoiceSummary.data?.overdueAmount);
}Webhook Handling
Stripe Webhooks
// In your webhook endpoint
app.post('/webhooks/stripe', async (req, res) => {
const signature = req.headers['stripe-signature'];
const result = await billingClient.handleStripeWebhook(
req.body,
signature
);
if (result.success) {
res.status(200).send('OK');
} else {
res.status(400).send('Webhook processing failed');
}
});Error Handling
All methods return a standardized response:
const response = await billingClient.createPayment(paymentData);
if (!response.success) {
console.error('Payment creation failed:', response.error?.message);
switch (response.error?.code) {
case 'INSUFFICIENT_FUNDS':
// Handle insufficient funds
break;
case 'INVALID_PAYMENT_METHOD':
// Handle invalid payment method
break;
case 'NETWORK_ERROR':
// Handle connection issues
break;
}
}Payment Statuses
enum PaymentStatus {
Pending = 'pending',
Processing = 'processing',
Completed = 'completed',
Failed = 'failed',
Cancelled = 'cancelled',
Refunded = 'refunded'
}Invoice Statuses
enum InvoiceStatus {
Draft = 'draft',
Sent = 'sent',
Paid = 'paid',
Overdue = 'overdue',
Cancelled = 'cancelled'
}Health Check
const health = await billingClient.getHealth();
if (health.success) {
console.log('Service status:', health.data?.status);
console.log('Dependencies:', health.data?.dependencies);
}License
MIT
