# Chargebee Node.js / TypeScript SDK Chargebee is a comprehensive subscription billing and revenue management platform. This official Node.js/TypeScript SDK provides a type-safe interface for integrating Chargebee's billing APIs into your applications. The SDK supports multiple JavaScript runtimes including Node.js 18+, Deno, Bun, Cloudflare Workers, and Edge Functions, making it versatile for modern application architectures. The SDK offers complete coverage of Chargebee's billing features including customer management, subscription lifecycle handling, invoicing, payment processing, hosted checkout pages, usage-based billing, quotes, credit notes, and webhook event handling. All API methods return strongly-typed responses and support both promise-based async/await patterns and custom HTTP headers for advanced use cases. ## Initializing the Chargebee Client The `createChargebee` function creates a configured Chargebee client instance with your site credentials. The client provides access to all Chargebee resources through a unified interface. ```typescript import { createChargebee } from 'chargebee'; // Initialize the Chargebee client const chargebee = createChargebee({ site: 'your-site', // Your Chargebee site name apiKey: 'your-api-key', // Your Chargebee API key }); // Access resources through the client const { customer } = await chargebee.customer.retrieve('cust_123'); console.log('Customer:', customer.first_name, customer.email); ``` ## Customer Management The Customer resource allows you to create, retrieve, update, and manage customer records. Customers are the foundation of your subscription billing system. ```typescript import { createChargebee } from 'chargebee'; const chargebee = createChargebee({ site: 'your-site', apiKey: 'your-api-key', }); // Create a new customer const { customer } = await chargebee.customer.create({ id: 'cust_123', first_name: 'John', last_name: 'Doe', email: 'john.doe@example.com', phone: '+1-555-123-4567', billing_address: { first_name: 'John', last_name: 'Doe', line1: '123 Main Street', city: 'San Francisco', state_code: 'CA', zip: '94105', country: 'US', }, }); console.log('Created customer:', customer.id); // Update an existing customer const { customer: updatedCustomer } = await chargebee.customer.update('cust_123', { company: 'Acme Inc', auto_collection: 'on', }); // List customers with filtering const { list } = await chargebee.customer.list({ limit: 10, 'email[is]': 'john.doe@example.com', 'created_at[after]': Math.floor(Date.now() / 1000) - 86400 * 30, // Last 30 days }); for (const item of list) { console.log('Customer:', item.customer.id, item.customer.email); } // Delete a customer await chargebee.customer.delete('cust_123'); ``` ## Subscription Creation and Management The Subscription resource handles the complete subscription lifecycle including creation, updates, cancellation, pause/resume, and billing cycle management. ```typescript import { createChargebee } from 'chargebee'; const chargebee = createChargebee({ site: 'your-site', apiKey: 'your-api-key', }); // Create a subscription with item prices (Product Catalog 2.0) const { subscription, customer, invoice } = await chargebee.subscription.createWithItems( 'cust_123', { subscription_items: [ { item_price_id: 'pro-plan-USD-monthly', quantity: 1, }, { item_price_id: 'addon-extra-users-USD-monthly', quantity: 5, }, ], billing_cycles: 12, auto_collection: 'on', coupon_ids: ['WELCOME20'], } ); console.log('Subscription created:', subscription.id); console.log('Status:', subscription.status); console.log('Current term end:', new Date(subscription.current_term_end * 1000)); // Update subscription items const { subscription: updated } = await chargebee.subscription.updateForItems( subscription.id, { subscription_items: [ { item_price_id: 'pro-plan-USD-monthly', quantity: 1, }, { item_price_id: 'addon-extra-users-USD-monthly', quantity: 10, // Increase from 5 to 10 users }, ], prorate: true, } ); // Cancel subscription at term end const { subscription: cancelled } = await chargebee.subscription.cancelForItems( subscription.id, { cancel_option: 'end_of_term', cancel_reason_code: 'not_using', } ); // Pause a subscription const { subscription: paused } = await chargebee.subscription.pause(subscription.id, { pause_option: 'immediately', unbilled_charges_handling: 'invoice', }); // Resume a paused subscription const { subscription: resumed } = await chargebee.subscription.resume(subscription.id, { resume_option: 'immediately', }); // List subscriptions with filters const { list } = await chargebee.subscription.list({ limit: 20, 'status[in]': '["active", "in_trial"]', 'customer_id[is]': 'cust_123', }); for (const item of list) { console.log('Subscription:', item.subscription.id, item.subscription.status); } ``` ## Invoice Operations The Invoice resource provides comprehensive invoice management including creation, retrieval, payment collection, refunds, and PDF generation. ```typescript import { createChargebee } from 'chargebee'; const chargebee = createChargebee({ site: 'your-site', apiKey: 'your-api-key', }); // Create a one-time invoice with charge items const { invoice } = await chargebee.invoice.createForChargeItemsAndCharges({ customer_id: 'cust_123', currency_code: 'USD', item_prices: [ { item_price_id: 'setup-fee-USD', quantity: 1, }, ], charges: [ { amount: 5000, // $50.00 in cents description: 'Professional services', taxable: true, }, ], auto_collection: 'on', }); console.log('Invoice created:', invoice.id); console.log('Total:', invoice.total / 100, invoice.currency_code); console.log('Status:', invoice.status); // Retrieve an invoice const { invoice: retrieved } = await chargebee.invoice.retrieve('inv_123'); console.log('Line items:', retrieved.line_items?.length); // Collect payment on a pending invoice const { invoice: collected, transaction } = await chargebee.invoice.collectPayment('inv_123', { payment_source_id: 'pm_card_123', }); console.log('Payment status:', transaction.status); // Record an offline payment const { invoice: paid } = await chargebee.invoice.recordPayment('inv_123', { transaction: { amount: 10000, // $100.00 payment_method: 'cash', date: Math.floor(Date.now() / 1000), reference_number: 'CHECK-12345', }, }); // Issue a refund const { invoice: refunded, credit_note } = await chargebee.invoice.refund('inv_123', { refund_amount: 5000, // $50.00 credit_note: { reason_code: 'service_unsatisfactory', }, }); // Generate invoice PDF const { download } = await chargebee.invoice.pdf('inv_123'); console.log('PDF URL:', download.download_url); // List invoices with filters const { list } = await chargebee.invoice.list({ limit: 10, 'status[in]': '["paid", "payment_due"]', 'customer_id[is]': 'cust_123', 'sort_by[desc]': 'date', }); for (const item of list) { console.log('Invoice:', item.invoice.id, item.invoice.status, item.invoice.total); } // Void an invoice const { invoice: voided } = await chargebee.invoice.voidInvoice('inv_123', { void_reason_code: 'duplicate', }); ``` ## Payment Source Management The PaymentSource resource manages customer payment methods including credit cards, bank accounts, and various payment types like PayPal, Apple Pay, and Google Pay. ```typescript import { createChargebee } from 'chargebee'; const chargebee = createChargebee({ site: 'your-site', apiKey: 'your-api-key', }); // Create a payment source using a payment gateway token const { payment_source, customer } = await chargebee.paymentSource.createUsingToken({ customer_id: 'cust_123', token_id: 'tok_stripe_xxxxx', // Token from Stripe.js or similar replace_primary_payment_source: true, }); console.log('Payment source created:', payment_source.id); console.log('Card brand:', payment_source.card?.brand); console.log('Last 4:', payment_source.card?.last4); // Create a card payment source directly (PCI-compliant environments only) const { payment_source: cardSource } = await chargebee.paymentSource.createCard({ customer_id: 'cust_123', card: { gateway_account_id: 'gw_stripe', number: '4111111111111111', expiry_month: 12, expiry_year: 2025, cvv: '123', first_name: 'John', last_name: 'Doe', billing_country: 'US', billing_zip: '94105', }, }); // Create a bank account payment source const { payment_source: bankSource } = await chargebee.paymentSource.createBankAccount({ customer_id: 'cust_123', bank_account: { gateway_account_id: 'gw_stripe_ach', first_name: 'John', last_name: 'Doe', account_number: '000123456789', routing_number: '110000000', account_type: 'checking', account_holder_type: 'individual', }, }); // Update card details const { payment_source: updated } = await chargebee.paymentSource.updateCard('pm_123', { card: { expiry_month: 6, expiry_year: 2026, }, }); // List payment sources for a customer const { list } = await chargebee.paymentSource.list({ 'customer_id[is]': 'cust_123', 'status[is]': 'valid', }); for (const item of list) { console.log('Payment source:', item.payment_source.id, item.payment_source.type); } // Delete a payment source await chargebee.paymentSource.delete('pm_123'); ``` ## Hosted Pages for Checkout Hosted Pages provide secure, PCI-compliant checkout experiences. Use them for new subscriptions, updating payment methods, and managing customer billing. ```typescript import { createChargebee } from 'chargebee'; const chargebee = createChargebee({ site: 'your-site', apiKey: 'your-api-key', }); // Create a checkout page for a new subscription const { hosted_page } = await chargebee.hostedPage.checkoutNewForItems({ subscription_items: [ { item_price_id: 'pro-plan-USD-monthly', quantity: 1, }, ], customer: { email: 'newuser@example.com', first_name: 'Jane', last_name: 'Smith', }, billing_address: { country: 'US', }, redirect_url: 'https://yoursite.com/checkout/success', cancel_url: 'https://yoursite.com/checkout/cancel', pass_thru_content: JSON.stringify({ referrer: 'landing-page-a' }), }); console.log('Checkout URL:', hosted_page.url); console.log('Expires at:', new Date(hosted_page.expires_at * 1000)); // Create a checkout for an existing customer to update their subscription const { hosted_page: updatePage } = await chargebee.hostedPage.checkoutExistingForItems({ subscription: { id: 'sub_123', }, subscription_items: [ { item_price_id: 'enterprise-plan-USD-monthly', quantity: 1, }, ], redirect_url: 'https://yoursite.com/upgrade/success', cancel_url: 'https://yoursite.com/upgrade/cancel', }); // Create a page to update payment method const { hosted_page: paymentPage } = await chargebee.hostedPage.updatePaymentMethod({ customer: { id: 'cust_123', }, redirect_url: 'https://yoursite.com/payment/updated', cancel_url: 'https://yoursite.com/payment/cancel', }); // Create a page to collect outstanding payments const { hosted_page: collectPage } = await chargebee.hostedPage.collectNow({ customer: { id: 'cust_123', }, redirect_url: 'https://yoursite.com/payment/success', }); // Retrieve hosted page state after redirect const { hosted_page: completed } = await chargebee.hostedPage.retrieve('hp_123'); if (completed.state === 'succeeded') { const content = completed.content; console.log('Subscription:', content.subscription?.id); console.log('Customer:', content.customer?.id); console.log('Invoice:', content.invoice?.id); // Acknowledge the hosted page await chargebee.hostedPage.acknowledge('hp_123'); } ``` ## Portal Sessions for Self-Service Portal Sessions enable customers to access the Chargebee Self-Service Portal to manage their subscriptions, payment methods, and billing history. ```typescript import { createChargebee } from 'chargebee'; const chargebee = createChargebee({ site: 'your-site', apiKey: 'your-api-key', }); // Create a portal session for a customer const { portal_session } = await chargebee.portalSession.create({ customer: { id: 'cust_123', }, redirect_url: 'https://yoursite.com/account', }); console.log('Portal URL:', portal_session.access_url); console.log('Session token:', portal_session.token); console.log('Expires at:', new Date(portal_session.expires_at * 1000)); // Redirect the customer to the portal // res.redirect(portal_session.access_url); // Retrieve a portal session status const { portal_session: session } = await chargebee.portalSession.retrieve('ps_123'); console.log('Session status:', session.status); // Logout a portal session const { portal_session: loggedOut } = await chargebee.portalSession.logout('ps_123'); ``` ## Usage-Based Billing The Usage resource tracks metered usage for subscription items with usage-based pricing models. ```typescript import { createChargebee } from 'chargebee'; const chargebee = createChargebee({ site: 'your-site', apiKey: 'your-api-key', }); // Record usage for a subscription const { usage } = await chargebee.usage.create('sub_123', { item_price_id: 'api-calls-USD-monthly', quantity: '1500', usage_date: Math.floor(Date.now() / 1000), note: 'API calls for the day', dedupe_option: 'increment', // Add to existing usage for the day }); console.log('Usage recorded:', usage.id); console.log('Quantity:', usage.quantity); // Retrieve usage record const { usage: retrieved } = await chargebee.usage.retrieve('sub_123', { id: usage.id, }); // List usage records const { list } = await chargebee.usage.list({ 'subscription_id[is]': 'sub_123', 'item_price_id[is]': 'api-calls-USD-monthly', 'usage_date[between]': `[${startTimestamp}, ${endTimestamp}]`, 'sort_by[desc]': 'usage_date', }); for (const item of list) { console.log('Date:', new Date(item.usage.usage_date * 1000)); console.log('Quantity:', item.usage.quantity); } // Delete a usage record await chargebee.usage.delete('sub_123', { id: usage.id, }); ``` ## Estimates and Pricing Preview The Estimate resource allows you to preview subscription costs, renewal charges, and invoice totals before committing changes. ```typescript import { createChargebee } from 'chargebee'; const chargebee = createChargebee({ site: 'your-site', apiKey: 'your-api-key', }); // Estimate a new subscription const { estimate } = await chargebee.estimate.createSubItemEstimate({ subscription_items: [ { item_price_id: 'pro-plan-USD-monthly', quantity: 1, }, { item_price_id: 'addon-storage-USD-monthly', quantity: 100, }, ], coupon_ids: ['FIRST50'], billing_address: { country: 'US', state_code: 'CA', }, }); console.log('Estimated invoice:'); console.log('Subtotal:', estimate.invoice_estimate?.sub_total); console.log('Tax:', estimate.invoice_estimate?.taxes?.reduce((sum, t) => sum + t.amount, 0)); console.log('Total:', estimate.invoice_estimate?.total); // Estimate subscription renewal const { estimate: renewalEstimate } = await chargebee.estimate.renewalEstimate('sub_123', { include_delayed_charges: true, }); console.log('Next renewal total:', renewalEstimate.invoice_estimate?.total); console.log('Next billing date:', new Date(renewalEstimate.subscription_estimate?.next_billing_at * 1000)); // Estimate subscription update/upgrade const { estimate: updateEstimate } = await chargebee.estimate.updateSubscriptionForItems({ subscription: { id: 'sub_123', }, subscription_items: [ { item_price_id: 'enterprise-plan-USD-monthly', quantity: 1, }, ], prorate: true, }); console.log('Prorated charge:', updateEstimate.invoice_estimate?.total); // Estimate cancellation const { estimate: cancelEstimate } = await chargebee.estimate.cancelSubscriptionForItems('sub_123', { cancel_option: 'end_of_term', }); if (cancelEstimate.credit_note_estimates?.length > 0) { console.log('Credit note amount:', cancelEstimate.credit_note_estimates[0].total); } ``` ## Coupons and Discounts The Coupon resource enables you to create and manage promotional discounts for your subscriptions and invoices. ```typescript import { createChargebee } from 'chargebee'; const chargebee = createChargebee({ site: 'your-site', apiKey: 'your-api-key', }); // Create a percentage discount coupon const { coupon } = await chargebee.coupon.createForItems({ id: 'SUMMER2024', name: 'Summer Sale 2024', discount_type: 'percentage', discount_percentage: 25, duration_type: 'limited_period', duration_month: 3, apply_on: 'invoice_amount', valid_till: Math.floor(new Date('2024-09-30').getTime() / 1000), max_redemptions: 1000, item_constraints: [ { item_type: 'plan', constraint: 'all', }, ], }); console.log('Coupon created:', coupon.id); // Create a fixed amount discount coupon const { coupon: fixedCoupon } = await chargebee.coupon.createForItems({ id: 'FLAT50', name: '$50 Off First Month', discount_type: 'fixed_amount', discount_amount: 5000, // $50.00 in cents currency_code: 'USD', duration_type: 'one_time', apply_on: 'invoice_amount', coupon_constraints: [ { entity_type: 'customer', type: 'new_customer', }, ], }); // Retrieve a coupon const { coupon: retrieved } = await chargebee.coupon.retrieve('SUMMER2024'); console.log('Redemptions:', retrieved.redemptions, '/', retrieved.max_redemptions); // List active coupons const { list } = await chargebee.coupon.list({ 'status[is]': 'active', 'discount_type[in]': '["percentage", "fixed_amount"]', }); for (const item of list) { console.log('Coupon:', item.coupon.id, item.coupon.name); } // Archive a coupon await chargebee.coupon.delete('EXPIRED_PROMO'); ``` ## Quotes The Quote resource allows you to create sales quotes for customers that can be converted to subscriptions or invoices upon acceptance. ```typescript import { createChargebee } from 'chargebee'; const chargebee = createChargebee({ site: 'your-site', apiKey: 'your-api-key', }); // Create a quote for a new subscription const { quote } = await chargebee.quote.createSubItemsForCustomerQuote('cust_123', { name: 'Enterprise Plan Quote', subscription_items: [ { item_price_id: 'enterprise-plan-USD-annual', quantity: 1, }, { item_price_id: 'addon-premium-support-USD-annual', quantity: 1, }, ], discounts: [ { apply_on: 'invoice_amount', duration_type: 'one_time', percentage: 10, }, ], valid_till: Math.floor(Date.now() / 1000) + 30 * 86400, // Valid for 30 days }); console.log('Quote created:', quote.id); console.log('Total:', quote.total); console.log('Valid until:', new Date(quote.valid_till * 1000)); // Generate quote PDF const { download } = await chargebee.quote.pdf(quote.id); console.log('Quote PDF:', download.download_url); // Convert quote to subscription when customer accepts const { subscription, invoice, customer } = await chargebee.quote.convert(quote.id, { subscription: { auto_collection: 'on', }, }); console.log('Quote converted to subscription:', subscription.id); // List quotes const { list } = await chargebee.quote.list({ 'status[in]': '["open", "accepted"]', 'customer_id[is]': 'cust_123', }); for (const item of list) { console.log('Quote:', item.quote.id, item.quote.status, item.quote.total); } ``` ## Credit Notes The CreditNote resource manages refundable credits, adjustments, and store credits for customers. ```typescript import { createChargebee } from 'chargebee'; const chargebee = createChargebee({ site: 'your-site', apiKey: 'your-api-key', }); // Create a credit note for an invoice const { credit_note, invoice } = await chargebee.creditNote.create({ reference_invoice_id: 'inv_123', type: 'refundable', reason_code: 'service_unsatisfactory', total: 2500, // $25.00 customer_notes: 'Service credit for downtime', line_items: [ { reference_line_item_id: 'li_123', unit_amount: 2500, quantity: 1, description: 'Service credit', }, ], }); console.log('Credit note created:', credit_note.id); console.log('Amount:', credit_note.total); console.log('Status:', credit_note.status); // Retrieve a credit note const { credit_note: retrieved } = await chargebee.creditNote.retrieve('cn_123'); // Refund a credit note const { credit_note: refunded, transaction } = await chargebee.creditNote.refund('cn_123', { refund_amount: 2500, customer_notes: 'Refund processed', }); console.log('Refund transaction:', transaction.id); console.log('Transaction status:', transaction.status); // Generate credit note PDF const { download } = await chargebee.creditNote.pdf('cn_123'); console.log('PDF URL:', download.download_url); // List credit notes const { list } = await chargebee.creditNote.list({ 'customer_id[is]': 'cust_123', 'status[in]': '["refund_due", "adjusted"]', 'sort_by[desc]': 'date', }); for (const item of list) { console.log('Credit note:', item.credit_note.id, item.credit_note.total); } // Void a credit note const { credit_note: voided } = await chargebee.creditNote.voidCreditNote('cn_123', { comment: 'Voided per customer request', }); ``` ## Items and Item Prices (Product Catalog) Items and ItemPrices form the Product Catalog 2.0, allowing flexible pricing configurations for plans, add-ons, and one-time charges. ```typescript import { createChargebee } from 'chargebee'; const chargebee = createChargebee({ site: 'your-site', apiKey: 'your-api-key', }); // Create an item (product) const { item } = await chargebee.item.create({ id: 'pro-plan', name: 'Pro Plan', type: 'plan', description: 'Professional plan with advanced features', item_family_id: 'subscription-plans', enabled_for_checkout: true, enabled_in_portal: true, metered: false, }); console.log('Item created:', item.id); // Create an item price (pricing variant) const { item_price } = await chargebee.itemPrice.create({ id: 'pro-plan-USD-monthly', name: 'Pro Plan - Monthly', item_id: 'pro-plan', pricing_model: 'flat_fee', price: 4900, // $49.00 currency_code: 'USD', period: 1, period_unit: 'month', trial_period: 14, trial_period_unit: 'day', }); console.log('Item price created:', item_price.id); // Create tiered pricing const { item_price: tieredPrice } = await chargebee.itemPrice.create({ id: 'api-calls-USD-monthly', name: 'API Calls - Monthly', item_id: 'api-calls', pricing_model: 'tiered', currency_code: 'USD', period: 1, period_unit: 'month', tiers: [ { starting_unit: 1, ending_unit: 1000, price: 0 }, // First 1000 free { starting_unit: 1001, ending_unit: 10000, price: 10 }, // $0.10 per call { starting_unit: 10001, price: 5 }, // $0.05 per call ], }); // List item prices const { list } = await chargebee.itemPrice.list({ 'item_id[is]': 'pro-plan', 'status[is]': 'active', 'currency_code[is]': 'USD', }); for (const { item_price } of list) { console.log('Price:', item_price.id, item_price.price, item_price.currency_code); } // Update an item price const { item_price: updated } = await chargebee.itemPrice.update('pro-plan-USD-monthly', { price: 5900, // New price: $59.00 trial_period: 7, // Reduce trial to 7 days }); ``` ## Webhook Event Handling The SDK provides a built-in webhook handler for processing Chargebee events with authentication support, type-safe event handling, and framework integration. ```typescript import express from 'express'; import { createHandler, basicAuthValidator } from 'chargebee/webhook'; const app = express(); app.use(express.json()); // Create webhook handler with Basic Auth const webhookHandler = createHandler({ requestValidator: basicAuthValidator((username, password) => { return username === process.env.CHARGEBEE_WEBHOOK_USERNAME && password === process.env.CHARGEBEE_WEBHOOK_PASSWORD; }), }); // Register event handlers (do this ONCE at startup, not per-request) webhookHandler.on('subscription_created', async ({ event, response }) => { const subscription = event.content.subscription; const customer = event.content.customer; console.log('New subscription:', subscription.id); console.log('Customer:', customer.email); // Process the subscription (e.g., provision access, send welcome email) await provisionSubscription(subscription, customer); response?.status(200).send('OK'); }); webhookHandler.on('subscription_cancelled', async ({ event, response }) => { const subscription = event.content.subscription; console.log('Subscription cancelled:', subscription.id); console.log('Cancel reason:', subscription.cancel_reason_code); // Handle cancellation (e.g., revoke access, send feedback request) await handleCancellation(subscription); response?.status(200).send('OK'); }); webhookHandler.on('payment_succeeded', async ({ event, response }) => { const transaction = event.content.transaction; const invoice = event.content.invoice; console.log('Payment received:', transaction.amount / 100, transaction.currency_code); console.log('Invoice:', invoice.id); response?.status(200).send('OK'); }); webhookHandler.on('payment_failed', async ({ event, response }) => { const transaction = event.content.transaction; const customer = event.content.customer; console.log('Payment failed for customer:', customer.id); console.log('Error:', transaction.error_text); // Handle failed payment (e.g., send notification, update status) await handleFailedPayment(customer, transaction); response?.status(200).send('OK'); }); // Handle unregistered events webhookHandler.on('unhandled_event', ({ event, response }) => { console.log('Unhandled event type:', event.event_type); response?.status(200).send('OK'); }); // Error handling webhookHandler.on('error', (error, { response }) => { console.error('Webhook error:', error.message); if (error.name === 'WebhookAuthenticationError') { response?.status(401).send('Unauthorized'); } else if (error.name === 'WebhookPayloadValidationError') { response?.status(400).send('Bad Request'); } else { response?.status(500).send('Internal Server Error'); } }); // Express route handler app.post('/webhooks/chargebee', async (req, res) => { await webhookHandler.handle({ body: req.body, headers: req.headers, request: req, response: res, }); }); app.listen(3000, () => { console.log('Webhook server listening on port 3000'); }); ``` ## Error Handling The SDK provides structured error handling with detailed error information from the Chargebee API. ```typescript import { createChargebee, ChargebeeError } from 'chargebee'; const chargebee = createChargebee({ site: 'your-site', apiKey: 'your-api-key', }); async function handleSubscriptionUpdate(subscriptionId: string) { try { const { subscription } = await chargebee.subscription.updateForItems(subscriptionId, { subscription_items: [ { item_price_id: 'enterprise-plan-USD-monthly', quantity: 1 }, ], }); return subscription; } catch (error) { if (error instanceof ChargebeeError) { console.error('Chargebee API Error:'); console.error('Message:', error.message); console.error('Error code:', error.api_error_code); console.error('HTTP status:', error.http_status_code); console.error('Error type:', error.type); // Handle specific error codes switch (error.api_error_code) { case 'resource_not_found': throw new Error(`Subscription ${subscriptionId} not found`); case 'invalid_request': throw new Error('Invalid subscription update request'); case 'payment_processing_failed': throw new Error('Payment failed during subscription update'); case 'api_authentication_failed': throw new Error('Invalid API credentials'); default: throw new Error(`Chargebee error: ${error.message}`); } } throw error; } } ``` ## Pagination and List Filtering All list operations support pagination and comprehensive filtering to efficiently query large datasets. ```typescript import { createChargebee } from 'chargebee'; const chargebee = createChargebee({ site: 'your-site', apiKey: 'your-api-key', }); // Paginate through all subscriptions async function getAllActiveSubscriptions() { const subscriptions = []; let offset: string | undefined; do { const { list, next_offset } = await chargebee.subscription.list({ limit: 100, offset, 'status[in]': '["active", "in_trial"]', 'sort_by[asc]': 'created_at', }); for (const item of list) { subscriptions.push(item.subscription); } offset = next_offset; } while (offset); return subscriptions; } // Advanced filtering examples async function queryExamples() { // Customers created in the last 30 days with active subscriptions const { list: newCustomers } = await chargebee.customer.list({ limit: 50, 'created_at[after]': Math.floor(Date.now() / 1000) - 30 * 86400, 'has_active_subscription[is]': 'true', }); // Invoices with amount due greater than $100 const { list: unpaidInvoices } = await chargebee.invoice.list({ limit: 50, 'status[is]': 'payment_due', 'amount_due[gt]': 10000, // $100.00 in cents 'sort_by[desc]': 'amount_due', }); // Subscriptions updated in a specific date range const { list: updatedSubs } = await chargebee.subscription.list({ limit: 50, 'updated_at[between]': `[${startTimestamp}, ${endTimestamp}]`, }); // Multiple filter conditions const { list: filtered } = await chargebee.subscription.list({ limit: 20, 'status[in]': '["active", "non_renewing"]', 'plan_id[is_not]': 'free-plan', 'mrr[gt]': 5000, // MRR greater than $50 }); } ``` ## Summary The Chargebee Node.js/TypeScript SDK provides a comprehensive solution for integrating subscription billing into your applications. Its primary use cases include SaaS subscription management with recurring billing cycles, usage-based metering for API or resource consumption, hybrid billing models combining flat fees with metered components, self-service customer portals for subscription management, and automated invoice and payment processing with dunning management. The SDK's integration patterns support both server-side API operations and client-side checkout experiences through hosted pages. The webhook handler enables real-time event processing for subscription lifecycle events, payment notifications, and invoice updates. Type-safe interfaces ensure compile-time error detection, while the unified client interface provides consistent access to all Chargebee resources across different JavaScript runtimes including Node.js, Deno, Bun, and Edge Functions.