### CLI: Start WhatsApp Emulator with Media Persistence Options Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/emulator/README.md Command-line interface examples for starting the WhatsApp emulator with various media persistence configurations, including import, export, and specifying paths. ```bash # Import only (no export) wa-emulator start --number 15550123456 --import ./emulator-data # Import and export to same location wa-emulator start --number 15550123456 --import ./emulator-data --export-on-exit # Import and export to different locations wa-emulator start --number 15550123456 --import ./old-data --export-on-exit ./new-data # Export only wa-emulator start --number 15550123456 --export-on-exit ./emulator-data ``` -------------------------------- ### Start WhatsApp Emulator (TypeScript) Source: https://context7.com/ericvera/whatsapp-cloudapi/llms.txt Provides examples of initializing and starting the `WhatsAppEmulator` from '@whatsapp-cloudapi/emulator'. Demonstrates basic setup, full configuration with webhooks and persistence, and error handling. ```typescript import { WhatsAppEmulator } from '@whatsapp-cloudapi/emulator' // Basic emulator setup const emulator = new WhatsAppEmulator({ businessPhoneNumberId: '15550123456', port: 3000, }) await emulator.start() console.log('Emulator running on port 3000') // Clean shutdown await emulator.stop() // Full configuration with webhook and persistence const fullEmulator = new WhatsAppEmulator({ businessPhoneNumberId: '15550123456', port: 4004, host: 'localhost', delay: 100, // Simulate 100ms network delay webhook: { url: 'https://your-app.com/webhook', secret: 'webhook-verification-secret', timeout: 5000, // 5 second timeout }, persistence: { importPath: './emulator-data', exportOnExit: './emulator-data', shouldExport: true, }, log: { level: 'verbose', // 'quiet' | 'normal' | 'verbose' }, }) await fullEmulator.start() // Error handling try { await emulator.start() } catch (error) { console.error('Failed to start emulator:', error.message) // Possible errors: port in use, invalid configuration } ``` -------------------------------- ### Quick Start: Initialize and Run WhatsApp Emulator Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/emulator/README.md A basic TypeScript example demonstrating how to initialize and start the WhatsApp Cloud API Emulator. It shows essential configuration options like phone number ID, port, webhook, persistence, and logging. ```typescript import { WhatsAppEmulator } from '@whatsapp-cloudapi/emulator' // Create a new emulator instance const emulator = new WhatsAppEmulator({ businessPhoneNumberId: '15550123456', // The phone number ID to emulate port: 3000, // Optional, defaults to 4004 webhook: { url: 'https://your-webhook-endpoint.com/webhook', // URL to receive webhook events secret: 'your-webhook-secret', // Required secret for webhook verification timeout: 5000, // Optional timeout in milliseconds (defaults to 5000) }, persistence: { importPath: './emulator-data', // Optional: Import media metadata on startup exportOnExit: './emulator-data', // Optional: Export media metadata on shutdown shouldExport: true, // Required when exportOnExit is specified }, log: { level: 'normal', // Optional: 'quiet' | 'normal' | 'verbose' (defaults to 'quiet') }, }) // Start the emulator await emulator.start() // The emulator is now running and ready to accept requests // Use it in your tests or development environment // When done, stop the emulator await emulator.stop() ``` -------------------------------- ### Install WhatsApp Cloud API Emulator Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/emulator/README.md Instructions for installing the emulator package using npm or yarn. This is the first step to integrating the emulator into your project. ```bash npm install @whatsapp-cloudapi/emulator # or yarn add @whatsapp-cloudapi/emulator ``` -------------------------------- ### Start WhatsApp Cloud API Emulator Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/cli/README.md Starts the WhatsApp Cloud API emulator with various configuration options. Key options include specifying the business phone number, webhook URL and secret for receiving events, port and host for the emulator, and settings for media persistence and logging levels. ```bash # Start the emulator with webhook configuration (required for simulation) wa-emulator start --number 15550123456 \ --webhook-url http://localhost:8080/webhook \ --webhook-secret my-secret-key # Check if the emulator is running wa-emulator status # Simulate an incoming message wa-emulator simulate text --message "Hello, I need help!" # Basic usage without webhooks wa-emulator start --number 15550123456 # With custom port and host wa-emulator start --port 3000 --host 0.0.0.0 --number 15550123456 # With webhook configuration (required for simulation) wa-emulator start --number 15550123456 \ --webhook-url http://localhost:8080/webhook \ --webhook-secret my-secret-key # With media persistence - import only wa-emulator start --number 15550123456 --import ./emulator-data # With media persistence - import and export to same location wa-emulator start --number 15550123456 --import ./emulator-data --export-on-exit # With media persistence - import and export to different locations wa-emulator start --number 15550123456 --import ./old-data --export-on-exit ./new-data # Export only (no import) wa-emulator start --number 15550123456 --export-on-exit ./emulator-data # With verbose logging for debugging wa-emulator start --number 15550123456 --log-level verbose # With normal logging (includes webhook events) wa-emulator start --number 15550123456 \ --webhook-url http://localhost:8080/webhook \ --webhook-secret my-secret \ --log-level normal ``` -------------------------------- ### Example: Flow with Video Header (TypeScript) Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/client/README.md Provides an example of sending a WhatsApp Flow message with a video header. This is useful for tutorials or promotional content, specifying a video link for the header. ```typescript // Send a flow message with video header const response = await sendFlowMessage({ accessToken: 'YOUR_ACCESS_TOKEN', from: 'YOUR_PHONE_NUMBER_ID', to: '+16505551234', bodyText: 'Watch our tutorial and complete the setup process.', flowToken: 'SETUP_TOKEN_456', flowId: 'SETUP_FLOW_789', flowCta: 'Start Setup', flowAction: 'navigate', screen: 'tutorial_screen', headerVideo: { link: 'https://example.com/tutorial.mp4' }, }) ``` -------------------------------- ### Emulator CLI Commands Source: https://context7.com/ericvera/whatsapp-cloudapi/llms.txt Demonstrates common command-line interface operations for the WhatsApp emulator, such as simulating messages, checking status, and starting the emulator with specific configurations for media persistence and logging. ```bash # Auto-generate phone number wa-emulator simulate text --message "What are your hours?" # Check emulator status wa-emulator status # Start with media persistence wa-emulator start --number 15550123456 \ --import ./emulator-data \ --export-on-exit # Start with verbose logging wa-emulator start --number 15550123456 \ --log-level verbose \ --webhook-url http://localhost:8080/webhook \ --webhook-secret test-secret ``` -------------------------------- ### Example: Navigate Flow with Text Header (TypeScript) Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/client/README.md Demonstrates how to send a WhatsApp Flow message for navigation with a text header. This example includes the necessary parameters for initiating a flow, specifying a screen to navigate to, and adding header and footer text. ```typescript import { sendFlowMessage } from '@whatsapp-cloudapi/client' // Send a flow message that navigates to a specific screen const response = await sendFlowMessage({ accessToken: 'YOUR_ACCESS_TOKEN', from: 'YOUR_PHONE_NUMBER_ID', to: '+16505551234', bodyText: 'Complete your loan application form to get started.', flowToken: 'FLOW_SESSION_TOKEN_123', flowId: 'FLOW_ID_456', flowCta: 'Start Application', flowAction: 'navigate', screen: 'welcome_screen', headerText: 'Loan Application', footerText: 'Secure and fast process', }) console.log('Flow message sent:', response.messages[0].id) ``` -------------------------------- ### Install WhatsApp Cloud API Client Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/client/README.md Installs the WhatsApp Cloud API client package using either npm or yarn. This is the first step to using the library in your Node.js project. ```bash npm install @whatsapp-cloudapi/client # or yarn add @whatsapp-cloudapi/client ``` -------------------------------- ### Example Unhandled Request Log Output Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/emulator/README.md Demonstrates the console log output when an unsupported endpoint is requested. It includes the request method, path, headers, and body, aiding in debugging. ```text ❌ Unhandled request: POST /v15.0/1234567890/media Headers: { "content-type": "application/json", "authorization": "Bearer your-token" } Body: { "messaging_product": "whatsapp", "media": {...} } ``` -------------------------------- ### Install WhatsApp Cloud API CLI Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/cli/README.md Installs the WhatsApp Cloud API CLI globally using npm or yarn package managers. This tool is essential for interacting with the WhatsApp Cloud API emulator. ```bash npm install -g @whatsapp-cloudapi/cli # or yarn global add @whatsapp-cloudapi/cli ``` -------------------------------- ### Simulate Incoming Messages using WhatsApp Emulator CLI (Bash) Source: https://context7.com/ericvera/whatsapp-cloudapi/llms.txt Demonstrates using the `wa-emulator` command-line interface to start the emulator with webhook configurations and simulate incoming text messages. This is useful for testing webhook handlers. ```bash # Start emulator with webhook wa-emulator start --number 15550123456 \ --webhook-url http://localhost:8080/webhook \ --webhook-secret my-secret-key # Simulate incoming text message wa-emulator simulate text \ --from +1234567890 \ --name "John Doe" \ --message "Hello, I need help with my order!" ``` -------------------------------- ### Example Unhandled Request Error Response Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/emulator/README.md Illustrates the JSON error response returned by the emulator for an unsupported endpoint. This response includes an error message, a list of available routes, and a link to documentation. ```json { "error": "Route not found", "message": "The endpoint POST /v15.0/1234567890/media is not supported by the WhatsApp Cloud API emulator", "availableRoutes": [ "GET /are-you-ok", "POST /v{version}/1234567890/messages", "POST /simulate/incoming/text" ], "documentation": "See the emulator documentation for supported endpoints" } ``` -------------------------------- ### Example: Data Exchange Flow with Image Header (TypeScript) Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/client/README.md Illustrates sending a WhatsApp Flow message for data exchange, featuring an image header. This example shows how to provide user-specific data and reference a media ID for the header. ```typescript // Send a flow message for data exchange with image header const response = await sendFlowMessage({ accessToken: 'YOUR_ACCESS_TOKEN', from: 'YOUR_PHONE_NUMBER_ID', to: '+16505551234', bodyText: 'Update your preferences with our interactive form.', flowToken: 'FLOW_TOKEN_789', flowId: 'PREFERENCES_FLOW_101', flowCta: 'Update Preferences', flowAction: 'data_exchange', data: { userId: '12345', currentPlan: 'premium' }, headerImage: { id: 'MEDIA_ID_FROM_UPLOAD' }, }) ``` -------------------------------- ### Install WhatsApp Cloud API Types Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/types/README.md Installs the @whatsapp-cloudapi/types package using either npm or yarn. This package provides TypeScript definitions for the WhatsApp Cloud API. ```bash npm install @whatsapp-cloudapi/types # or yarn add @whatsapp-cloudapi/types ``` -------------------------------- ### Example: Error Handling for sendFlowMessage (TypeScript) Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/client/README.md Demonstrates robust error handling when sending a WhatsApp Flow message. This example uses a try-catch block to capture potential issues such as missing required parameters or API authentication errors. ```typescript try { await sendFlowMessage({ accessToken: 'YOUR_ACCESS_TOKEN', from: 'YOUR_PHONE_NUMBER_ID', to: '+16505551234', bodyText: 'Complete our survey.', flowToken: 'FLOW_TOKEN_123', flowId: 'SURVEY_FLOW_456', flowCta: 'Start Survey', flowAction: 'navigate', // Missing required 'screen' parameter }) } catch (error) { // Possible errors: // - Screen parameter required for navigate action // - Body text too long (>1024 characters) // - Header text too long (>60 characters) // - Footer text too long (>60 characters) // - Multiple header types specified // - API authentication errors console.error('Failed to send flow message:', error.message) } ``` -------------------------------- ### JSON: Example Media Manifest Data Format Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/emulator/README.md The structure of the `media-manifest.json` file used by the WhatsApp Emulator for persisting media metadata. It includes details about each media item like ID, filename, type, size, and expiration. ```json { "version": "1.0", "exportedAt": "2024-01-15T10:30:00.000Z", "media": [ { "id": "abc123", "filename": "image.jpg", "mimeType": "image/jpeg", "size": 2048576, "uploadedAt": "2024-01-15T10:15:00.000Z", "expiresAt": "2024-02-14T10:15:00.000Z" } ] } ``` -------------------------------- ### Configure Emulator Logging (TypeScript) Source: https://context7.com/ericvera/whatsapp-cloudapi/llms.txt Demonstrates how to configure logging levels for the WhatsApp emulator using the `@whatsapp-cloudapi/emulator` package in TypeScript. It shows examples for 'quiet', 'normal', and 'verbose' logging modes, along with sample outputs for different log types. ```typescript import { WhatsAppEmulator } from '@whatsapp-cloudapi/emulator' // Quiet mode (default) - shows only messages, events, and errors const quietEmulator = new WhatsAppEmulator({ businessPhoneNumberId: '15550123456', log: { level: 'quiet' }, }) // Normal mode - adds webhook delivery status const normalEmulator = new WhatsAppEmulator({ businessPhoneNumberId: '15550123456', log: { level: 'normal' }, webhook: { url: 'http://localhost:8080/webhook', secret: 'test-secret', }, }) // Verbose mode - includes HTTP requests, media ops, validation errors const verboseEmulator = new WhatsAppEmulator({ businessPhoneNumberId: '15550123456', log: { level: 'verbose' }, }) await verboseEmulator.start() // Message bubble example output (all levels): // ╭─────────────────────────────────────────────────────╮ // │ To: +1234567890 │ // │ │ // │ Hello! How can I help you today? │ // │ 9:45 │ // ╰─────────────────────────────────────────────────────╯ // HTTP request log (verbose only): // → POST /v15.0/1234567890/messages [200] 45ms // Webhook log (normal and verbose): // ✓ Webhook delivered: http://localhost:8080/webhook [200] // Unhandled request (all levels): // ❌ Unhandled request: POST /v15.0/1234567890/unsupported // Body: { "type": "custom", "data": {...} } ``` -------------------------------- ### Webhook Events and Validation Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/emulator/README.md Explains how the emulator handles webhook events for message status updates and the process for validating the webhook endpoint using GET /webhook. ```APIDOC ## Webhook Integration ### Webhook Events When enabled, the emulator sends webhook events to the configured URL for message status updates. The payload structure adheres to the official WhatsApp Cloud API format. ### Webhook Validation - **GET /webhook**: Handles the WhatsApp Cloud API verification flow. - **Query Parameters**: - **`hub.mode`** (string) - Required - Must be `subscribe`. - **`hub.verify_token`** (string) - Required - The token configured in `EmulatorOptions.webhook.secret`. - **`hub.challenge`** (string) - Required - A random string to be echoed back. - **Response**: Returns the `hub.challenge` value if `hub.verify_token` matches the secret. ### Example Webhook Payload ```json { "object": "whatsapp_business_account", "entry": [ { "id": "15550123456", "changes": [ { "value": { "messaging_product": "whatsapp", "metadata": { "display_phone_number": "15550123456", "phone_number_id": "15550123456" }, "statuses": [ { "id": "message_id", "recipient_id": "recipient_phone_number", "status": "sent", "timestamp": "1234567890", "conversation": { "id": "conversation_id", "origin": { "type": "utility" } } } ] }, "field": "messages" } ] } ] } ``` ``` -------------------------------- ### Use WhatsApp Cloud API Client with Emulator Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/client/README.md Shows how to integrate the WhatsApp Cloud API client with the provided emulator for testing. This involves starting the emulator and configuring the client to use the emulator's base URL. ```typescript import { sendTextMessage } from '@whatsapp-cloudapi/client' import { WhatsAppEmulator } from '@whatsapp-cloudapi/emulator' // Start the emulator const emulator = new WhatsAppEmulator({ businessPhoneNumberId: 'YOUR_PHONE_NUMBER_ID', port: 4004, }) await emulator.start() // Send messages to the emulator instead of the live API const response = await sendTextMessage({ accessToken: 'fake-token', // Any string works with emulator from: 'YOUR_PHONE_NUMBER_ID', to: '+1234567890', text: 'Hello from emulator!', baseUrl: 'http://localhost:4004', // Point to emulator }) // Clean up await emulator.stop() ``` -------------------------------- ### Simulate Incoming Message via HTTP (TypeScript) Source: https://context7.com/ericvera/whatsapp-cloudapi/llms.txt Shows how to simulate an incoming WhatsApp message programmatically using `fetch` in TypeScript. It sends a POST request to the emulator's simulation endpoint and logs the response. Also includes an example of a generated webhook payload for incoming messages. ```typescript // Simulate incoming message via HTTP const response = await fetch('http://localhost:4004/simulate/incoming/text', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ from: '+1234567890', name: 'John Doe', message: 'Hello, I need help with my order!', }), }) const result = await response.json() console.log(result) // Output: { success: true, messageSimulated: true } // Generated webhook payload const webhookPayload = { object: 'whatsapp_business_account', entry: [{ id: '15550123456', changes: [{ value: { messaging_product: 'whatsapp', metadata: { display_phone_number: '15550123456', phone_number_id: '15550123456', }, contacts: [{ wa_id: '+1234567890', profile: { name: 'John Doe' }, }], messages: [{ id: 'mock_incoming_1234567890_abc123', from: '+1234567890', timestamp: '1734567890', type: 'text', text: { body: 'Hello, I need help with my order!' }, }], }, field: 'messages', }], }], } ``` -------------------------------- ### Example: Uploading and Sending an Image Message Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/client/README.md Demonstrates the complete process of uploading an image to the WhatsApp Cloud API and then sending it as a message. It involves creating a Blob from image data, calling `uploadMedia`, and then using the returned media ID with `sendImageMessage`. ```typescript import { uploadMedia, sendImageMessage } from '@whatsapp-cloudapi/client' // Step 1: Create Blob from image data const response = await fetch('/path/to/image.jpg') const imageBlob = await response.blob() // Step 2: Upload the image const mediaResponse = await uploadMedia({ accessToken: 'YOUR_ACCESS_TOKEN', from: 'YOUR_PHONE_NUMBER_ID', file: imageBlob, }) // Step 3: Send the image message const messageResponse = await sendImageMessage({ accessToken: 'YOUR_ACCESS_TOKEN', from: 'YOUR_PHONE_NUMBER_ID', to: '+1234567890', mediaId: mediaResponse.id, caption: 'Check out this image!', }) console.log('Media ID:', mediaResponse.id) console.log('Message sent:', messageResponse.messages[0].id) ``` -------------------------------- ### WhatsAppEmulator Class Definition and Usage (TypeScript) Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/emulator/README.md Defines the WhatsAppEmulator class for creating and managing a WhatsApp Cloud API emulator instance. Includes methods for starting and stopping the server, and demonstrates error handling for server startup. ```typescript class WhatsAppEmulator { constructor(options: EmulatorOptions) start(): Promise stop(): Promise } interface EmulatorOptions { /** Business phone number ID to emulate */ businessPhoneNumberId: string /** Port to run the emulator server on (defaults to 4004) */ port?: number /** Host to bind to (defaults to localhost) */ host?: string /** Simulate network delay in milliseconds */ delay?: number /** Webhook configuration */ webhook?: { /** URL to send webhook events to */ url: string /** Secret token for webhook endpoint validation (used for GET /webhook verification) */ secret: string /** Optional timeout in milliseconds for webhook requests (defaults to 5000) */ timeout?: number } /** Media persistence configuration */ persistence?: { /** Directory to import media metadata from */ importPath?: string /** Directory to export media metadata to (defaults to importPath if not specified) */ exportOnExit?: string /** Whether export was explicitly requested */ shouldExport: boolean } /** Logging configuration */ log?: { /** Controls the verbosity level of logging output (defaults to 'quiet') */ level?: 'quiet' | 'normal' | 'verbose' } } try { await emulator.start() } catch (error) { console.error('Failed to start emulator:', error.message) } ``` -------------------------------- ### WhatsApp Cloud API Webhook Payload Example (JSON) Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/emulator/README.md Illustrates the structure of a typical webhook payload sent by the WhatsApp Cloud API emulator for message status updates. This JSON object details message events, including recipient, status, and conversation information. ```json { "object": "whatsapp_business_account", "entry": [ { "id": "15550123456", "changes": [ { "value": { "messaging_product": "whatsapp", "metadata": { "display_phone_number": "15550123456", "phone_number_id": "15550123456" }, "statuses": [ { "id": "message_id", "recipient_id": "recipient_phone_number", "status": "sent", "timestamp": "1234567890", "conversation": { "id": "conversation_id", "origin": { "type": "utility" } } } ] }, "field": "messages" } ] } ] } ``` -------------------------------- ### Send Text Message with WhatsApp Cloud API Client Source: https://context7.com/ericvera/whatsapp-cloudapi/llms.txt Demonstrates how to send plain text messages and messages with link previews using the `@whatsapp-cloudapi/client` library. It includes examples for basic message sending, enabling link previews, and handling API errors with a provided access token, sender ID, recipient ID, and message text. ```typescript import { sendTextMessage } from '@whatsapp-cloudapi/client' // Send a simple text message const response = await sendTextMessage({ accessToken: 'EAABsbCS1iHgBO7V9ZA8pqgZBwXcZCk...', from: '1234567890', to: '+16505551234', text: 'Hello from WhatsApp Cloud API!', }) console.log('Message ID:', response.messages[0].id) // Output: wamid.HBgLMTY1MDU1NTEyMzQVAgARGBI5QT... // Send message with link preview enabled const responseWithPreview = await sendTextMessage({ accessToken: 'EAABsbCS1iHgBO7V9ZA8pqgZBwXcZCk...', from: '1234567890', to: '+16505551234', text: 'Check out this link: https://example.com', previewUrl: true, bizOpaqueCallbackData: 'tracking-id-12345', }) // Error handling try { await sendTextMessage({ accessToken: 'invalid-token', from: '1234567890', to: '+16505551234', text: 'Test message', }) } catch (error) { console.error('Failed to send:', error.message) // Output: API request failed: Invalid OAuth access token } ``` -------------------------------- ### Send WhatsApp Interactive List Message Source: https://context7.com/ericvera/whatsapp-cloudapi/llms.txt Demonstrates how to send a list message with multiple sections using the `@whatsapp-cloudapi/client` library. It includes an example of handling user selections from the list in a webhook. Requires `accessToken`, `from`, `to`, `headerText`, `bodyText`, `buttonText`, and `sections` for sending. The webhook handler uses `WebhookInteractiveMessage` from `@whatsapp-cloudapi/types/webhook` to parse the reply. ```typescript import { sendListMessage } from '@whatsapp-cloudapi/client'; // Send list with multiple sections const response = await sendListMessage({ accessToken: 'EAABsbCS1iHgBO7V9ZA8pqgZBwXcZCk...', from: '1234567890', to: '+16505551234', headerText: 'Product Catalog', bodyText: 'Browse our products by category. Tap to view options.', buttonText: 'View Products', sections: [ { title: 'Electronics', rows: [ { id: 'phones', title: 'Smartphones', description: 'Latest models from top brands', }, { id: 'laptops', title: 'Laptops', description: 'High-performance computing', }, ], }, { title: 'Accessories', rows: [ { id: 'cases', title: 'Cases & Covers' }, { id: 'chargers', title: 'Chargers' }, ], }, ], footerText: 'Free shipping on orders over $50', }); // Handle list selection in webhook import type { WebhookInteractiveMessage } from '@whatsapp-cloudapi/types/webhook'; function handleListReply(message: WebhookInteractiveMessage) { if (message.interactive.type === 'list_reply') { const listReply = message.interactive.list_reply; const selectedId = listReply.id; const selectedTitle = listReply.title; const selectedDescription = listReply.description; console.log(`User selected: ${selectedTitle} (${selectedId})`); if (selectedId === 'phones') { // Show smartphone catalog } else if (selectedId === 'laptops') { // Show laptop catalog } } } ``` -------------------------------- ### Send Interactive Reply Buttons with WhatsApp Cloud API Source: https://context7.com/ericvera/whatsapp-cloudapi/llms.txt Illustrates sending interactive messages with reply buttons using the `@whatsapp-cloudapi/client` library. It includes an example of handling button clicks within a webhook. The function requires an access token, sender ID, recipient ID, header text, body text, and a list of buttons with unique IDs and titles. Error handling for duplicate button IDs is also demonstrated. ```typescript import { sendButtonsMessage } from '@whatsapp-cloudapi/client' import type { WebhookInteractiveMessage } from '@whatsapp-cloudapi/types/webhook' // Send message with three reply buttons const response = await sendButtonsMessage({ accessToken: 'EAABsbCS1iHgBO7V9ZA8pqgZBwXcZCk...', from: '1234567890', to: '+16505551234', headerText: 'Delivery Options', bodyText: 'When would you like your order delivered?', buttons: [ { id: 'morning', title: 'Morning' }, { id: 'afternoon', title: 'Afternoon' }, { id: 'evening', title: 'Evening' }, ], footerText: 'Select your preferred time', }) // Handle button click in webhook function handleWebhook(message: WebhookInteractiveMessage) { if (message.interactive.type === 'button_reply') { const buttonId = message.interactive.button_reply.id const buttonTitle = message.interactive.button_reply.title console.log(`User clicked: ${buttonTitle} (${buttonId})`) if (buttonId === 'morning') { // Schedule morning delivery } else if (buttonId === 'afternoon') { // Schedule afternoon delivery } } } // Error handling for duplicate button IDs try { await sendButtonsMessage({ accessToken: 'EAABsbCS1iHgBO7V9ZA8pqgZBwXcZCk...', from: '1234567890', to: '+16505551234', bodyText: 'Choose an option:', buttons: [ { id: 'option1', title: 'Option 1' }, { id: 'option1', title: 'Option 2' }, // Duplicate ID ], }) } catch (error) { console.error('Validation error:', error.message) // Output: Duplicate button ID found: option1 } ``` -------------------------------- ### Emulator Media Persistence (TypeScript) Source: https://context7.com/ericvera/whatsapp-cloudapi/llms.txt Illustrates how to enable media persistence in the WhatsApp emulator using the `@whatsapp-cloudapi/emulator` package. It covers importing existing media on startup, exporting on shutdown, and persisting uploaded media across emulator restarts. Includes the expected format for the media manifest file. ```typescript import { WhatsAppEmulator } from '@whatsapp-cloudapi/emulator' // Import existing media on startup, export on shutdown const emulator = new WhatsAppEmulator({ businessPhoneNumberId: '15550123456', persistence: { importPath: './emulator-data', exportOnExit: './backup-data', shouldExport: true, }, }) await emulator.start() // Upload media - will be persisted on shutdown import { uploadMedia } from '@whatsapp-cloudapi/client' const blob = new Blob([imageData], { type: 'image/jpeg' }) const result = await uploadMedia({ accessToken: 'fake-token', from: '15550123456', file: blob, baseUrl: 'http://localhost:4004', }) console.log('Media ID:', result.id) // On shutdown, creates: ./backup-data/media-manifest.json await emulator.stop() // Media manifest format: // { // "version": "1.0", // "exportedAt": "2024-01-15T10:30:00.000Z", // "media": [ // { // "id": "abc123", // "filename": "image.jpg", // "mimeType": "image/jpeg", // "size": 2048576, // "uploadedAt": "2024-01-15T10:15:00.000Z", // "expiresAt": "2024-02-14T10:15:00.000Z" // } // ] // } // Next restart - media persists const nextEmulator = new WhatsAppEmulator({ businessPhoneNumberId: '15550123456', persistence: { importPath: './backup-data', shouldExport: false, }, }) await nextEmulator.start() // Previously uploaded media still accessible ``` -------------------------------- ### Configure Media Persistence for WhatsApp Emulator Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/emulator/README.md TypeScript configuration snippet for setting up media persistence in the WhatsApp Emulator. This allows media metadata to be saved and loaded across emulator restarts. ```typescript const emulator = new WhatsAppEmulator({ businessPhoneNumberId: '15550123456', persistence: { // Import media metadata on startup importPath: './test-data', // Export media metadata on shutdown exportOnExit: './backup-data', // Must be true to enable export shouldExport: true, }, }) ``` -------------------------------- ### Send Interactive CTA URL Message with Text Header (TypeScript) Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/types/README.md Provides a TypeScript example of constructing a `CloudAPISendInteractiveCTAURLRequest` for a message with a text header. This message includes a 'Shop Now' button linking to a promotional URL. ```typescript import { CloudAPISendInteractiveCTAURLRequest } from '@whatsapp-cloudapi/types/cloudapi' // CTA with text header const ctaWithText: CloudAPISendInteractiveCTAURLRequest = { messaging_product: 'whatsapp', recipient_type: 'individual', to: '+1234567890', type: 'interactive', interactive: { type: 'cta_url', header: { type: 'text', text: 'Special Offer!' }, body: { text: 'Check out our latest deals and save up to 50% on selected items.' }, action: { name: 'cta_url', parameters: { display_text: 'Shop Now', url: 'https://shop.example.com/deals' } } } } ``` -------------------------------- ### Use WhatsApp Client with Emulator (TypeScript) Source: https://context7.com/ericvera/whatsapp-cloudapi/llms.txt Illustrates how to configure the '@whatsapp-cloudapi/client' to interact with the local `WhatsAppEmulator`. Shows sending text and uploading media to the emulator by specifying its `baseUrl`. ```typescript import { sendTextMessage } from '@whatsapp-cloudapi/client' import { WhatsAppEmulator } from '@whatsapp-cloudapi/emulator' // Start emulator const emulator = new WhatsAppEmulator({ businessPhoneNumberId: '1234567890', port: 4004, webhook: { url: 'http://localhost:8080/webhook', secret: 'test-secret', }, }) await emulator.start() // Send message to emulator instead of production API const response = await sendTextMessage({ accessToken: 'fake-token', // Any string works with emulator from: '1234567890', to: '+16505551234', text: 'Hello from emulator!', baseUrl: 'http://localhost:4004', // Point to emulator }) console.log('Emulator response:', response.messages[0].id) // Upload media to emulator import { uploadMedia } from '@whatsapp-cloudapi/client' const blob = new Blob([imageData], { type: 'image/jpeg' }) const mediaResponse = await uploadMedia({ accessToken: 'fake-token', from: '1234567890', file: blob, baseUrl: 'http://localhost:4004', }) console.log('Media ID:', mediaResponse.id) // Clean up await emulator.stop() ``` -------------------------------- ### Send Interactive CTA URL Message with Image Header (TypeScript) Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/types/README.md Provides a TypeScript example of constructing a `CloudAPISendInteractiveCTAURLRequest` for a message with an image header. This message includes a 'View Catalog' button linking to a product catalog URL. ```typescript import { CloudAPISendInteractiveCTAURLRequest } from '@whatsapp-cloudapi/types/cloudapi' // CTA with image header const ctaWithImage: CloudAPISendInteractiveCTAURLRequest = { messaging_product: 'whatsapp', recipient_type: 'individual', to: '+1234567890', type: 'interactive', interactive: { type: 'cta_url', header: { type: 'image', image: { id: 'MEDIA_ID_FROM_UPLOAD' } }, body: { text: 'Browse our complete product catalog with detailed specifications.' }, action: { name: 'cta_url', parameters: { display_text: 'View Catalog', url: 'https://catalog.example.com' } } } } ``` -------------------------------- ### POST /messages (Send Flow Message) Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/client/README.md Sends a WhatsApp Flow message to guide users through interactive forms and experiences. This endpoint supports various header types and actions like navigation and data exchange. ```APIDOC ## POST /messages (Send Flow Message) ### Description Sends a WhatsApp Flow message to guide users through interactive forms and experiences. This endpoint supports various header types and actions like navigation and data exchange. ### Method POST ### Endpoint https://graph.facebook.com/v18.0/YOUR_PHONE_NUMBER_ID/messages ### Parameters #### Query Parameters - **access_token** (string) - Required - Your WhatsApp Cloud API access token #### Request Body - **messaging_product** (string) - Required - Must be "whatsapp" - **to** (string) - Required - Recipient's phone number with country code (e.g., "+16505551234") - **type** (string) - Required - Must be "template" - **template** (object) - Required - Template object containing flow message details - **name** (string) - Required - The name of the template (e.g., "flow_template") - **language** (object) - Required - Language object for the template - **code** (string) - Required - Language code (e.g., "en") - **components** (array) - Required - Array of template components - **type** (string) - Required - Type of component (e.g., "HEADER", "BODY", "FOOTER") - **format** (string) - Required (for HEADER type) - Format of the header media (e.g., "TEXT", "IMAGE", "VIDEO", "DOCUMENT") - **text** (string) - Required (for BODY type) - Main message text. Maximum 1024 characters - **text** (string) - Required (for TEXT header type) - Header text. Maximum 60 characters. - **example** (object) - Required (for HEADER media types) - Example of header media - **header_handle** (string) - Required (for IMAGE, VIDEO, DOCUMENT header types) - Media ID or URL of the header asset - **content** (string) - Required (for DOCUMENT header type) - Filename for the document - **type** (string) - Required (for BUTTON type) - Type of button (e.g., "QUICK_REPLY", "URL", "CALL_TO_ACTION") - **text** (string) - Required (for BUTTON type) - Text displayed on the button - **url** (string) - Required (for URL button type) - URL to open when the button is clicked - **flow** (object) - Required (for CALL_TO_ACTION button type) - Flow details for the button - **flow_message_token** (string) - Required - Session token for the flow - **flow_id** (string) - Required - Unique ID of the flow - **flow_cta** (string) - Required - Call-to-action text on the button - **flow_action** (string) - Required - Type of flow action: 'navigate' or 'data_exchange' - **screen** (string) - Optional - Screen to navigate to (required for 'navigate' action) - **data** (object) - Optional - Additional data to pass to the flow - **text** (string) - Optional (for FOOTER type) - Footer text. Maximum 60 characters ### Request Example ```json { "messaging_product": "whatsapp", "to": "+16505551234", "type": "template", "template": { "name": "loan_application_flow", "language": {"code": "en"}, "components": [ { "type": "HEADER", "format": "TEXT", "text": "Loan Application" }, { "type": "BODY", "text": "Complete your loan application form to get started." }, { "type": "FOOTER", "text": "Secure and fast process" }, { "type": "BUTTON", "text": "Start Application", "type": "CALL_TO_ACTION", "flow": { "flow_message_token": "FLOW_SESSION_TOKEN_123", "flow_id": "FLOW_ID_456", "flow_cta": "Start Application", "flow_action": "navigate", "screen": "welcome_screen" } } ] } } ``` ### Response #### Success Response (200) - **messages** (array) - Array of message objects, each containing an `id` for the sent message. - **id** (string) - The unique ID of the sent message. #### Response Example ```json { "messages": [ { "id": "wamid.HBgNNTQ2MTIzNDU2Nzg5MAZDOTQ2MjM0NTY3ODkwMjM0NQ==" } ] } ``` ### Error Handling Common errors include invalid access tokens, incorrect phone number formats, missing required parameters, exceeding character limits for text fields, or attempting to use multiple header types simultaneously. ```json { "error": { "message": "Invalid parameter", "type": "OAuthException", "code": 100, "error_subcode": 1402030, "fbtrace_id": "A1B2C3D4E5F6G7H8" } } ``` ### Flow Actions - **navigate**: Directs users to a specific screen within the flow. Requires the `screen` parameter. - **data_exchange**: Initiates data collection or exchange. Can include optional `data` parameter with initial values. ``` -------------------------------- ### WhatsAppEmulator Class and Methods Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/emulator/README.md Information about the WhatsAppEmulator class, its constructor, and the start/stop methods for managing the emulator server. ```APIDOC ## WhatsAppEmulator Creates a new instance of the WhatsApp Cloud API emulator. ### Description Initializes the WhatsApp emulator with specified options. ### Constructor `constructor(options: EmulatorOptions)` ### Methods - `start()`: Starts the emulator server. - `stop()`: Stops the emulator server. ### Error Handling The emulator throws errors for common issues like port conflicts, invalid configurations, or startup failures. ```typescript try { await emulator.start() } catch (error) { console.error('Failed to start emulator:', error.message) } ``` ``` -------------------------------- ### EmulatorOptions Interface Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/emulator/README.md Details the configuration options available for the WhatsAppEmulator, including business phone number ID, port, host, delay, webhook, persistence, and logging. ```APIDOC ## EmulatorOptions Defines the configuration object for the `WhatsAppEmulator`. ### Properties - **`businessPhoneNumberId`** (string) - Required - The business phone number ID to emulate. - **`port`** (number) - Optional - The port to run the emulator server on (defaults to 4004). - **`host`** (string) - Optional - The host to bind the server to (defaults to `localhost`). - **`delay`** (number) - Optional - Simulates network delay in milliseconds. - **`webhook`** (object) - Optional - Webhook configuration. - **`url`** (string) - Required - URL to send webhook events to. - **`secret`** (string) - Required - Secret token for webhook endpoint validation. - **`timeout`** (number) - Optional - Timeout in milliseconds for webhook requests (defaults to 5000). - **`persistence`** (object) - Optional - Media persistence configuration. - **`importPath`** (string) - Directory to import media metadata from. - **`exportOnExit`** (string) - Optional - Directory to export media metadata to (defaults to `importPath`). - **`shouldExport`** (boolean) - Indicates if export was explicitly requested. - **`log`** (object) - Optional - Logging configuration. - **`level`** (string) - Optional - Controls logging verbosity (`quiet`, `normal`, `verbose`, defaults to `quiet`). ``` -------------------------------- ### Send List Message (TypeScript) Source: https://github.com/ericvera/whatsapp-cloudapi/blob/main/packages/client/README.md Provides a TypeScript function signature and an example for sending an interactive list message. This feature allows users to select from structured menus organized into sections, with detailed parameter explanations for customization. ```typescript import { sendListMessage } from '@whatsapp-cloudapi/client' // Send a list with multiple sections const response = await sendListMessage({ accessToken: 'YOUR_ACCESS_TOKEN', from: 'YOUR_PHONE_NUMBER_ID', to: '+16505551234', headerText: 'Product Catalog', bodyText: 'Browse our products by category. Tap to view options.', buttonText: 'View Products', sections: [ { title: 'Electronics', rows: [ { id: 'phones', title: 'Smartphones', description: 'Latest models from top brands', }, { id: 'laptops', title: 'Laptops', description: 'High-performance computing', }, ], }, { title: 'Accessories', rows: [ { id: 'cases', title: 'Cases & Covers' }, { id: 'chargers', title: 'Chargers' }, ], }, ], footerText: 'Free shipping on orders over $50', }) console.log('List message sent:', response.messages[0].id) ```