UNPKG

meta-cloud-api

Version:
1,567 lines (1,566 loc) 139 kB
import { AudioMediaTypesEnum, BusinessVerticalEnum, ButtonPositionEnum, CategoryEnum, ComponentTypesEnum, ConversationTypesEnum, CurrencyCodesEnum, DataLocalizationRegionEnum, DocumentMediaTypesEnum, HttpMethodsEnum, ImageMediaTypesEnum, InteractiveTypesEnum, LanguagesEnum, MessageTypesEnum, ParametersTypesEnum, ReferralSourceTypesEnum, RequestCodeMethodsEnum, StatusEnum, StickerMediaTypesEnum, SubTypeEnum, SystemChangeTypesEnum, TemplateStatusEnum, VideoMediaTypesEnum, WabaConfigEnum, WebhookTypesEnum } from "./enums.js"; import { IncomingHttpHeaders, IncomingMessage } from "node:http"; //#region src/types/request.d.ts type GeneralRequestBody = Record<string, unknown>; type UrlEncodedFormBody = Record<string, string | string[]>; interface GeneralHeaderInterface { /** * Authorization token. This is required for all HTTP requests made to the graph API. * @default 'Bearer ' */ Authorization: string; /** * Content type of the message being sent. This is required for all HTTP requests made to the graph API. * @default 'application/json' */ 'Content-Type': string; /** * User agent field sent in all requests. This is used to gather SDK usage metrics and help * better triage support requests. * @default `WA_SDK/${ SDK_version } (Node.js ${ process.version })` */ 'User-Agent': string; } interface RequesterResponseInterface<T> { json: () => Promise<T>; } interface ResponseSuccess { success: boolean; } interface ResponseData<T> { data: T; } interface ResponsePagination<T> { data: T[]; paging: Paging; } interface Paging { cursors: { before: string; after: string; }; next: string; } /** * Common error detail structure used in Meta API responses * Used for individual item errors in bulk operations */ interface MetaErrorDetail { message: string; code: string; error_data?: { details: string; }; } declare class RequesterClass { constructor(apiVersion: string, phoneNumberId: number, accessToken: string, businessAcctId: string, userAgent: string); sendRequest: (method: HttpMethodsEnum, path: string, timeout: number, body?: GeneralRequestBody, contentType?: string, additionalHeaders?: Record<string, string>) => Promise<RequesterResponseInterface<unknown>>; getJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: GeneralRequestBody, additionalHeaders?: Record<string, string>): Promise<T>; sendFormData<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, formData: FormData, additionalHeaders?: Record<string, string>): Promise<T>; sendUrlEncodedForm<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, formData: UrlEncodedFormBody, additionalHeaders?: Record<string, string>): Promise<T>; updateTimeout(timeout: number): void; updateAccessToken(accessToken: string): void; } //#endregion //#region src/api/blockUsers/types/blockUsers.d.ts /** * Blocked user information in response */ type BlockedUserInfo = { input: string; wa_id: string; }; /** * Failed user information with error details * Uses common MetaErrorDetail type for consistency across APIs */ type FailedUserInfo = BlockedUserInfo & { errors?: MetaErrorDetail[]; }; /** * Response for block/unblock operations */ type BlockUsersResponse = { messaging_product: 'whatsapp'; block_users: { added_users?: BlockedUserInfo[]; failed_users?: FailedUserInfo[]; }; }; /** * Pagination cursors for list operations */ type PagingCursors = { after?: string; before?: string; }; /** * Pagination information */ type PagingInfo$1 = { cursors?: PagingCursors; previous?: string; next?: string; }; /** * List blocked users response */ type ListBlockedUsersResponse = { data: Array<{ block_users: BlockedUserInfo[]; }>; paging?: PagingInfo$1; }; /** * Query parameters for listing blocked users */ type ListBlockedUsersParams = { limit?: number; after?: string; before?: string; }; /** * Block Users API Interface */ interface BlockUsersClass { /** * Block one or more WhatsApp users * @param users - Array of phone numbers or WhatsApp IDs to block * @returns Response with successfully blocked and failed users * @throws Error if users have not messaged in last 24 hours * @see https://developers.facebook.com/docs/whatsapp/cloud-api/block-users#block-users */ block(users: string[]): Promise<BlockUsersResponse>; /** * Unblock one or more WhatsApp users * @param users - Array of phone numbers or WhatsApp IDs to unblock * @returns Response with successfully unblocked and failed users * @see https://developers.facebook.com/docs/whatsapp/cloud-api/block-users#unblock-users */ unblock(users: string[]): Promise<BlockUsersResponse>; /** * Get list of blocked WhatsApp users with pagination * @param params - Optional pagination parameters * @returns List of blocked users with pagination info * @see https://developers.facebook.com/docs/whatsapp/cloud-api/block-users#get-list-of-blocked-numbers */ listBlockedUsers(params?: ListBlockedUsersParams): Promise<ListBlockedUsersResponse>; } //#endregion //#region src/api/calling/types/calling.d.ts /** * Calling API Types * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/ */ type CallingStatus = 'ENABLED' | 'DISABLED'; type CallIconVisibility = 'DEFAULT' | 'DISABLE_ALL'; type CallbackPermissionStatus = 'ENABLED' | 'DISABLED'; type CallHoursStatus = 'ENABLED' | 'DISABLED'; type SipStatus = 'ENABLED' | 'DISABLED'; type CallHoursDay = 'MONDAY' | 'TUESDAY' | 'WEDNESDAY' | 'THURSDAY' | 'FRIDAY' | 'SATURDAY' | 'SUNDAY'; type WeeklyOperatingHours = { day_of_week: CallHoursDay; open_time: string; close_time: string; }; type HolidaySchedule = { date: string; start_time: string; end_time: string; }; type CallHours = { status: CallHoursStatus; timezone_id: string; weekly_operating_hours: WeeklyOperatingHours[]; holiday_schedule?: HolidaySchedule[]; }; type SipServer = { hostname: string; port?: number; request_uri_user_params?: Record<string, string>; sip_user_password?: string; }; type SipSettings = { status: SipStatus; servers?: SipServer[]; }; type CallingSettings = { status?: CallingStatus; call_icon_visibility?: CallIconVisibility; call_hours?: CallHours; callback_permission_status?: CallbackPermissionStatus; sip?: SipSettings; }; type UpdateCallingSettingsRequest = { calling: CallingSettings; }; type CallingSettingsResponse = { calling?: CallingSettings; [key: string]: unknown; }; type CallPermission = { status: string; expiration_time?: number; }; type CallPermissionLimit = { time_period: string; max_allowed: number; current_usage: number; limit_expiration_time?: number; }; type CallPermissionAction = { action_name: string; can_perform_action: boolean; limits?: CallPermissionLimit[]; }; type CallPermissionsResponse = { messaging_product: 'whatsapp'; permission: CallPermission; actions?: CallPermissionAction[]; }; type CallSdpType = 'offer' | 'answer'; type CallSession = { sdp_type: CallSdpType; sdp: string; }; type CallAction = 'connect' | 'pre_accept' | 'accept' | 'reject' | 'terminate'; type InitiateCallRequest = { to: string; session: CallSession; biz_opaque_callback_data?: string; }; type PreAcceptCallRequest = { call_id: string; session?: CallSession; }; type AcceptCallRequest = { call_id: string; session?: CallSession; biz_opaque_callback_data?: string; }; type RejectCallRequest = { call_id: string; }; type TerminateCallRequest = { call_id: string; }; type InitiateCallResponse = { messaging_product: 'whatsapp'; calls: Array<{ id: string; }>; }; type CallActionResponse = { messaging_product: 'whatsapp'; success: boolean; }; interface CallingClass { updateCallingSettings(params: UpdateCallingSettingsRequest): Promise<ResponseSuccess>; getCallingSettings(params?: { fields?: string[] | string; include_sip_credentials?: boolean; }): Promise<CallingSettingsResponse>; getCallPermissions(params: { userWaId: string; }): Promise<CallPermissionsResponse>; initiateCall(params: InitiateCallRequest): Promise<InitiateCallResponse>; preAcceptCall(params: PreAcceptCallRequest): Promise<CallActionResponse>; acceptCall(params: AcceptCallRequest): Promise<CallActionResponse>; rejectCall(params: RejectCallRequest): Promise<CallActionResponse>; terminateCall(params: TerminateCallRequest): Promise<CallActionResponse>; } //#endregion //#region src/api/commerce/types/commerce.d.ts /** * Commerce Settings API Types * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/catalogs/sell-products-and-services/set-commerce-settings/ */ type CommerceSetting = { id: string; is_cart_enabled?: boolean; is_catalog_visible?: boolean; }; type CommerceSettingsResponse = { data: CommerceSetting[]; }; type UpdateCommerceSettingsRequest = { is_cart_enabled?: boolean; is_catalog_visible?: boolean; }; interface CommerceClass { getCommerceSettings(): Promise<CommerceSettingsResponse>; updateCommerceSettings(params: UpdateCommerceSettingsRequest): Promise<ResponseSuccess>; } //#endregion //#region src/api/encryption/types/publicKey.d.ts type EncryptionPublicKeyResponse = ResponseData<{ business_public_key: string; business_public_key_signature_status: 'VALID' | 'MISMATCH'; }>; //#endregion //#region src/api/groups/types/groups.d.ts /** * Groups API Types * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/ */ type GroupJoinApprovalMode = 'approval_required' | 'auto_approve'; type GroupCreateRequest = { subject: string; description?: string; join_approval_mode?: GroupJoinApprovalMode; }; type GroupCreateResponse = { messaging_product: 'whatsapp'; id: string; invite_link?: string; }; type GroupInfoField = 'join_approval_mode' | 'subject' | 'description' | 'suspended' | 'creation_timestamp' | 'participants' | 'total_participant_count'; type GroupInfoFieldsParam = GroupInfoField[] | string; type GroupParticipant = { wa_id: string; }; type GroupInfoResponse = { messaging_product: 'whatsapp'; id: string; subject?: string; description?: string; suspended?: boolean; creation_timestamp?: number; participants?: GroupParticipant[]; total_participant_count?: number; join_approval_mode?: GroupJoinApprovalMode; }; type GroupInviteLinkResponse = { messaging_product: 'whatsapp'; invite_link: string; }; type GroupJoinRequest = { join_request_id: string; wa_id: string; creation_timestamp: number; }; type GroupJoinRequestError = { code: number; message: string; title?: string; error_data?: { details?: string; }; }; type GroupJoinRequestFailure = { join_request_id: string; errors: GroupJoinRequestError[]; }; type GroupJoinRequestsResponse = { data: GroupJoinRequest[]; paging?: PagingInfo; }; type GroupJoinRequestsActionResponse = { messaging_product: 'whatsapp'; approved_join_requests?: string[]; rejected_join_requests?: string[]; failed_join_requests?: GroupJoinRequestFailure[]; errors?: GroupJoinRequestError[]; }; type GroupSummary = { id: string; subject: string; created_at: number; }; type GroupListResponse = { data: { groups: GroupSummary[]; }; paging?: PagingInfo; }; type GroupListParams = { limit?: number; after?: string; before?: string; }; type UpdateGroupSettingsRequest = { subject?: string; description?: string; profilePictureFile?: Blob | Buffer; }; type GroupSettingsResponse = ResponseSuccess; interface GroupsClass { createGroup(params: GroupCreateRequest): Promise<GroupCreateResponse>; deleteGroup(groupId: string): Promise<ResponseSuccess>; getGroupInfo(groupId: string, fields?: GroupInfoFieldsParam): Promise<GroupInfoResponse>; getActiveGroups(params?: GroupListParams): Promise<GroupListResponse>; getGroupInviteLink(groupId: string): Promise<GroupInviteLinkResponse>; createGroupInviteLink(groupId: string): Promise<GroupInviteLinkResponse>; resetGroupInviteLink(groupId: string): Promise<GroupInviteLinkResponse>; deleteGroupInviteLink(groupId: string): Promise<ResponseSuccess>; getJoinRequests(groupId: string): Promise<GroupJoinRequestsResponse>; approveJoinRequests(groupId: string, joinRequestIds: string[]): Promise<GroupJoinRequestsActionResponse>; rejectJoinRequests(groupId: string, joinRequestIds: string[]): Promise<GroupJoinRequestsActionResponse>; addParticipants(groupId: string, participants: string[]): Promise<ResponseSuccess>; removeParticipants(groupId: string, participants: string[]): Promise<ResponseSuccess>; updateGroupSettings(groupId: string, params: UpdateGroupSettingsRequest): Promise<GroupSettingsResponse>; } type PagingInfo = { cursors?: { before?: string; after?: string; }; previous?: string; next?: string; }; //#endregion //#region src/api/messages/types/text.d.ts type TextObject = { body: string; preview_url?: boolean; }; interface TextMessageParams extends MessageRequestParams<TextObject | string> { previewUrl?: boolean; } //#endregion //#region src/api/messages/types/template.d.ts type LanguageObject = { policy: 'deterministic'; code: LanguagesEnum | (string & {}); }; type ParametersObject<T extends ParametersTypesEnum> = { type: T; }; type SimpleTextObject$1 = { text: string; }; type TextParametersObject = ParametersObject<ParametersTypesEnum.Text> & SimpleTextObject$1; type CouponCodeParametersObject = ParametersObject<ParametersTypesEnum.CouponCode> & { coupon_code: string; }; type CurrencyObject = { fallback_value: string; code: CurrencyCodesEnum; amount_1000: number; }; type CurrencyParametersObject = ParametersObject<ParametersTypesEnum.Currency> & { currency: CurrencyObject; }; type DateTimeObject = { fallback_value: string; }; type DateTimeParametersObject = ParametersObject<ParametersTypesEnum.Currency> & { date_time: DateTimeObject; }; type DocumentMediaObject$2 = { id?: string; link?: string; caption?: string; filename?: string; }; type ImageMediaObject$2 = { id?: string; link?: string; caption?: string; }; type VideoMediaObject$2 = { id?: string; link?: string; caption?: string; }; type DocumentParametersObject = ParametersObject<ParametersTypesEnum.Document> & DocumentMediaObject$2; type ImageParametersObject = ParametersObject<ParametersTypesEnum.Image> & ImageMediaObject$2; type VideoParametersObject = ParametersObject<ParametersTypesEnum.Video> & VideoMediaObject$2; type ComponentObject<T extends ComponentTypesEnum> = { type: T; parameters: (CurrencyParametersObject | DateTimeParametersObject | DocumentParametersObject | ImageParametersObject | TextParametersObject | VideoParametersObject | CouponCodeParametersObject)[]; }; type ButtonComponentObject = ComponentObject<ComponentTypesEnum.Button> & { parameters?: (TextParametersObject | PayloadParametersObject)[]; sub_type: SubTypeEnum; index: ButtonPositionEnum; }; type PayloadParametersObject = ParametersObject<ParametersTypesEnum.Payload> & { payload: string; }; type MessageTemplateObject<T extends ComponentTypesEnum> = { name: string; language: LanguageObject; components?: (ComponentObject<T> | ButtonComponentObject)[]; }; //#endregion //#region src/api/messages/types/media.d.ts type MetaMediaObject = { id: string; link?: never; }; type HostedMediaObject = { id?: never; link: string; }; type AudioMediaObject = MetaMediaObject | HostedMediaObject; type MetaDocumentMediaObject = MetaMediaObject & { caption?: string; filename?: string; }; type HostedDocumentMediaObject = HostedMediaObject & { caption?: string; filename?: string; }; type DocumentMediaObject = MetaDocumentMediaObject | HostedDocumentMediaObject; type MetaImageMediaObject = MetaMediaObject & { caption?: string; }; type HostedImageMediaObject = HostedMediaObject & { caption?: string; }; type ImageMediaObject = MetaImageMediaObject | HostedImageMediaObject; type MetaVideoMediaObject = MetaMediaObject & { caption?: string; }; type HostedVideoMediaObject = HostedMediaObject & { caption?: string; }; type VideoMediaObject = MetaVideoMediaObject | HostedVideoMediaObject; type StickerMediaObject = MetaMediaObject | HostedMediaObject; //#endregion //#region src/api/messages/types/contact.d.ts type AddressesObject = { street?: string; city?: string; state?: string; zip?: string; country?: string; country_code?: string; type?: 'HOME' | 'WORK' | string; }; type EmailObject = { email?: string; type?: 'HOME' | 'WORK' | string; }; type NameObject = { formatted_name: string; first_name?: string; last_name?: string; middle_name?: string; suffix?: string; prefix?: string; }; type OrgObject = { company?: string; department?: string; title?: string; }; type PhoneObject = { phone?: string; type?: 'CELL' | 'MAIN' | 'IPHONE' | 'HOME' | 'WORK' | string; wa_id?: string; }; type URLObject = { url?: string; type?: 'HOME' | 'WORK' | string; }; type ContactObject = { addresses?: AddressesObject[]; birthday?: `${number}${number}${number}${number}-${number}${number}-${number}${number}`; emails?: EmailObject[]; name: NameObject; org?: OrgObject; phones?: PhoneObject[]; urls?: URLObject[]; }; //#endregion //#region src/api/messages/types/location.d.ts type LocationObject = { longitude: number; latitude: number; name?: string; address?: string; }; //#endregion //#region src/api/messages/types/interactive.d.ts type DocumentMediaObject$1 = { id?: string; link?: string; caption?: string; filename?: string; }; type ImageMediaObject$1 = { id?: string; link?: string; caption?: string; }; type VideoMediaObject$1 = { id?: string; link?: string; caption?: string; }; type ProductObject = { product_retailer_id: string; }; type SimpleTextObject = { text: string; }; type RowObject = { id: string; title: string; description?: string; }; type MultiProductSectionObject = { product_items: ProductObject[]; rows?: never; title?: string; }; type ListSectionObject = { product_items?: never; rows: RowObject[]; title?: string; }; type SectionObject = MultiProductSectionObject | ListSectionObject; type ButtonObject = { title: string; id: string; }; type ReplyButtonObject = { type: 'reply'; reply: ButtonObject; }; type ActionObject = { button?: string; buttons?: ReplyButtonObject[]; catalog_id?: string; product_retailer_id?: string; sections?: SectionObject[]; }; type HeaderObject = { type: 'document' | 'image' | 'text' | 'video'; document?: DocumentMediaObject$1; image?: ImageMediaObject$1; text?: string; sub_text?: string; video?: VideoMediaObject$1; }; type ButtonInteractiveObject = { type: InteractiveTypesEnum.Button | 'button'; body: SimpleTextObject; footer?: SimpleTextObject; header?: HeaderObject; action: ActionObject; }; type ListInteractiveObject = { type: InteractiveTypesEnum.List | 'list'; body: SimpleTextObject; footer?: SimpleTextObject; header?: HeaderObject; action: ActionObject; }; type ProductInteractiveObject = { type: InteractiveTypesEnum.Product | 'product'; body?: SimpleTextObject; footer?: SimpleTextObject; header?: HeaderObject; action: ActionObject; }; type ProductListInteractiveObject = { type: InteractiveTypesEnum.ProductList | 'product_list'; body: SimpleTextObject; footer?: SimpleTextObject; header: HeaderObject; action: ActionObject; }; type CatalogMessageParameters = { thumbnail_product_retailer_id: string; }; type CatalogMessageActionObject = { name: 'catalog_message'; parameters?: CatalogMessageParameters; }; type CatalogMessageInteractiveObject = { type: InteractiveTypesEnum.CatalogMessage | 'catalog_message'; body?: SimpleTextObject; footer?: SimpleTextObject; header?: HeaderObject; action: CatalogMessageActionObject; }; type CallPermissionRequestActionObject = { name: 'call_permission_request'; }; type CallPermissionRequestInteractiveObject = { type: InteractiveTypesEnum.CallPermissionRequest | 'call_permission_request'; body?: SimpleTextObject; footer?: SimpleTextObject; header?: HeaderObject; action: CallPermissionRequestActionObject; }; type CtaUrlParameters = { display_text: string; url: string; }; type CtaUrlActionObject = { name: 'cta_url'; parameters: CtaUrlParameters; }; type CtaUrlInteractiveObject = { type: InteractiveTypesEnum.CtaUrl | 'cta_url'; body?: SimpleTextObject; footer?: SimpleTextObject; header?: HeaderObject; action: CtaUrlActionObject; }; type LocationRequestActionObject = { name: 'send_location'; }; type LocationRequestInteractiveObject = { type: InteractiveTypesEnum.LocationRequest | 'location_request_message'; body: SimpleTextObject; footer?: SimpleTextObject; header?: HeaderObject; action: LocationRequestActionObject; }; type AddressValues = { name?: string; phone_number?: string; in_pin_code?: string; house_number?: string; floor_number?: string; tower_number?: string; building_name?: string; address?: string; landmark_area?: string; city?: string; state?: string; }; type SavedAddress = { id: string; value: AddressValues; }; type ValidationErrors = { [key in keyof AddressValues]?: string }; type AddressMessageParameters = { country: string; values?: AddressValues; saved_addresses?: SavedAddress[]; validation_errors?: ValidationErrors; }; type AddressMessageActionObject = { name: 'address_message'; parameters: AddressMessageParameters; }; type AddressMessageInteractiveObject = { type: InteractiveTypesEnum.AddressMessage | 'address_message'; body: SimpleTextObject; footer?: SimpleTextObject; header?: HeaderObject; action: AddressMessageActionObject; }; type FlowParameters = { flow_message_version: string; flow_id?: string; flow_name?: string; flow_cta: string; mode?: 'draft' | 'published'; flow_token?: string; flow_action?: 'navigate' | 'data_exchange'; flow_action_payload?: { screen?: string; data?: Record<string, string>; }; }; type FlowActionObject = { name: 'flow'; parameters: FlowParameters; }; type FlowInteractiveObject = { type: InteractiveTypesEnum.Flow | 'flow'; body: SimpleTextObject; footer?: SimpleTextObject; header?: HeaderObject; action: FlowActionObject; }; type CarouselHeaderObject = { type: 'image' | 'video'; image?: ImageMediaObject$1; video?: VideoMediaObject$1; }; type CarouselQuickReply = { id: string; title: string; }; type CarouselQuickReplyButton = { type: 'quick_reply'; quick_reply: CarouselQuickReply; }; type CarouselCtaUrlAction = { name: 'cta_url'; parameters: CtaUrlParameters; }; type CarouselQuickReplyAction = { buttons: CarouselQuickReplyButton[]; }; type MediaCarouselCard$1 = { card_index: number; type: 'cta_url'; header: CarouselHeaderObject; body?: SimpleTextObject; action: CarouselCtaUrlAction | CarouselQuickReplyAction; }; type ProductCarouselAction = { product_retailer_id: string; catalog_id: string; }; type ProductCarouselCard$1 = { card_index: number; type: 'product'; action: ProductCarouselAction; }; type CarouselActionObject = { cards: Array<MediaCarouselCard$1 | ProductCarouselCard$1>; }; type CarouselInteractiveObject = { type: InteractiveTypesEnum.Carousel | 'carousel'; body: SimpleTextObject; action: CarouselActionObject; }; type InteractiveObject = ButtonInteractiveObject | ListInteractiveObject | ProductInteractiveObject | ProductListInteractiveObject | CatalogMessageInteractiveObject | CallPermissionRequestInteractiveObject | CtaUrlInteractiveObject | CarouselInteractiveObject | LocationRequestInteractiveObject | AddressMessageInteractiveObject | FlowInteractiveObject; //#endregion //#region src/api/messages/types/reaction.d.ts interface ReactionParams { messageId: string; emoji: string; to: string; recipientType?: MessageRecipientType; } //#endregion //#region src/types/config.d.ts /** * Configuration for automatic retry behavior on throttling errors. * * When the WhatsApp API returns a rate limit error (WhatsAppThrottlingError), * the SDK will automatically retry the request using exponential backoff. * * @example * ```typescript * const wa = new WhatsApp({ * accessToken: '...', * phoneNumberId: 123, * retry: { maxAttempts: 3, backoff: 'exponential', initialDelayMs: 1000 }, * }); * ``` */ interface RetryConfig { /** * Maximum number of attempts (including the initial attempt). * Defaults to 3. */ maxAttempts?: number; /** * Backoff strategy. * - 'exponential': delay doubles each attempt (1s → 2s → 4s) * - 'fixed': constant delay between attempts * Defaults to 'exponential'. */ backoff?: 'exponential' | 'fixed'; /** * Initial delay in milliseconds before the first retry. * Defaults to 1000 (1 second). */ initialDelayMs?: number; } type WhatsAppConfig = { accessToken: string; appId?: string; appSecret?: string; phoneNumberId?: number; businessAcctId?: string; apiVersion?: string; webhookEndpoint?: string; webhookVerificationToken?: string; listenerPort?: number; debug?: boolean; maxRetriesAfterWait?: number; requestTimeout?: number; privatePem?: string; passphrase?: string; /** Automatic retry configuration for throttling errors. */ retry?: RetryConfig; }; type WabaConfigType = { /** * The Meta for Developers business application Id for this registered application. */ [WabaConfigEnum.AppId]: string; /** * The Meta for Developers business application secret for this registered application. */ [WabaConfigEnum.AppSecret]: string; /** * The Meta for Developers phone number id used by the registered business. */ [WabaConfigEnum.PhoneNumberId]: number; /** * The Meta for Developers business id for the registered business. */ [WabaConfigEnum.BusinessAcctId]: string; /** * The version of the Cloud API being used. Starts with a "v" and follows the major number. */ [WabaConfigEnum.APIVersion]: string; /** * The access token to make calls on behalf of the signed in Meta for Developers account or business. */ [WabaConfigEnum.AccessToken]: string; /** * The endpoint path (e.g. if the value here is webhook, the webhook URL would look like http/https://{host}/webhook). */ [WabaConfigEnum.WebhookEndpoint]: string; /** * The verification token that needs to match what is sent by the Cloud API webhook in order to subscribe. */ [WabaConfigEnum.WebhookVerificationToken]: string; /** * The listener port for the webhook web server. */ [WabaConfigEnum.ListenerPort]: number; /** * To turn on global debugging of the logger to print verbose output across the APIs. */ [WabaConfigEnum.Debug]: boolean; /** * The total number of times a request should be retried after the wait period if it fails. */ [WabaConfigEnum.MaxRetriesAfterWait]: number; /** * The timeout period for a request to quit and destroy the attempt in ms. */ [WabaConfigEnum.RequestTimeout]: number; /** * The private key for the Meta for Developers business. */ [WabaConfigEnum.PrivatePem]: string; /** * The passphrase for the Meta for Developers business. */ [WabaConfigEnum.Passphrase]: string; /** * Automatic retry configuration for throttling errors. * Passed through from WhatsAppConfig. */ retry?: RetryConfig; }; //#endregion //#region src/types/base.d.ts declare class BaseClass { constructor(config: WabaConfigType); } //#endregion //#region src/api/messages/types/common.d.ts type GeneralMessageBody = GeneralRequestBody & { /** * The Meta messaging product name. * @default 'whatsapp' */ messaging_product: 'whatsapp'; }; type StatusObject = { status: 'read' | 'typing'; message_id: string; typing_indicator?: TypingIndicatorObject; }; type TypingIndicatorObject = { type: 'text'; }; type StatusResponse = ResponseSuccess; type ConTextObject = { message_id: string; }; type MessageRecipientType = 'individual' | 'group'; type MessageRequestBody<T extends MessageTypesEnum> = GeneralMessageBody & { recipient_type?: MessageRecipientType; to: string; context?: ConTextObject; type?: T; }; interface MessageRequestParams<T> { body: T; to: string; recipientType?: MessageRecipientType; replyMessageId?: string; } interface StatusParams { status: StatusObject['status']; messageId: string; typingIndicator?: TypingIndicatorObject; } type MessagesResponse = GeneralMessageBody & { contacts: Array<{ input: string; wa_id: string; }>; messages: Array<{ id: string; message_status?: 'accepted' | 'held_for_quality_assessment' | 'paused'; }>; }; type EncryptedMessageRequest = { messaging_product: 'whatsapp'; encrypted_contents: string; }; type EncryptedMessagesResponse = { encrypted_contents: string; }; declare class MessagesClass extends BaseClass { text(params: TextMessageParams): Promise<MessagesResponse>; template(params: MessageRequestParams<MessageTemplateObject<ComponentTypesEnum>>): Promise<MessagesResponse>; audio(params: MessageRequestParams<AudioMediaObject>): Promise<MessagesResponse>; document(params: MessageRequestParams<DocumentMediaObject>): Promise<MessagesResponse>; image(params: MessageRequestParams<ImageMediaObject>): Promise<MessagesResponse>; video(params: MessageRequestParams<VideoMediaObject>): Promise<MessagesResponse>; sticker(params: MessageRequestParams<StickerMediaObject>): Promise<MessagesResponse>; contacts(params: MessageRequestParams<ContactObject[]>): Promise<MessagesResponse>; location(params: MessageRequestParams<LocationObject>): Promise<MessagesResponse>; interactive(params: MessageRequestParams<InteractiveObject>): Promise<MessagesResponse>; interactiveList(params: MessageRequestParams<InteractiveObject & { type: InteractiveTypesEnum.List; }>): Promise<MessagesResponse>; interactiveCtaUrl(params: MessageRequestParams<InteractiveObject & { type: InteractiveTypesEnum.CtaUrl; }>): Promise<MessagesResponse>; interactiveLocationRequest(params: MessageRequestParams<InteractiveObject & { type: InteractiveTypesEnum.LocationRequest; }>): Promise<MessagesResponse>; interactiveAddressMessage(params: MessageRequestParams<InteractiveObject & { type: InteractiveTypesEnum.AddressMessage; }>): Promise<MessagesResponse>; interactiveReplyButtons(params: MessageRequestParams<InteractiveObject & { type: InteractiveTypesEnum.Button; }>): Promise<MessagesResponse>; interactiveFlow(params: MessageRequestParams<InteractiveObject & { type: InteractiveTypesEnum.Flow; }>): Promise<MessagesResponse>; interactiveCarousel(params: MessageRequestParams<InteractiveObject & { type: InteractiveTypesEnum.Carousel; }>): Promise<MessagesResponse>; reaction(params: ReactionParams): Promise<MessagesResponse>; encrypted(params: EncryptedMessageRequest): Promise<EncryptedMessagesResponse>; markAsRead(params: { messageId: string; }): Promise<StatusResponse>; showTypingIndicator(params: { messageId: string; }): Promise<StatusResponse>; status(params: StatusParams): Promise<StatusResponse>; } //#endregion //#region src/api/marketingMessages/types/marketingMessages.d.ts /** * Marketing Messages API Types * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/marketing-messages/send-marketing-messages/ */ type MarketingMessageRequest = { to: string; template: MessageTemplateObject<ComponentTypesEnum>; message_activity_sharing?: boolean; product_policy?: 'CLOUD_API_FALLBACK' | 'STRICT'; }; interface MarketingMessagesClass { sendTemplateMessage(params: MarketingMessageRequest): Promise<MessagesResponse>; } //#endregion //#region src/api/media/types/common.d.ts type MediaResponse = { id: string; url: string; mime_type: string; sha256: string; file_size: number; messaging_product: 'whatsapp'; }; type MediasResponse = { data: MediaResponse[]; paging: { cursors: { before: string; after: string; }; }; }; type UploadMediaResponse = { id: string; }; interface MediaClass { getMediaById(mediaId: string): Promise<MediaResponse>; uploadMedia(file: File, messagingProduct?: string): Promise<UploadMediaResponse>; deleteMedia(mediaId: string): Promise<ResponseSuccess>; downloadMedia(mediaUrl: string): Promise<Blob>; } //#endregion //#region src/api/payments/types/payments.d.ts /** * Payments API Types (India Payment Configuration) * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/ */ type PaymentConfigurationProvider = 'upi_vpa' | 'razorpay' | 'payu' | 'zaakpay'; type PaymentConfigurationStatus = 'Active' | 'Needs_Connecting' | 'Needs_Testing'; type PaymentConfigurationCode = { code: string; description?: string; }; type PaymentConfiguration = { configuration_name: string; provider_name: string; provider_mid?: string; status?: PaymentConfigurationStatus; merchant_category_code?: PaymentConfigurationCode; purpose_code?: PaymentConfigurationCode; created_timestamp?: number; updated_timestamp?: number; }; type PaymentConfigurationsResponse = { data: Array<{ payment_configurations: PaymentConfiguration[]; }>; }; type PaymentConfigurationCreateRequest = { configuration_name: string; provider_name: PaymentConfigurationProvider; purpose_code?: string; merchant_category_code?: string; redirect_url?: string; merchant_vpa?: string; }; type PaymentConfigurationUpdateRequest = { provider_name?: PaymentConfigurationProvider; purpose_code?: string; merchant_category_code?: string; redirect_url?: string; merchant_vpa?: string; }; type PaymentConfigurationCreateResponse = { success: boolean; oauth_url?: string; expiration?: number; }; type PaymentConfigurationUpdateResponse = PaymentConfigurationCreateResponse; type PaymentConfigurationOauthLinkRequest = { configuration_name: string; redirect_url?: string; }; type PaymentConfigurationOauthLinkResponse = { oauth_url: string; expiration?: number; }; type PaymentConfigurationDeleteRequest = { configuration_name: string; }; interface PaymentsClass { listPaymentConfigurations(wabaId: string): Promise<PaymentConfigurationsResponse>; getPaymentConfiguration(wabaId: string, configurationName: string): Promise<PaymentConfigurationsResponse>; createPaymentConfiguration(wabaId: string, params: PaymentConfigurationCreateRequest): Promise<PaymentConfigurationCreateResponse>; updatePaymentConfiguration(wabaId: string, configurationName: string, params: PaymentConfigurationUpdateRequest): Promise<PaymentConfigurationUpdateResponse>; generatePaymentConfigurationOauthLink(wabaId: string, params: PaymentConfigurationOauthLinkRequest): Promise<PaymentConfigurationOauthLinkResponse>; deletePaymentConfiguration(wabaId: string, params: PaymentConfigurationDeleteRequest): Promise<ResponseSuccess>; } //#endregion //#region src/api/phone/types/common.d.ts type QualityRating = 'GREEN' | 'YELLOW' | 'RED' | 'NA' | 'UNKNOWN'; type AccountMode = 'LIVE' | 'SANDBOX'; type CodeVerificationStatus = 'NOT_VERIFIED' | 'VERIFIED' | 'EXPIRED' | 'PENDING' | 'DELETED' | 'MIGRATED' | 'BANNED' | 'RESTRICTED' | 'RATE_LIMITED' | 'FLAGGED' | 'CONNECTED' | 'DISCONNECTED' | 'UNKNOWN' | 'UNVERIFIED'; type MessagingLimitTier = 'TIER_50' | 'TIER_250' | 'TIER_1K' | 'TIER_2K' | 'TIER_10K' | 'TIER_100K' | 'TIER_UNLIMITED' | (string & {}); type PlatformType = 'CLOUD_API' | 'ON_PREMISE' | 'NOT_APPLICABLE'; type ThroughputLevel = 'STANDARD' | 'HIGH' | 'NOT_APPLICABLE'; type PhoneNumberStatus = 'PENDING' | 'LINKED' | 'UNLINKED' | 'DELETED' | 'MIGRATED' | 'BANNED' | 'RESTRICTED'; type UnifiedCertStatus = 'APPROVED' | 'PENDING' | 'REJECTED' | 'EXPIRED' | 'NONE' | string; type HostPlatform = 'CLOUD_API' | 'ON_PREMISE' | 'NOT_APPLICABLE' | string; type HealthStatusEntity = { entity_type: string; id: string; can_send_message: string; additional_info?: string[]; errors?: Array<{ error_code: number; error_description: string; possible_solution: string; }>; }; type HealthStatus = { can_send_message: string; entities: HealthStatusEntity[]; }; type QualityScore = { score: QualityRating; }; type Throughput = { level: ThroughputLevel; }; type PhoneNumberField = 'country_code' | 'country_dial_code' | 'display_phone_number' | 'id' | 'quality_rating' | 'verified_name' | 'account_mode' | 'certificate' | 'code_verification_status' | 'conversational_automation' | 'eligibility_for_api_business_global_search' | 'health_status' | 'host_platform' | 'is_official_business_account' | 'is_on_biz_app' | 'is_pin_enabled' | 'is_preverified_number' | 'last_onboarded_time' | 'messaging_limit_tier' | 'name_status' | 'new_certificate' | 'new_name_status' | 'platform_type' | 'quality_score' | 'search_visibility' | 'status' | 'throughput' | 'unified_cert_status' | 'username'; type PhoneNumberFieldsParam = PhoneNumberField[] | string; type PhoneNumberSort = 'creation_time.asc' | 'creation_time.desc' | 'last_onboarded_time.asc' | 'last_onboarded_time.desc' | (string & {}); type PhoneNumberFilter = Record<string, unknown>; type PhoneNumbersListParams = { fields?: PhoneNumberFieldsParam; filtering?: PhoneNumberFilter[] | string; sort?: PhoneNumberSort; limit?: number; after?: string; before?: string; }; type GraphObject = Record<string, unknown>; type CreatePhoneNumberRequest = { cc?: string; phone_number?: string; verified_name?: string; preverified_id?: string; [key: string]: unknown; }; type CreatePhoneNumberResponse = { id: string; [key: string]: unknown; }; type UpdatePhoneNumberStatusRequest = { connection_status?: 'CONNECTED' | 'DISCONNECTED' | (string & {}); webhook_url?: string; whatsapp_business_api_data?: Record<string, unknown>; pin?: string; }; type PhoneNumberSettingsFieldsParam = string[] | string; type PhoneNumberSettingsParams = { fields?: PhoneNumberSettingsFieldsParam; include_sip_credentials?: boolean; }; type PhoneNumberSettingsResponse = GraphObject; type UpdatePhoneNumberSettingsRequest = { calling?: GraphObject; [key: string]: unknown; }; type OfficialBusinessAccountStatusResponse = GraphObject; type OfficialBusinessAccountAction = 'SUBMIT_APPLICATION' | 'WITHDRAW_APPLICATION' | 'RESUBMIT_APPLICATION'; type OfficialBusinessAccountApplicationData = { business_name?: string; business_description?: string; /** * OBA examples use `website_url`, while the schema also exposes `business_website_url`. * Both are accepted to track Meta's published OpenAPI variants. */ website_url?: string; business_website_url?: string; contact_email?: string; primary_country_of_operation?: string; primary_language?: string; parent_business_or_brand?: string; [key: string]: unknown; }; type UpdateOfficialBusinessAccountStatusRequest = { action?: OfficialBusinessAccountAction | (string & {}); application_data?: OfficialBusinessAccountApplicationData; business_website_url?: string; primary_country_of_operation?: string; [key: string]: unknown; }; type BusinessComplianceInfoResponse = GraphObject; type UpdateBusinessComplianceInfoRequest = { [key: string]: unknown; }; type PhoneNumberResponse = { display_phone_number: string; id: string; quality_rating: QualityRating; verified_name: string; account_mode?: AccountMode; certificate?: string; code_verification_status?: CodeVerificationStatus; conversational_automation?: Record<string, unknown>; country_code?: string; country_dial_code?: string; eligibility_for_api_business_global_search?: string; health_status?: HealthStatus; host_platform?: HostPlatform; is_official_business_account?: boolean; is_on_biz_app?: boolean; is_pin_enabled?: boolean; is_preverified_number?: boolean; last_onboarded_time?: string; messaging_limit_tier?: MessagingLimitTier; name_status?: string; new_certificate?: string; new_name_status?: string; platform_type?: PlatformType; quality_score?: QualityScore; search_visibility?: string; status?: PhoneNumberStatus | CodeVerificationStatus; throughput?: Throughput; unified_cert_status?: UnifiedCertStatus; username?: string; }; type Cursors = { before: string; after: string; }; type PhoneNumbersResponse = { data: PhoneNumberResponse[]; paging: Paging; }; type RequestVerificationCodeRequest = { code_method: 'SMS' | 'VOICE'; language: string; }; type VerifyCodeRequest = { code: string; }; type TwoStepVerificationParams = { pin: string; }; /** * Conversational Components - Commands */ type ConversationalCommand = { command_name: string; command_description: string; }; /** * Conversational Components - Ice Breakers (Prompts) */ type ConversationalPrompt = string; /** * Request payload for configuring conversational automation */ type ConversationalAutomationRequest = { enable_welcome_message?: boolean; commands?: ConversationalCommand[]; prompts?: ConversationalPrompt[]; }; /** * Response from conversational automation GET endpoint */ type ConversationalAutomationResponse = { enable_welcome_message?: boolean; commands?: ConversationalCommand[]; prompts?: ConversationalPrompt[]; id: string; }; /** * Response from throughput GET endpoint */ type ThroughputResponse = { throughput: Throughput; id: string; }; interface PhoneNumberClass { getPhoneNumberById(fields?: PhoneNumberFieldsParam): Promise<PhoneNumberResponse>; getPhoneNumbers(params?: PhoneNumbersListParams): Promise<PhoneNumbersResponse>; createPhoneNumber(request: CreatePhoneNumberRequest, wabaId?: string): Promise<CreatePhoneNumberResponse>; updatePhoneNumberStatus(request: UpdatePhoneNumberStatusRequest): Promise<ResponseSuccess>; requestVerificationCode(params: RequestVerificationCodeRequest): Promise<ResponseSuccess>; verifyCode(params: VerifyCodeRequest): Promise<ResponseSuccess>; getPhoneNumberSettings(params?: PhoneNumberSettingsParams): Promise<PhoneNumberSettingsResponse>; updatePhoneNumberSettings(params: UpdatePhoneNumberSettingsRequest): Promise<ResponseSuccess>; setConversationalAutomation(params: ConversationalAutomationRequest): Promise<ResponseSuccess>; getConversationalAutomation(): Promise<ConversationalAutomationResponse>; getThroughput(): Promise<ThroughputResponse>; getOfficialBusinessAccountStatus(): Promise<OfficialBusinessAccountStatusResponse>; updateOfficialBusinessAccountStatus(params: UpdateOfficialBusinessAccountStatusRequest): Promise<ResponseSuccess>; getBusinessComplianceInfo(): Promise<BusinessComplianceInfoResponse>; updateBusinessComplianceInfo(params: UpdateBusinessComplianceInfoRequest): Promise<ResponseSuccess>; } //#endregion //#region src/api/profile/types/upload.d.ts /** * Response from creating an upload session. */ interface UploadSessionResponse { id: string; } /** * Response from uploading business profile media. */ interface UploadBusinessProfileResponse { h: string; } /** * Upload handle information containing file details and handle. */ interface UploadHandle { handle: string; file_size: number; upload_result: { handle_type: string; name: string; }; } //#endregion //#region src/api/profile/types/common.d.ts /** * Available fields that can be requested when retrieving a business profile. */ type BusinessProfileField = 'about' | 'address' | 'description' | 'email' | 'messaging_product' | 'profile_picture_url' | 'websites' | 'vertical'; type BusinessProfileFieldsParam = BusinessProfileField[] | string; /** * Business profile data structure containing all profile information. */ interface BusinessProfileData { /** * The business's About text. This text appears in the business's profile, beneath its profile image, * phone number, and contact buttons. * - String cannot be empty * - Strings must be between 1 and 139 characters * - Rendered emojis are supported however their unicode values are not. * Emoji unicode values must be Java- or JavaScript-escape encoded * - Hyperlinks can be included but will not render as clickable links * - Markdown is not supported */ about?: string; /** * Address of the business. Character limit 256. */ address?: string; /** * Description of the business. Character limit 512. */ description?: string; /** * The contact email address (in valid email format) of the business. Character limit 128. */ email?: string; /** * The messaging service used for the request. Always set it to "whatsapp" if you are using * the WhatsApp Business API. */ messaging_product: string; /** * Profile picture URL. */ profile_picture_url?: string; /** * The URLs associated with the business. For instance, a website, Facebook Page, or Instagram. * - You must include the http:// or https:// portion of the URL * - There is a maximum of 2 websites with a maximum of 256 characters each */ websites?: string[]; /** * Business category. This can be either an empty string or one of the predefined business categories. * @see BusinessVerticalEnum for all available options */ vertical?: BusinessVerticalEnum | string; } /** * Response structure for business profile GET requests. */ interface BusinessProfileResponse { data: BusinessProfileData[]; } /** * Request structure for updating business profile. */ interface UpdateBusinessProfileRequest { /** * The messaging service used for the request. Always set it to "whatsapp" if you are using * the WhatsApp Business API. * @required */ messaging_product: string; /** * The business's About text. This text appears in the business's profile, beneath its profile image, * phone number, and contact buttons. * - String cannot be empty * - Strings must be between 1 and 139 characters * - Rendered emojis are supported however their unicode values are not. * Emoji unicode values must be Java- or JavaScript-escape encoded * - Hyperlinks can be included but will not render as clickable links * - Markdown is not supported */ about?: string; /** * Address of the business. Character limit 256. */ address?: string; /** * Description of the business. Character limit 512. */ description?: string; /** * Business category. This can be either an empty string or one of the predefined business categories. * @see BusinessVerticalEnum for all available options */ vertical?: BusinessVerticalEnum | string; /** * The contact email address (in valid email format) of the business. Character limit 128. */ email?: string; /** * The URLs associated with the business. For instance, a website, Facebook Page, or Instagram. * - You must include the http:// or https:// portion of the URL * - There is a maximum of 2 websites with a maximum of 256 characters each */ websites?: string[]; /** * Handle of the profile picture. This handle is generated when you upload the binary file * for the profile picture to Meta using the Resumable Upload API. */ profile_picture_handle?: string; } declare class BusinessProfileClass extends BaseClass { /** * Get your business profile. * @param fields Specific fields to be returned in the response. If not specified, all fields will be returned. */ getBusinessProfile(fields?: BusinessProfileFieldsParam): Promise<BusinessProfileResponse>; /** * Update your business profile. * @param updateRequest The request object containing the fields to update. */ updateBusinessProfile(updateRequest: UpdateBusinessProfileRequest): Promise<ResponseSuccess>; /** * Create an upload session for profile picture. * @param fileLength Length of the file to be uploaded in bytes. * @param fileType MIME type of the file (e.g., 'image/jpeg'). * @param fileName Name of the file. */ createUploadSession(fileLength: number, fileType: string, fileName: string): Promise<UploadSessionResponse>; /** * Upload media file to the upload session. * @param uploadId The ID of the upload session. * @param file The binary data of the file. */ uploadMedia(uploadId: string, file: Buffer): Promise<UploadBusinessProfileResponse>; /** * Get the upload handle information. * @param uploadId The ID of the upload session. */ getUploadHandle(uploadId: string): Promise<UploadHandle>; } //#endregion //#region src/api/qrCode/types/common.d.ts type QrCodeResponse = { code: string; prefilled_message: string; deep_link_url: string; qr_image_url?: string; }; type QrCodesResponse = ResponseData<QrCodeResponse[]>; type CreateQrCodeRequest = { prefilled_message: string; generate_qr_image?: 'SVG' | 'PNG'; }; type UpdateQrCodeRequest = { code: string; prefilled_message: string; }; interface QrCodeClass { createQrCode(request: CreateQrCodeRequest): Promise<QrCodeResponse>; getQrCodes(): Promise<QrCodesResponse>; getQrCode(qrCodeId: string): Promise<QrCodeResponse>; updateQrCode(request: UpdateQrCodeRequest): Promise<QrCodeResponse>; deleteQrCode(qrCodeId: string): Promise<ResponseSuccess>; } //#endregion //#region src/api/registration/types/common.d.ts type RegistrationRequest = { messaging_product: 'whatsapp'; pin: string; data_localization_region?: DataLocalizationRegionEnum; }; interface RegistrationClass { register(pin: string, dataLocalizationRegion?: DataLocalizationRegionEnum): Promise<ResponseSuccess>; deregister(): Promise<ResponseSuccess>; } //#endregion //#region src/api/template/types/common.d.ts type TemplateFormat = 'TEXT' | 'IMAGE' | 'VIDEO' | 'DOCUMENT' | 'LOCATION' | 'PRODUCT'; type PhoneNumberButton = { type: 'PHONE_NUMBER'; text: string; phone_number: string; }; type URLB