chargebee
Version:
A library for integrating with Chargebee.
540 lines (507 loc) • 22.1 kB
TypeScript
///<reference path='./resources/Addon.d.ts' />
///<reference path='./resources/Address.d.ts' />
///<reference path='./resources/AdvanceInvoiceSchedule.d.ts' />
///<reference path='./resources/Alert.d.ts' />
///<reference path='./resources/AlertStatus.d.ts' />
///<reference path='./resources/AttachedItem.d.ts' />
///<reference path='./resources/Attribute.d.ts' />
///<reference path='./resources/BillingConfiguration.d.ts' />
///<reference path='./resources/Brand.d.ts' />
///<reference path='./resources/BusinessEntity.d.ts' />
///<reference path='./resources/BusinessEntityTransfer.d.ts' />
///<reference path='./resources/Card.d.ts' />
///<reference path='./resources/Comment.d.ts' />
///<reference path='./resources/Configuration.d.ts' />
///<reference path='./resources/Contact.d.ts' />
///<reference path='./resources/ContractTerm.d.ts' />
///<reference path='./resources/Coupon.d.ts' />
///<reference path='./resources/CouponCode.d.ts' />
///<reference path='./resources/CouponSet.d.ts' />
///<reference path='./resources/CpqQuoteSignature.d.ts' />
///<reference path='./resources/CreditNote.d.ts' />
///<reference path='./resources/CreditNoteEstimate.d.ts' />
///<reference path='./resources/Currency.d.ts' />
///<reference path='./resources/Customer.d.ts' />
///<reference path='./resources/CustomerEntitlement.d.ts' />
///<reference path='./resources/DifferentialPrice.d.ts' />
///<reference path='./resources/Discount.d.ts' />
///<reference path='./resources/Download.d.ts' />
///<reference path='./resources/Einvoice.d.ts' />
///<reference path='./resources/Entitlement.d.ts' />
///<reference path='./resources/EntitlementOverride.d.ts' />
///<reference path='./resources/Estimate.d.ts' />
///<reference path='./resources/Event.d.ts' />
///<reference path='./resources/Export.d.ts' />
///<reference path='./resources/Feature.d.ts' />
///<reference path='./resources/FilterCondition.d.ts' />
///<reference path='./resources/GatewayErrorDetail.d.ts' />
///<reference path='./resources/Gift.d.ts' />
///<reference path='./resources/GrantBlock.d.ts' />
///<reference path='./resources/Hierarchy.d.ts' />
///<reference path='./resources/HostedPage.d.ts' />
///<reference path='./resources/ImpactedCustomer.d.ts' />
///<reference path='./resources/ImpactedItem.d.ts' />
///<reference path='./resources/ImpactedItemPrice.d.ts' />
///<reference path='./resources/ImpactedSubscription.d.ts' />
///<reference path='./resources/InAppSubscription.d.ts' />
///<reference path='./resources/Invoice.d.ts' />
///<reference path='./resources/InvoiceEstimate.d.ts' />
///<reference path='./resources/Item.d.ts' />
///<reference path='./resources/ItemEntitlement.d.ts' />
///<reference path='./resources/ItemFamily.d.ts' />
///<reference path='./resources/ItemPrice.d.ts' />
///<reference path='./resources/LedgerAccountBalance.d.ts' />
///<reference path='./resources/LedgerOperation.d.ts' />
///<reference path='./resources/Metadata.d.ts' />
///<reference path='./resources/NonSubscription.d.ts' />
///<reference path='./resources/OfferEvent.d.ts' />
///<reference path='./resources/OfferFulfillment.d.ts' />
///<reference path='./resources/OmnichannelOneTimeOrder.d.ts' />
///<reference path='./resources/OmnichannelOneTimeOrderItem.d.ts' />
///<reference path='./resources/OmnichannelSubscription.d.ts' />
///<reference path='./resources/OmnichannelSubscriptionItem.d.ts' />
///<reference path='./resources/OmnichannelSubscriptionItemOffer.d.ts' />
///<reference path='./resources/OmnichannelSubscriptionItemScheduledChange.d.ts' />
///<reference path='./resources/OmnichannelTransaction.d.ts' />
///<reference path='./resources/Order.d.ts' />
///<reference path='./resources/PaymentIntent.d.ts' />
///<reference path='./resources/PaymentReferenceNumber.d.ts' />
///<reference path='./resources/PaymentSchedule.d.ts' />
///<reference path='./resources/PaymentScheduleEstimate.d.ts' />
///<reference path='./resources/PaymentScheduleScheme.d.ts' />
///<reference path='./resources/PaymentSource.d.ts' />
///<reference path='./resources/PaymentVoucher.d.ts' />
///<reference path='./resources/PersonalizedOffer.d.ts' />
///<reference path='./resources/Plan.d.ts' />
///<reference path='./resources/PortalSession.d.ts' />
///<reference path='./resources/PriceVariant.d.ts' />
///<reference path='./resources/PricingPageSession.d.ts' />
///<reference path='./resources/PromotionalCredit.d.ts' />
///<reference path='./resources/PromotionalGrant.d.ts' />
///<reference path='./resources/Purchase.d.ts' />
///<reference path='./resources/Quote.d.ts' />
///<reference path='./resources/QuoteLineGroup.d.ts' />
///<reference path='./resources/QuotedCharge.d.ts' />
///<reference path='./resources/QuotedDeltaRamp.d.ts' />
///<reference path='./resources/QuotedRamp.d.ts' />
///<reference path='./resources/QuotedSubscription.d.ts' />
///<reference path='./resources/Ramp.d.ts' />
///<reference path='./resources/RecordedPurchase.d.ts' />
///<reference path='./resources/ResourceMigration.d.ts' />
///<reference path='./resources/Rule.d.ts' />
///<reference path='./resources/SiteMigrationDetail.d.ts' />
///<reference path='./resources/Subscription.d.ts' />
///<reference path='./resources/SubscriptionEntitlement.d.ts' />
///<reference path='./resources/SubscriptionEntitlementsCreatedDetail.d.ts' />
///<reference path='./resources/SubscriptionEntitlementsUpdatedDetail.d.ts' />
///<reference path='./resources/SubscriptionEstimate.d.ts' />
///<reference path='./resources/TaxWithheld.d.ts' />
///<reference path='./resources/ThirdPartyPaymentMethod.d.ts' />
///<reference path='./resources/TimeMachine.d.ts' />
///<reference path='./resources/Token.d.ts' />
///<reference path='./resources/Transaction.d.ts' />
///<reference path='./resources/UnbilledCharge.d.ts' />
///<reference path='./resources/Usage.d.ts' />
///<reference path='./resources/UsageCharge.d.ts' />
///<reference path='./resources/UsageEvent.d.ts' />
///<reference path='./resources/UsageFile.d.ts' />
///<reference path='./resources/UsageSummary.d.ts' />
///<reference path='./resources/VirtualBankAccount.d.ts' />
///<reference path='./resources/WebhookEndpoint.d.ts' />
///<reference path='./resources/Content.d.ts' />
///<reference path='./resources/WebhookEvent.d.ts' />
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;
/**
* @telemetryAdapter optional telemetry adapter for observability (e.g. OpenTelemetry)
*/
telemetryAdapter?: TelemetryAdapter;
/**
* @enableValidation When true, every request's parameters are validated against each endpoint's generated Zod schema before the HTTP request is sent. Violations throw `ChargebeeZodValidationError` with structured Zod issues. Calls with no params argument are validated as `{}`. Required resource ids in the URL path are still checked separately.
*/
enableValidation?: boolean;
};
export interface HttpClientInterface {
makeApiRequest: (request: Request, timeout: number) => Promise<Response>;
}
export type RequestTelemetryHandle = unknown;
export const TelemetryAttributeKeys: {
readonly URL_FULL: 'url.full';
readonly HTTP_REQUEST_METHOD: 'http.request.method';
readonly HTTP_RESPONSE_STATUS_CODE: 'http.response.status_code';
readonly SERVER_ADDRESS: 'server.address';
readonly ERROR_TYPE: 'error.type';
readonly CHARGEBEE_SITE: 'chargebee.site';
readonly CHARGEBEE_API_VERSION: 'chargebee.api_version';
readonly CHARGEBEE_RESOURCE: 'chargebee.resource';
readonly CHARGEBEE_OPERATION: 'chargebee.operation';
readonly CHARGEBEE_SDK_NAME: 'chargebee.sdk.name';
readonly CHARGEBEE_SDK_VERSION: 'chargebee.sdk.version';
readonly CHARGEBEE_ERROR_CODE: 'chargebee.error.code';
readonly CHARGEBEE_ERROR_TYPE: 'chargebee.error.type';
readonly CHARGEBEE_ERROR_PARAM: 'chargebee.error.param';
};
export type RequestTelemetryContext = {
spanName: string;
resource: string;
operation: string;
httpMethod: string;
httpUrl: string;
serverAddress: string;
chargebeeSite: string;
chargebeeApiVersion: 'v1' | 'v2';
sdkName: string;
sdkVersion: string;
/**
* Prebuilt span attributes — pass these to your tracer. Captured `chargebee-*` request
* headers appear as `http.request.header.<name>` with string[] values per OTel semconv.
*/
startAttributes: Record<string, string | string[]>;
};
export type RequestTelemetryError = {
message: string;
chargebeeErrorCode?: string;
chargebeeApiErrorType?: string;
chargebeeErrorParam?: string;
};
export type RequestTelemetryResult = {
httpStatusCode: number;
durationMs: number;
error?: RequestTelemetryError;
/** Prebuilt span attributes — pass these to your tracer. */
endAttributes: Record<string, string | number>;
};
/**
* Optional telemetry adapter. Implement as a class or plain object — the SDK
* keeps it by reference (never deep-cloned). Wire OpenTelemetry or other tools here.
*/
export interface TelemetryAdapter<THandle = RequestTelemetryHandle> {
onRequestStart(
context: RequestTelemetryContext,
requestHeaders: Record<string, string | number>,
): THandle | void;
onRequestEnd(handle: THandle | void, result: RequestTelemetryResult): void;
}
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<number>;
};
export default class Chargebee {
constructor(config: Config);
addon: Addon.AddonResource;
address: Address.AddressResource;
alert: Alert.AlertResource;
alertStatu: AlertStatus.AlertStatusResource;
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;
grantBlock: GrantBlock.GrantBlockResource;
hostedPage: HostedPage.HostedPageResource;
inAppSubscription: InAppSubscription.InAppSubscriptionResource;
invoice: Invoice.InvoiceResource;
item: Item.ItemResource;
itemEntitlement: ItemEntitlement.ItemEntitlementResource;
itemFamily: ItemFamily.ItemFamilyResource;
itemPrice: ItemPrice.ItemPriceResource;
ledgerAccountBalance: LedgerAccountBalance.LedgerAccountBalanceResource;
ledgerOperation: LedgerOperation.LedgerOperationResource;
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;
promotionalGrant: PromotionalGrant.PromotionalGrantResource;
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<ReqT = unknown, ResT = unknown>(
options?: WebhookHandlerOptions,
): WebhookHandler<ReqT, ResT>;
};
}
// 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<ReqT = unknown, ResT = unknown> {
/** 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<ReqT = unknown, ResT = unknown> {
/** 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<string, string | string[] | undefined>,
) => void | Promise<void>;
/**
* 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<ReqT = unknown, ResT = unknown> {
/** The raw request body (string) or pre-parsed object */
body: string | object;
/** Optional HTTP headers for validation */
headers?: Record<string, string | string[] | undefined>;
/** 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<ReqT, ResT> & { event: WebhookEvent<T> },
) => Promise<void> | void;
export type WebhookErrorListener<ReqT = unknown, ResT = unknown> = (
error: Error,
context: WebhookErrorContext<ReqT, ResT>,
) => Promise<void> | void;
// Helper type to map string literal to enum member
type StringToWebhookEventType<S extends WebhookEventTypeValue> = {
[]: `${K}` extends S ? K : never;
}[WebhookEventType];
export interface WebhookHandler<ReqT = unknown, ResT = unknown> {
on<T extends WebhookEventType>(
eventName: T,
listener: WebhookEventListener<ReqT, ResT, T>,
): this;
on<S extends WebhookEventTypeValue>(
eventName: S,
listener: WebhookEventListener<ReqT, ResT, StringToWebhookEventType<S>>,
): this;
on(
eventName: 'unhandled_event',
listener: WebhookEventListener<ReqT, ResT>,
): this;
on(eventName: 'error', listener: WebhookErrorListener<ReqT, ResT>): this;
once<T extends WebhookEventType>(
eventName: T,
listener: WebhookEventListener<ReqT, ResT, T>,
): this;
once<S extends WebhookEventTypeValue>(
eventName: S,
listener: WebhookEventListener<ReqT, ResT, StringToWebhookEventType<S>>,
): this;
once(
eventName: 'unhandled_event',
listener: WebhookEventListener<ReqT, ResT>,
): this;
once(eventName: 'error', listener: WebhookErrorListener<ReqT, ResT>): this;
off<T extends WebhookEventType>(
eventName: T,
listener: WebhookEventListener<ReqT, ResT, T>,
): this;
off<S extends WebhookEventTypeValue>(
eventName: S,
listener: WebhookEventListener<ReqT, ResT, StringToWebhookEventType<S>>,
): this;
off(
eventName: 'unhandled_event',
listener: WebhookEventListener<ReqT, ResT>,
): this;
off(eventName: 'error', listener: WebhookErrorListener<ReqT, ResT>): this;
handle(options: HandleOptions<ReqT, ResT>): Promise<void>;
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<boolean>;
/**
* Creates a Basic Auth validator for webhook requests.
*/
export function basicAuthValidator(
validateCredentials: CredentialValidator,
): (headers: Record<string, string | string[] | undefined>) => Promise<void>;
// 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;
}
/**
* Thrown when `enableValidation` is on and request parameters fail the action's Zod schema.
* Carries `actionName` and the original `ZodError` (issues, `flatten()`, etc.) for programmatic handling.
*/
export class ChargebeeZodValidationError extends Error {
constructor(actionName: string, zodError: import('zod').ZodError);
name: string;
readonly actionName: string;
readonly zodError: import('zod').ZodError;
}
}