/// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// declare module 'chargebee' { export type Config = { /** * @apiKey api key for the site. */ apiKey: string; /** * @site api site name. */ site: string; /** * @apiPath this value indicates the api version, default value is /api/v2. */ apiPath?: '/api/v2' | '/api/v1'; /** * @timeout client side request timeout in milliseconds, default value is 80000ms. */ timeout?: number; /** * @port url port */ port?: number; /** * @timemachineWaitInMillis time interval at which two subsequent retrieve timemachine call in milliseconds, default value is 3000ms. */ timemachineWaitInMillis?: number; /** * @exportWaitInMillis time interval at which two subsequent retrieve export call in milliseconds, default value is 3000ms. */ exportWaitInMillis?: number; /** * @protocol http protocol, default value is https */ protocol?: 'https' | 'http'; /** * @hostSuffix url host suffix, default value is .chargebee.com */ hostSuffix?: string; /** * @retryConfig retry configuration for the client, default value is { enabled: false, maxRetries: 3, delayMs: 1000, retryOn: [500, 502, 503, 504]} */ retryConfig?: RetryConfig; /** * @enableDebugLogs whether to enable debug logs, default value is false */ enableDebugLogs?: boolean; /** * @userAgentSuffix optional string appended to the User-Agent header for additional logging */ userAgentSuffix?: string; /** * @httpClient optional http client implementation, default http client will be used if not provided */ httpClient?: HttpClientInterface; }; export interface HttpClientInterface { makeApiRequest: (request: Request, timeout: number) => Promise; } export type RetryConfig = { /** * @enabled whether to enable retry logic, default value is false * @maxRetries maximum number of retries, default value is 3 * @delayMs delay in milliseconds between retries, default value is 1000ms * @retryOn array of HTTP status codes to retry on, default value is [500, 502, 503, 504] */ enabled?: boolean; maxRetries?: number; delayMs?: number; retryOn?: Array; }; export default class Chargebee { constructor(config: Config); addon: Addon.AddonResource; address: Address.AddressResource; attachedItem: AttachedItem.AttachedItemResource; businessEntity: BusinessEntity.BusinessEntityResource; card: Card.CardResource; comment: Comment.CommentResource; configuration: Configuration.ConfigurationResource; coupon: Coupon.CouponResource; couponCode: CouponCode.CouponCodeResource; couponSet: CouponSet.CouponSetResource; creditNote: CreditNote.CreditNoteResource; currency: Currency.CurrencyResource; customer: Customer.CustomerResource; customerEntitlement: CustomerEntitlement.CustomerEntitlementResource; differentialPrice: DifferentialPrice.DifferentialPriceResource; entitlement: Entitlement.EntitlementResource; entitlementOverride: EntitlementOverride.EntitlementOverrideResource; estimate: Estimate.EstimateResource; event: Event.EventResource; export: Export.ExportResource; feature: Feature.FeatureResource; gift: Gift.GiftResource; hostedPage: HostedPage.HostedPageResource; inAppSubscription: InAppSubscription.InAppSubscriptionResource; invoice: Invoice.InvoiceResource; item: Item.ItemResource; itemEntitlement: ItemEntitlement.ItemEntitlementResource; itemFamily: ItemFamily.ItemFamilyResource; itemPrice: ItemPrice.ItemPriceResource; nonSubscription: NonSubscription.NonSubscriptionResource; offerEvent: OfferEvent.OfferEventResource; offerFulfillment: OfferFulfillment.OfferFulfillmentResource; omnichannelOneTimeOrder: OmnichannelOneTimeOrder.OmnichannelOneTimeOrderResource; omnichannelSubscription: OmnichannelSubscription.OmnichannelSubscriptionResource; omnichannelSubscriptionItem: OmnichannelSubscriptionItem.OmnichannelSubscriptionItemResource; order: Order.OrderResource; paymentIntent: PaymentIntent.PaymentIntentResource; paymentScheduleScheme: PaymentScheduleScheme.PaymentScheduleSchemeResource; paymentSource: PaymentSource.PaymentSourceResource; paymentVoucher: PaymentVoucher.PaymentVoucherResource; personalizedOffer: PersonalizedOffer.PersonalizedOfferResource; plan: Plan.PlanResource; portalSession: PortalSession.PortalSessionResource; priceVariant: PriceVariant.PriceVariantResource; pricingPageSession: PricingPageSession.PricingPageSessionResource; promotionalCredit: PromotionalCredit.PromotionalCreditResource; purchase: Purchase.PurchaseResource; quote: Quote.QuoteResource; ramp: Ramp.RampResource; recordedPurchase: RecordedPurchase.RecordedPurchaseResource; resourceMigration: ResourceMigration.ResourceMigrationResource; rule: Rule.RuleResource; siteMigrationDetail: SiteMigrationDetail.SiteMigrationDetailResource; subscription: Subscription.SubscriptionResource; subscriptionEntitlement: SubscriptionEntitlement.SubscriptionEntitlementResource; timeMachine: TimeMachine.TimeMachineResource; transaction: Transaction.TransactionResource; unbilledCharge: UnbilledCharge.UnbilledChargeResource; usage: Usage.UsageResource; usageCharge: UsageCharge.UsageChargeResource; usageEvent: UsageEvent.UsageEventResource; usageFile: UsageFile.UsageFileResource; usageSummary: UsageSummary.UsageSummaryResource; virtualBankAccount: VirtualBankAccount.VirtualBankAccountResource; webhookEndpoint: WebhookEndpoint.WebhookEndpointResource; /** Webhook handler instance with auto-configured Basic Auth (if env vars are set) */ webhooks: WebhookHandler & { /** Create a new typed webhook handler instance */ createHandler( options?: WebhookHandlerOptions, ): WebhookHandler; }; } // Webhook Handler Types export type WebhookEventName = EventTypeEnum | 'unhandled_event'; export type WebhookEventTypeValue = `${WebhookEventType}`; /** * @deprecated Renamed to `WebhookEventTypeValue` for clarity. Use `WebhookEventTypeValue` instead. * This alias will be removed in the next major version. */ export type WebhookContentTypeValue = WebhookEventTypeValue; /** * Context object passed to webhook event listeners. * Wraps the event data with optional framework-specific request/response objects. */ export interface WebhookContext { /** The parsed webhook event from Chargebee */ event: WebhookEvent; /** Framework-specific request object (Express, Fastify, etc.) */ request?: ReqT; /** Framework-specific response object (Express, Fastify, etc.) */ response?: ResT; } /** * Context object passed to webhook error listeners. * Contains the request/response objects so errors can be handled appropriately. */ export interface WebhookErrorContext { /** Framework-specific request object (Express, Fastify, etc.) */ request?: ReqT; /** Framework-specific response object (Express, Fastify, etc.) */ response?: ResT; } /** * Validator function type for authenticating webhook requests. * Can be synchronous or asynchronous. */ export type RequestValidator = ( headers: Record, ) => void | Promise; /** * Configuration options for WebhookHandler. */ export interface WebhookHandlerOptions { /** * Optional validator function to authenticate incoming webhook requests. * Typically used for Basic Auth validation. * Can be sync or async - throw an error to reject the request. */ requestValidator?: RequestValidator; } /** * Options for the handle() method. */ export interface HandleOptions { /** The raw request body (string) or pre-parsed object */ body: string | object; /** Optional HTTP headers for validation */ headers?: Record; /** Optional framework-specific request object (Express, Fastify, etc.) */ request?: ReqT; /** Optional framework-specific response object (Express, Fastify, etc.) */ response?: ResT; } export type WebhookEventListener< ReqT = unknown, ResT = unknown, T extends WebhookEventType = WebhookEventType, > = ( context: WebhookContext & { event: WebhookEvent }, ) => Promise | void; export type WebhookErrorListener = ( error: Error, context: WebhookErrorContext, ) => Promise | void; // Helper type to map string literal to enum member type StringToWebhookEventType = { [K in WebhookEventType]: `${K}` extends S ? K : never; }[WebhookEventType]; export interface WebhookHandler { on( eventName: T, listener: WebhookEventListener, ): this; on( eventName: S, listener: WebhookEventListener>, ): this; on( eventName: 'unhandled_event', listener: WebhookEventListener, ): this; on(eventName: 'error', listener: WebhookErrorListener): this; once( eventName: T, listener: WebhookEventListener, ): this; once( eventName: S, listener: WebhookEventListener>, ): this; once( eventName: 'unhandled_event', listener: WebhookEventListener, ): this; once(eventName: 'error', listener: WebhookErrorListener): this; off( eventName: T, listener: WebhookEventListener, ): this; off( eventName: S, listener: WebhookEventListener>, ): this; off( eventName: 'unhandled_event', listener: WebhookEventListener, ): this; off(eventName: 'error', listener: WebhookErrorListener): this; handle(options: HandleOptions): Promise; requestValidator: RequestValidator | undefined; } // Webhook Auth /** * Credential validator function type. * Can be synchronous or asynchronous (e.g., for database lookups). */ export type CredentialValidator = ( username: string, password: string, ) => boolean | Promise; /** * Creates a Basic Auth validator for webhook requests. */ export function basicAuthValidator( validateCredentials: CredentialValidator, ): (headers: Record) => Promise; // Webhook Error Classes /** * Base class for all webhook-related errors. */ export class WebhookError extends Error { constructor(message: string); name: string; } /** * Authentication error thrown when webhook request authentication fails. * Typically maps to HTTP 401 Unauthorized. */ export class WebhookAuthenticationError extends WebhookError { constructor(message: string); name: string; } /** * Payload validation error thrown when the webhook payload structure is invalid. * Typically maps to HTTP 400 Bad Request. */ export class WebhookPayloadValidationError extends WebhookError { constructor(message: string); name: string; } /** * JSON parsing error thrown when the webhook body cannot be parsed as JSON. * Typically maps to HTTP 400 Bad Request. */ export class WebhookPayloadParseError extends WebhookError { constructor(message: string, rawBody?: string); name: string; readonly rawBody?: string; } }