### Install WhatsApp Business Platform SDK Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/README.md Install the SDK using npm, pnpm, yarn, or bun. For Deno, use 'deno add'. ```bash # NPM: npm install @great-detail/whatsapp # ^ or use PNPM, Yarn, Bun # Deno: deno add npm:@great-detail/whatsapp ``` -------------------------------- ### Initialize SDK with Minimal Configuration Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/configuration.md Initialize the SDK with only the essential request headers, such as the authorization token. This is the most basic setup. ```typescript import Client from "@great-detail/whatsapp"; const sdk = new Client({ request: { headers: { Authorization: `Bearer ${process.env.WHATSAPP_ACCESS_TOKEN}`, }, }, }); ``` -------------------------------- ### Initialize Client with Custom Timeout Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/configuration.md Configure a custom timeout for HTTP requests. This example sets a 30-second timeout. ```typescript const sdk = new Client({ request: { headers: { Authorization: "Bearer TOKEN" }, timeout: 30_000, // 30-second timeout }, }); ``` -------------------------------- ### Example Express.js Webhook Endpoint Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/api-reference/SubscribedApps.md This snippet shows how to create an Express.js server to handle WhatsApp webhook registration (GET requests) and event notifications (POST requests). It includes logic for verifying the registration token and processing incoming events, including signature verification. ```typescript import express from "express"; const app = express(); app.use(express.raw({ type: "application/json" })); // Webhook registration (GET) app.get("/webhook", async (req, res) => { try { const reg = await sdk.webhook.register({ method: req.method, query: req.query, body: undefined, headers: req.headers, }); if (reg.verifyToken !== process.env.WEBHOOK_VERIFY_TOKEN) { return res.status(403).send("Invalid token"); } res.send(reg.accept()); } catch (error) { res.status(400).send("Invalid registration request"); } }); // Webhook events (POST) app.post("/webhook", async (req, res) => { try { const event = sdk.webhook.eventNotification({ method: req.method, query: req.query, body: req.body.toString(), headers: req.headers, }); // Verify signature await event.verifySignature(process.env.WHATSAPP_APP_SECRET); // Process the event console.log("Webhook event received:", event.eventNotification); // Return 200 OK res.status(200).send(event.accept()); } catch (error) { console.error("Webhook error:", error); res.status(400).send("Webhook processing failed"); } }); app.listen(3000, () => console.log("Webhook listening on port 3000")); ``` -------------------------------- ### Example: Handling API Errors Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/errors.md Provides a TypeScript code example demonstrating how to catch and handle API errors, distinguishing between API-specific errors and general request failures. ```APIDOC ## Example: Handling API Errors ```typescript try { const message = await sdk.message.createMessage({ phoneNumberID: "invalid_id", to: "1234567890", type: "text", text: { body: "Hello" }, }); } catch (error) { if (error.response) { // API error response const apiError = error.response.body as WhatsappError; console.error(`Error ${apiError.code}: ${apiError.message}`); console.error(`Details: ${apiError.error_data?.details}`); console.error(`Trace ID: ${apiError.fbtrace_id}`); } else { // Network or client error console.error("Request failed:", error.message); } } ``` ``` -------------------------------- ### Setup Webhook Subscription Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/api-reference/SubscribedApps.md Creates a webhook subscription for receiving events and then verifies its creation by listing existing subscriptions. Ensure environment variables for WHATSAPP_BUSINESS_ACCOUNT_ID, API_HOST, and WEBHOOK_VERIFY_TOKEN are set. ```typescript async function setupWebhookSubscription() { const wabID = process.env.WHATSAPP_BUSINESS_ACCOUNT_ID; const webhookURL = `https://${process.env.API_HOST}/webhook`; const verifyToken = process.env.WEBHOOK_VERIFY_TOKEN; try { // 1. Create subscription const result = await sdk.subscribedApps.createSubscription({ businessAccountID: wabID, override_callback_uri: webhookURL, verify_token: verifyToken, }); if (!result.success) { throw new Error("Failed to create subscription"); } console.log("✓ Subscription created"); // 2. Verify subscription was created const subscriptions = await sdk.subscribedApps.listSubscriptions({ businessAccountID: wabID, }); console.log(`✓ Found ${subscriptions.data.length} subscription(s)`); subscriptions.data.forEach(sub => { const { name, link } = sub.whatsapp_business_api_data; console.log(` - ${name} (${link})`); }); return true; } catch (error) { console.error("✗ Subscription setup failed:", error); return false; } } // Run setup await setupWebhookSubscription(); ``` -------------------------------- ### SDK Initialization with Environment Variables Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/configuration.md Demonstrates initializing the WhatsApp SDK using environment variables for configuration, including authentication and API version. This promotes secure and flexible setup. ```typescript const sdk = new Client({ graphVersion: process.env.GRAPH_API_VERSION || "v23.0", request: { headers: { Authorization: `Bearer ${process.env.WHATSAPP_ACCESS_TOKEN}`, }, }, }); // Use in operations const message = await sdk.message.createMessage({ phoneNumberID: process.env.WHATSAPP_PHONE_NUMBER_ID!, to: "1234567890", type: "text", text: { body: "Hello" }, }); ``` -------------------------------- ### Initialize Client with Request/Response Hooks Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/configuration.md Implement custom logic for request and response lifecycle events. This example logs the request URL before sending and the response status after receiving. ```typescript const sdk = new Client({ request: { headers: { Authorization: "Bearer TOKEN" }, hooks: { beforeRequest: [ (request) => { console.log("Sending request:", request.url); }, ], afterResponse: [ (response) => { console.log("Response status:", response.status); }, ], }, }, }); ``` -------------------------------- ### Client Constructor Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/api-reference/Client.md Initializes a new instance of the Client class. This is the primary way to start using the SDK, allowing for customization of API endpoints, versions, and request behaviors. ```APIDOC ## Client Constructor ### Description Initializes a new instance of the `Client` class. This is the primary way to start using the SDK, allowing for customization of API endpoints, versions, and request behaviors. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options.baseUrl** (string) - Optional - Base URL for the Graph API. Can override the default Meta Graph API endpoint. Defaults to `https://graph.facebook.com`. - **options.prefixUrl** (string) - Optional - Deprecated. Use `baseUrl` instead. - **options.graphVersion** (string) - Optional - Graph API version (e.g., `v20.0`, `v23.0`). Defaults to `v23.0`. - **options.request** (KyOptions) - Optional - Request options passed to the underlying `ky` HTTP client (e.g., `headers`, `retry`, `timeout`). ### Return Value An instance of the `Client` class. ### Example ```typescript import Client from "@great-detail/whatsapp"; // Create a client with authorization const sdk = new Client({ request: { headers: { Authorization: "Bearer YOUR_ACCESS_TOKEN", }, }, }); // Use the client to send a message const message = await sdk.message.createMessage({ phoneNumberID: "123456789", to: "1234567890", type: "text", text: { body: "Hello, World!" }, }); ``` ### Advanced Configuration Example ```typescript // Use a custom Graph API version const sdk = new Client({ graphVersion: "v20.0", request: { headers: { Authorization: "Bearer YOUR_ACCESS_TOKEN", }, retry: 5, // Retry up to 5 times timeout: 30_000, // 30-second timeout }, }); // Use a custom base URL const sdk = new Client({ baseUrl: "https://custom-api.example.com", graphVersion: "v23.0", request: { headers: { Authorization: "Bearer YOUR_ACCESS_TOKEN", }, }, }); ``` ``` -------------------------------- ### Complete Business Profile Setup Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/api-reference/BusinessProfile.md Use this snippet to retrieve the current business profile and then update it with comprehensive information including about text, address, description, email, vertical, and websites. It also includes verification of the update. ```typescript const current = await sdk.businessProfile.getBusinessProfile({ phoneNumberID: "123456789", }); console.log("Current profile:", current.data[0]); const result = await sdk.businessProfile.updateBusinessProfile({ phoneNumberID: "123456789", about: "Quality products at great prices. Order now!", address: "789 Commerce Street, Boston, MA 02101", description: "Your one-stop shop for electronics, home goods, and more. Founded in 2020.", email: "support@myshop.com", vertical: "RETAIL", websites: ["https://myshop.com", "https://facebook.com/myshop"], }); if (result.success) { console.log("Profile fully updated"); const updated = await sdk.businessProfile.getBusinessProfile({ phoneNumberID: "123456789", }); console.log("Updated profile:", updated.data[0]); } ``` -------------------------------- ### Webhook API - register() Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Handles webhook registration, typically a GET request to verify the webhook URL. ```APIDOC ## Webhook API - register() ### Description Handle webhook registration requests, usually a GET request for verification. ### Method register ### Parameters - **request** (object) - Required - The incoming request object (e.g., from Express.js). - **response** (object) - Required - The outgoing response object (e.g., from Express.js). - **verifyToken** (string) - Required - The verify token configured in your WhatsApp Business Platform settings. ### Response #### Success Response (200) - The response will typically involve sending back the `verifyToken` in the response body or query parameters as per WhatsApp's verification process. ### Request Example (Express.js) ```javascript app.get('/webhook', (req, res) => { whatsapp.webhook.register(req, res, 'YOUR_VERIFY_TOKEN'); }); ``` ``` -------------------------------- ### register() Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/api-reference/Webhook.md Handles a webhook registration request (GET request from WhatsApp) and verifies the token. It echoes back a challenge to accept the registration or rejects it if verification fails. ```APIDOC ## GET /webhook ### Description Handles a webhook registration request (GET request from WhatsApp) and verifies the token. It echoes back a challenge to accept the registration or rejects it if verification fails. ### Method GET ### Endpoint /webhook ### Parameters #### Query Parameters - **hub.mode** (string) - Required - Mode for webhook subscription. - **hub.challenge** (string) - Required - Challenge string to echo back. - **hub.verify_token** (string) - Required - Token for verifying the webhook. #### Request Body - **body** (string | undefined) - Optional - Request body (typically empty for GET). ### Response #### Success Response (200) - **verifyToken** (string) - The verify token from the request. - **challenge** (string) - The challenge string to echo back. - **accept** (function) - Returns the challenge to accept registration. - **reject** (function) - Returns empty to reject registration. ### Throws - `IncorrectMethodWebhookError`: If method is not GET - `InvalidHubModeWebhookError`: If hub.mode is not "subscribe" - `InvalidHubChallengeWebhookError`: If hub.challenge is missing - `InvalidHubVerifyTokenWebhookError`: If hub.verify_token is missing ### Request Example ```typescript // Example using Express.js app.get("/webhook", async (req, res) => { try { const reg = await sdk.webhook.register({ method: req.method, query: req.query, body: undefined, headers: req.headers, }); if (reg.verifyToken !== process.env.WEBHOOK_VERIFY_TOKEN) { return res.end(reg.reject()); } return res.end(reg.accept()); } catch (error) { console.error("Webhook registration error:", error); res.status(400).end(); } }); ``` ``` -------------------------------- ### Initialize Client with Custom Retry Policy Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/configuration.md Set a custom number of retries for HTTP requests. This example configures the client to retry up to 5 times. ```typescript const sdk = new Client({ request: { headers: { Authorization: "Bearer TOKEN" }, retry: 5, // Retry up to 5 times }, }); ``` -------------------------------- ### Send Typing Indicator Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/api-reference/Message.md This example shows how to send a typing indicator along with marking a message as read. This can enhance user experience by indicating that a response is being prepared. ```typescript const status = await sdk.message.createStatus({ phoneNumberID: "123456789", message_id: "wamid.xxx", status: "read", typing_indicator: { type: "text" }, }); ``` -------------------------------- ### Listen for Webhook Registration Requests with Fastify Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/README.md Handles GET requests for webhook registration using Fastify. It verifies a token and sends an accept or reject response. ```typescript // Registration requests: fastify.route({ method: "GET", url: "/path/to/webhook", handler: (request, reply) => { * const reg = await sdk.webhook.register({ method: request.method, query: request.query, body: undefined, headers: request.headers, }); // DIY: Check the reg.verifyToken value if (reg.verifyToken !== "abcd") { return reply.send(reg.reject()); } return reply.send(reg.accept()); } }); ``` -------------------------------- ### SDK Documentation Structure Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt This snippet outlines the primary documentation files and their purposes for the whatsapp-js-sdk. Users should start with README.md and navigate to specific module files for API references. ```APIDOC ## SDK Documentation Navigation ### Overview - Start with `README.md` for a general overview and navigation guide. ### API Reference - For specific API operations, refer to `api-reference/[Module].md` files. - Each module file is self-contained, documenting all types, options, and including multiple examples per method. ### Types and Enums - Detailed type definitions, field descriptions, and usage locations can be found in `types.md`. ### Configuration - Information on client options, per-request options, environment variables, and setup patterns is available in `configuration.md`. ### Error Handling - A comprehensive reference for error types, codes, meanings, handling strategies, and examples is provided in `errors.md`. ### Real-World Examples - Production-ready examples for sending messages, template management, webhook integration, health monitoring, and error recovery are highlighted. ``` -------------------------------- ### Complete Webhook Registration and Event Handling Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/errors.md A full example demonstrating how to set up Express.js endpoints for webhook registration and event notifications, including comprehensive error handling for various webhook-related errors. ```typescript import express from "express"; import Client from "@great-detail/whatsapp"; const sdk = new Client({ request: { headers: { Authorization: "Bearer TOKEN" } } }); const app = express(); app.use(express.raw({ type: "application/json" })); // Registration endpoint app.get("/webhook", async (req, res) => { try { const reg = await sdk.webhook.register({ method: req.method, query: req.query, body: undefined, headers: req.headers, }); // Verify token if (reg.verifyToken !== process.env.WEBHOOK_VERIFY_TOKEN) { res.status(403).send("Forbidden"); return; } res.send(reg.accept()); } catch (error) { if (error instanceof sdk.webhook.errors.IncorrectMethodWebhookError) { res.status(400).send("Use GET method"); } else if (error instanceof sdk.webhook.errors.InvalidHubModeWebhookError) { res.status(400).send("hub.mode must be 'subscribe'"); } else if (error instanceof sdk.webhook.errors.InvalidHubChallengeWebhookError) { res.status(400).send("hub.challenge is required"); } else if (error instanceof sdk.webhook.errors.InvalidHubVerifyTokenWebhookError) { res.status(400).send("hub.verify_token is required"); } else { res.status(500).send("Internal error"); } } }); // Event notification endpoint app.post("/webhook", async (req, res) => { try { const event = sdk.webhook.eventNotification({ method: req.method, query: req.query, body: req.body.toString(), headers: req.headers, }); // Verify signature try { await event.verifySignature(process.env.WHATSAPP_APP_SECRET); } catch (error) { if (error instanceof sdk.webhook.errors.InvalidHubSignatureWebhookError) { res.status(401).send("Unauthorized"); return; } throw error; } // Process event console.log("Event:", event.eventNotification); res.status(200).send(event.accept()); } catch (error) { if (error instanceof sdk.webhook.errors.MissingBodyWebhookError) { res.status(400).send("Body is required"); } else if (error instanceof sdk.webhook.errors.InvalidHubSignatureWebhookError) { res.status(401).send("Unauthorized"); } else { res.status(500).send("Internal error"); } } }); app.listen(3000); ``` -------------------------------- ### Listen for Webhook Registration Requests with Express Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/README.md Handles GET requests for webhook registration. It verifies a token and sends an accept or reject response. ```typescript // Registration requests: app.get("/path/to/webhook", async (req, res) => { const reg = await sdk.webhook.register({ method: request.method, query: req.query, body: req.body, headers: req.headers, }); // DIY: Check the reg.verifyToken value if (reg.verifyToken !== "abcd") { return res.end(reg.reject()); } return res.end(reg.accept()); }); ``` -------------------------------- ### Register Webhook with Fastify Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/api-reference/Webhook.md Handles GET requests for webhook registration using Fastify. It verifies the token and accepts or rejects the registration challenge. ```typescript fastify.route({ method: "GET", url: "/webhook", handler: async (request, reply) => { try { const reg = await sdk.webhook.register({ method: request.method, query: request.query, body: undefined, headers: request.headers, }); if (reg.verifyToken !== process.env.WEBHOOK_VERIFY_TOKEN) { return reply.send(reg.reject()); } return reply.send(reg.accept()); } catch (error) { console.error("Webhook registration error:", error); reply.code(400).send(); } }, }); ``` -------------------------------- ### Register Webhook with Deno (Oak) Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/api-reference/Webhook.md Handles GET requests for webhook registration using Deno with the Oak framework. It verifies the token and accepts or rejects the registration challenge. ```typescript router.get("/webhook", async (context) => { try { const reg = await sdk.webhook.register({ method: context.request.method, query: Object.fromEntries(context.request.url.searchParams), body: undefined, headers: Object.fromEntries(context.request.headers), }); if (reg.verifyToken !== Deno.env.get("WEBHOOK_VERIFY_TOKEN")) { context.response.body = reg.reject(); return; } context.response.body = reg.accept(); } catch (error) { console.error("Webhook registration error:", error); context.response.status = 400; } }); ``` -------------------------------- ### Get Media File Download URL (After CLI Removal) Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/CHANGELOG.md Demonstrates how to retrieve a media file's download URL using the SDK after the CLI removal. Requires the media ID. ```bash # Before: npx @great-detail/whatsapp media get-url "" ``` ```typescript const result = await sdk.media.upload({ phoneNumberID: "123...809", mediaID: "", }); ``` -------------------------------- ### Check Account Health and Take Action Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/api-reference/WhatsappBusinessAccount.md Example of how to retrieve a WhatsApp Business Account and check its health status. It logs the overall health and investigates specific entity issues with their errors and possible solutions. ```typescript const account = await sdk.whatsappBusinessAccount.get("123456789", { fields: ["health_status", "business_verification_status"], }); // Check overall health if (account.health_status.can_send_message === "AVAILABLE") { console.log("✓ Account is healthy and can send messages"); } else { console.log(`✗ Account health issue: ${account.health_status.can_send_message}`); // Investigate specific entities account.health_status.entities.forEach(entity => { if (entity.can_send_message !== "AVAILABLE") { console.error(`\nIssue with ${entity.entity_type} (${entity.id}):`); if (entity.errors && entity.errors.length > 0) { entity.errors.forEach(err => { console.error(` Error: ${err.error_description}`); if (err.possible_solution) { console.error(` Action: ${err.possible_solution}`); } }); } } }); } // Check verification status switch (account.business_verification_status) { case "verified": console.log("✓ Business is verified"); break; case "pending": case "pending_need_more_info": console.log("⏳ Verification is pending"); break; case "rejected": case "failed": console.log("✗ Verification was rejected - may need resubmission"); break; } ``` -------------------------------- ### Get Complete Account Details Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/api-reference/WhatsappBusinessAccount.md Fetch all available details for a WhatsApp Business Account, including ID, name, review status, verification, timezone, currency, owner information, and health status. This is useful for comprehensive account management and auditing. ```typescript const account = await sdk.whatsappBusinessAccount.get("123456789", { fields: [ "id", "name", "account_review_status", "business_verification_status", "timezone_id", "currency", "country", "owner_business_info", "is_enabled_for_insights", "marketing_messages_lite_api_status", "marketing_messages_onboarding_status", "health_status", ], }); console.log("Account Details:"); console.log(` ID: ${account.id}`); console.log(` Name: ${account.name}`); console.log(` Status: ${account.status}`); console.log(` Verification: ${account.business_verification_status}`); console.log(` Currency: ${account.currency}`); console.log(` Country: ${account.country}`); console.log(` Timezone: ${account.timezone_id}`); console.log(` Insights Enabled: ${account.is_enabled_for_insights}`); console.log(` Marketing Messages: ${account.marketing_messages_lite_api_status}`); console.log(` Owner: ${account.owner_business_info.name}`); ``` -------------------------------- ### IncorrectMethodWebhookError Example Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/errors.md Thrown when the HTTP method used for webhook registration or event notification is incorrect. Ensure GET is used for registration and POST for notifications. ```typescript class IncorrectMethodWebhookError extends WebhookError ``` ```typescript try { const reg = await sdk.webhook.register({ method: "POST", // Should be GET query: {}, body: undefined, headers: {}, }); } catch (error) { if (error instanceof sdk.webhook.errors.IncorrectMethodWebhookError) { console.error("Use GET for registration"); } } ``` -------------------------------- ### Initialize SDK with Full Configuration Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/configuration.md Initialize the SDK with all available configuration options, including base URL, graph version, request settings like retry, timeout, and hooks. ```typescript const sdk = new Client({ baseUrl: "https://graph.facebook.com", graphVersion: "v23.0", request: { headers: { Authorization: `Bearer ${process.env.WHATSAPP_ACCESS_TOKEN}`, "User-Agent": "MyApp/1.0", }, retry: 5, timeout: 30000, throwHttpErrors: true, hooks: { beforeRequest: [ (request) => { console.log(`[${new Date().toISOString()}] ${request.method} ${request.url}`); }, ], afterResponse: [ (response) => { console.log(`[${new Date().toISOString()}] ${response.status}`); }, ], }, }, }); ``` -------------------------------- ### WhatsappBusinessAccount API - get() Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Retrieves details about the WhatsApp Business Account. ```APIDOC ## WhatsappBusinessAccount API - get() ### Description Retrieve details about the WhatsApp Business Account (WABA). ### Method get ### Parameters None ### Response #### Success Response (200) - **id** (string) - The WABA ID. - **name** (string) - The name of the business account. - **verification_status** (string) - The verification status of the account. - **health_status** (string) - The health status of the account. - **marketing_messaging_status** (string) - Status of marketing messages. ### Request Example ```javascript const wabaDetails = await whatsapp.whatsappBusinessAccount.get(); ``` ### Response Example ```json { "id": "100000000000000", "name": "My Awesome Business", "verification_status": "VERIFIED", "health_status": "OK", "marketing_messaging_status": "ENABLED" } ``` ``` -------------------------------- ### Template API - get() Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Retrieves details for a specific message template. ```APIDOC ## Template API - get() ### Description Retrieve details of a specific message template. ### Method get ### Parameters - **templateName** (string) - Required - The name of the template. - **languageCode** (string) - Required - The language code of the template (e.g., 'en_US'). ### Response #### Success Response (200) - **name** (string) - The name of the template. - **language** (string) - The language code. - **category** (string) - The category of the template. - **components** (array) - The components of the template. ### Request Example ```javascript const templateDetails = await whatsapp.template.get('welcome_message', 'en_US'); ``` ### Response Example ```json { "name": "welcome_message", "language": "en_US", "category": "utility", "components": [ { "type": "body", "parameters": [ { "type": "text", "text": "{{1}}" } ] } ] } ``` ``` -------------------------------- ### Client Initialization and Module Access Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/README.md Demonstrates how to initialize the SDK client and access its various modules for interacting with the WhatsApp Business Platform. ```APIDOC ## Client Initialization ### Description Initialize the SDK client with necessary configuration, typically including authentication headers. ### Method ```typescript new Client(options?: ClientOptions) ``` ### Parameters - **options** (ClientOptions) - Optional - Configuration options for the client. - **request** (RequestOptions) - Optional - Options for making HTTP requests. - **headers** (Record) - Optional - Custom headers to be sent with requests. - **Authorization** (string) - Required - Bearer token for authentication. ### Example ```typescript import Client from "@great-detail/whatsapp"; const sdk = new Client({ request: { headers: { Authorization: "Bearer ACCESS_TOKEN" } } }); // Accessing modules: // sdk.message // sdk.media // sdk.template // sdk.webhook // sdk.phoneNumbers // sdk.businessProfile // sdk.whatsappBusinessAccount // sdk.subscribedApps ``` ### Modules Upon successful initialization, the `Client` instance provides access to the following modules: - **message**: For sending various types of messages. - **media**: For managing media files. - **template**: For creating and managing message templates. - **webhook**: For handling incoming webhook events. - **phoneNumbers**: For managing associated phone numbers. - **businessProfile**: For managing business profile information. - **whatsappBusinessAccount**: For retrieving account information and health status. - **subscribedApps**: For managing webhook subscriptions. ``` -------------------------------- ### Define MessageID Type Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/types.md Defines the unique identifier for a WhatsApp message, which typically starts with the 'wamid.' prefix. ```typescript type MessageID = `wamid.${string}` | (string & NonNullable) ``` -------------------------------- ### Download Media Files (After CLI Removal) Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/CHANGELOG.md Shows how to download media files using the SDK after the CLI removal. The downloaded content can be written to a file. ```bash # Before: npx @great-detail/whatsapp media download "" > "" ``` ```typescript import fs from "fs"; const result = await sdk.media.download(""); const file = await result.arrayBuffer(); const file = await result.arrayBuffer(); fs.writeFileSync("", Buffer.from(file)); ``` -------------------------------- ### InvalidHubSignatureWebhookError Examples Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/errors.md Thrown when the signature verification fails or the 'x-hub-signature-256' header is missing. This ensures the integrity of incoming event notifications. ```typescript class InvalidHubSignatureWebhookError extends WebhookError ``` ```typescript try { const event = sdk.webhook.eventNotification({ method: "POST", query: {}, body: JSON.stringify(eventData), headers: { // Missing x-hub-signature-256 }, }); } catch (error) { if (error instanceof sdk.webhook.errors.InvalidHubSignatureWebhookError) { console.error("Signature header is missing or invalid"); } } ``` ```typescript try { const event = sdk.webhook.eventNotification({ method: "POST", query: {}, body: JSON.stringify(eventData), headers: { "x-hub-signature-256": "sha256=incorrect_signature" }, }); // Verify signature with wrong secret await event.verifySignature("wrong_secret"); } catch (error) { if (error instanceof sdk.webhook.errors.InvalidHubSignatureWebhookError) { console.error("Signature verification failed - check app secret"); } } ``` -------------------------------- ### Basic Syntax for Per-Request Configuration Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/configuration.md Illustrates the general structure for passing request-specific options to an SDK method. This is useful for fine-tuning behavior on a per-call basis. ```typescript const result = await sdk.message.createMessage({ // ... message options request: { // ... request-specific options }, }); ``` -------------------------------- ### InvalidHubVerifyTokenWebhookError Example Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/errors.md Thrown when the 'hub.verify_token' query parameter is missing during webhook registration. This token is used to authenticate the registration request. ```typescript class InvalidHubVerifyTokenWebhookError extends WebhookError ``` ```typescript try { const reg = await sdk.webhook.register({ method: "GET", query: { "hub.mode": "subscribe", "hub.challenge": "abc123" // Missing hub.verify_token }, headers: {}, }); } catch (error) { if (error instanceof sdk.webhook.errors.InvalidHubVerifyTokenWebhookError) { console.error("Verify token is required"); } } ``` -------------------------------- ### Basic Client Initialization Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/README.md Initializes the WhatsApp client with essential authentication headers. Ensure the WHATSAPP_ACCESS_TOKEN environment variable is set. ```typescript import Client from "@great-detail/whatsapp"; const sdk = new Client({ request: { headers: { Authorization: `Bearer ${process.env.WHATSAPP_ACCESS_TOKEN}` } } }); ``` -------------------------------- ### Initialize Client and Send Message Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/api-reference/Client.md Create a new Client instance with authorization headers and use it to send a text message. Requires importing the Client class. ```typescript import Client from "@great-detail/whatsapp"; // Create a client with authorization const sdk = new Client({ request: { headers: { Authorization: "Bearer YOUR_ACCESS_TOKEN", }, }, }); // Use the client to send a message const message = await sdk.message.createMessage({ phoneNumberID: "123456789", to: "1234567890", type: "text", text: { body: "Hello, World!" }, }); ``` -------------------------------- ### InvalidHubChallengeWebhookError Example Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/errors.md Thrown when the 'hub.challenge' query parameter is missing during webhook registration. This parameter is required to verify the webhook endpoint. ```typescript class InvalidHubChallengeWebhookError extends WebhookError ``` ```typescript try { const reg = await sdk.webhook.register({ method: "GET", query: { "hub.mode": "subscribe" }, // Missing hub.challenge headers: {}, }); } catch (error) { if (error instanceof sdk.webhook.errors.InvalidHubChallengeWebhookError) { console.error("Challenge is required for registration"); } } ``` -------------------------------- ### Initialize SDK with Environment-Specific Configuration Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/configuration.md Configure the SDK dynamically based on the environment (e.g., development vs. production). This allows for different settings like retries, timeouts, and logging hooks. ```typescript function createSDK() { const isDevelopment = process.env.NODE_ENV === "development"; return new Client({ graphVersion: process.env.GRAPH_API_VERSION || "v23.0", request: { headers: { Authorization: `Bearer ${process.env.WHATSAPP_ACCESS_TOKEN}`, }, retry: isDevelopment ? 1 : 3, timeout: isDevelopment ? 60000 : 30000, hooks: isDevelopment ? { beforeRequest: [ (request) => { console.log(`📤 ${request.method} ${request.url}`); }, ], afterResponse: [ (response) => { console.log(`📥 ${response.status} ${response.statusText}`); }, ], } : undefined, }, }); } const sdk = createSDK(); ``` -------------------------------- ### InvalidHubModeWebhookError Example Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/errors.md Thrown when the 'hub.mode' query parameter is missing or not set to 'subscribe' during webhook registration. This parameter is mandatory for subscription. ```typescript class InvalidHubModeWebhookError extends WebhookError ``` ```typescript try { const reg = await sdk.webhook.register({ method: "GET", query: { "hub.challenge": "abc123" }, // Missing hub.mode headers: {}, }); } catch (error) { if (error instanceof sdk.webhook.errors.InvalidHubModeWebhookError) { console.error("Must include hub.mode=subscribe"); } } ``` -------------------------------- ### Initialize WhatsApp SDK Client Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/README.md Demonstrates how to initialize the WhatsApp SDK client with an access token. This client provides access to various API modules for interacting with the WhatsApp Business Platform. ```typescript import Client from "@great-detail/whatsapp"; const sdk = new Client({ request: { headers: { Authorization: "Bearer ACCESS_TOKEN" } } }); // Available modules sdk.message // Send messages sdk.media // Manage media files sdk.template // Manage templates sdk.webhook // Handle webhooks sdk.phoneNumbers // Manage phone numbers sdk.businessProfile // Manage business profile sdk.whatsappBusinessAccount // Account info sdk.subscribedApps // Webhook subscriptions ``` -------------------------------- ### get() Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/api-reference/Template.md Retrieves information about a specific message template using its ID. You can specify which fields to return and customize request options. ```APIDOC ## GET /template/{templateID} ### Description Retrieve information about a specific template. ### Method GET ### Endpoint `/template/{templateID}` ### Parameters #### Path Parameters - **templateID** (string) - Yes - The ID of the template to retrieve. #### Query Parameters - **fields** (GetTemplateFields[]) - No - Array of fields to retrieve (e.g., "name", "status", "components"). - **request** (KyOptions) - No - Custom request options. ### Response #### Success Response (200) - **id** (string) - **name** (string) - **category** (TemplateCategory) - **status** (TemplateStatus) - **language** (TemplateLanguage) - **components** (TemplateComponent[]) - **quality_score** ({ date: number, score: TemplateQualityScore }) ### Request Example ```typescript const template = await sdk.template.get("1234567890", { fields: ["name", "status", "language", "components"], }); console.log(template.name); console.log(template.status); // e.g., "APPROVED" ``` ``` -------------------------------- ### Get WhatsApp Media Download URL Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/README.md Retrieve the download URL for a previously uploaded media file. Requires phoneNumberID and the mediaID. ```typescript const result = await sdk.media.upload({ phoneNumberID: "123...809", mediaID: "", }); ``` -------------------------------- ### Upload Media Files (After CLI Removal) Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/CHANGELOG.md Illustrates how to upload media files using the SDK after the CLI removal. Requires the file buffer and MIME type. ```bash # Before: npx @great-detail/whatsapp media upload --mime-type="" < "" ``` ```typescript import fs from "fs"; const fileBuffer = fs.readFileSync(""); const result = await sdk.media.upload({ phoneNumberID: "123...809", mimeType: "", file: fileBuffer, }); ``` -------------------------------- ### Get Whatsapp Business Account Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/api-reference/WhatsappBusinessAccount.md Retrieves details about a specific Whatsapp Business Account. You can specify which fields you want to retrieve to optimize your request. ```APIDOC ## GET /whatsapp_business_accounts/{id} ### Description Retrieves details about a specific Whatsapp Business Account. You can specify which fields you want to retrieve to optimize your request. ### Method GET ### Endpoint /whatsapp_business_accounts/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the Whatsapp Business Account. #### Query Parameters - **fields** (string) - Optional - A comma-separated list of fields to retrieve. Example: "health_status,business_verification_status,account_review_status" ### Response #### Success Response (200) - **health_status** (object) - Contains information about the account's messaging capability and any issues. - **business_verification_status** (string) - The verification status of the business associated with the account. - **account_review_status** (string) - The status of the account review process. ``` -------------------------------- ### Instantiate and Use WhatsApp SDK Client Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/README.md Instantiate the SDK client with authentication headers and use it to send messages. Supports ESM, CJS, and Deno environments. ```typescript import Client from "@great-detail/whatsapp"; // for ESM environments // require("@great-detail/whatsapp"); // for CJS environments // import Client from "npm:@great-detail/whatsapp"; // for Deno // Instantiate the SDK Client const sdk = new Client({ request: { headers: { Authorization: "Bearer ..." }, }, }); // Use it! const message = await sdk.message.createMessage({ phoneNumberID: "123...809", to: "1234567890", type: "text", text: { body: "Hello" }, }); ``` -------------------------------- ### Register Webhook with Express.js Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/api-reference/Webhook.md Handles GET requests for webhook registration using Express.js. It verifies the token and accepts or rejects the registration challenge. ```typescript import express from "express"; app.get("/webhook", async (req, res) => { try { const reg = await sdk.webhook.register({ method: req.method, query: req.query, body: undefined, headers: req.headers, }); // Verify the token matches your configuration if (reg.verifyToken !== process.env.WEBHOOK_VERIFY_TOKEN) { return res.end(reg.reject()); } // Accept the registration return res.end(reg.accept()); } catch (error) { console.error("Webhook registration error:", error); res.status(400).end(); } }); ``` -------------------------------- ### Get Account Information Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/README.md Fetch information about your WhatsApp Business Account. This includes details like the account ID, name, and health status. ```typescript const account = await sdk.whatsappBusinessAccount.get("123456789", { fields: ["id", "name", "health_status"] }); ``` -------------------------------- ### Get Phone Number Information Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/README.md Retrieve details about a specific phone number associated with your WhatsApp Business account. You can specify which fields to retrieve. ```typescript const pn = await sdk.phoneNumbers.getPhoneNumber({ phoneNumberID: "123456789", fields: ["id", "display_phone_number", "quality_rating"] }); ``` -------------------------------- ### Define Client Options Interface Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/types.md Defines the configuration options for initializing the WhatsApp client. Includes optional settings for base URL, graph API version, and request customization. ```typescript interface Options { baseUrl?: string prefixUrl?: string // Deprecated graphVersion?: `v${string}` | (string & NonNullable) request?: Omit } ``` -------------------------------- ### Initialize Client with Authorization Header Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/configuration.md Configure the underlying HTTP client to include an Authorization header for API requests. Replace 'YOUR_ACCESS_TOKEN' with your actual token. ```typescript const sdk = new Client({ request: { headers: { Authorization: "Bearer YOUR_ACCESS_TOKEN", }, }, }); ``` -------------------------------- ### Get a Specific Template Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/api-reference/Template.md Retrieve details for a single message template using its ID. Specify which fields to include in the response, such as name, status, and components. ```typescript const template = await sdk.template.get("1234567890", { fields: ["name", "status", "language", "components"], }); console.log(template.name); console.log(template.status); // e.g., "APPROVED" ``` -------------------------------- ### Create Subscription with Default Settings Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/api-reference/SubscribedApps.md Use this to create a webhook subscription using the default webhook URL and verification token configured for the WhatsApp Business Account. This is simpler if you don't need a custom endpoint. ```typescript const result = await sdk.subscribedApps.createSubscription({ businessAccountID: "123456789", }); if (result.success) { console.log("Subscription created with default settings"); } ``` -------------------------------- ### Configure Client with Custom Base URL Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/api-reference/Client.md Initialize the Client using a custom base URL for the Graph API, along with a specified Graph API version and authorization headers. ```typescript // Use a custom base URL const sdk = new Client({ baseUrl: "https://custom-api.example.com", graphVersion: "v23.0", request: { headers: { Authorization: "Bearer YOUR_ACCESS_TOKEN", }, }, }); ``` -------------------------------- ### create() Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/api-reference/Template.md Creates a new message template. This can be a custom template with specified components or a template based on a pre-defined library template. ```APIDOC ## create() API ### Description Create a new template. This method allows for the creation of both custom templates with detailed components and templates leveraging pre-defined library options. ### Method POST (inferred from SDK method) ### Endpoint /templates (inferred from SDK context) ### Parameters #### Path Parameters - **businessAccountID** (WhatsappBusinessAccountID) - Yes - The WABA ID. #### Query Parameters - **name** (string) - Yes - Unique template name (lowercase, underscores allowed). - **category** (TemplateCategory) - Yes - Template category (AUTHENTICATION, MARKETING, UTILITY, etc.). - **language** (TemplateLanguage) - Yes - Language code (e.g., "en_US", "es_ES"). - **parameter_format** (TemplateParameterFormat) - Yes (custom) - Parameter format: "NAMED" or "POSITIONAL" (required for custom templates). - **components** (CreateTemplateComponent[]) - No (custom) - Template components (header, body, footer, buttons). Omit if using library template. - **library_template_name** (string) - No (library) - Name of the library template to use. Omit if creating custom template. - **library_template_button_inputs** (string) - No (library) - JSON stringified array of button values for library template. - **add_contact_number** (boolean) - No - Add contact number to template. - **add_learn_more_link** (boolean) - No - Add "Learn More" link. - **add_security_recommendation** (boolean) - No - Add security recommendation message. - **add_track_package_link** (boolean) - No - Add package tracking link. - **code_expiration_minutes** (number) - No - Expiration time for auth codes (in minutes). - **request** (KyOptions) - No - Custom request options. ### Request Example ```json { "businessAccountID": "123456789", "name": "order_confirmation", "category": "UTILITY", "language": "en_US", "parameter_format": "NAMED", "components": [ { "type": "BODY", "text": "Your order {{order_id}} has been confirmed. Total: {{amount}}", "example": { "body_text_named_params": [ { "param_name": "order_id", "example": "ORD-12345" }, { "param_name": "amount", "example": "$99.99" } ] } } ] } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the created template. - **status** (TemplateStatus) - The current status of the template (e.g., 'PENDING', 'APPROVED'). - **category** (TemplateCategory) - The category assigned to the template. #### Response Example ```json { "id": "template_id_123", "status": "PENDING", "category": "UTILITY" } ``` ``` -------------------------------- ### Get All Business Profile Information Source: https://github.com/great-detail/whatsapp-js-sdk/blob/main/_autodocs/api-reference/BusinessProfile.md Retrieves all available business profile details for a given phone number ID. Use this when you need the complete profile data. ```typescript const profile = await sdk.businessProfile.getBusinessProfile({ phoneNumberID: "123456789", }); const businessData = profile.data[0]; console.log(`Business: ${businessData.vertical}`); console.log(`About: ${businessData.about}`); console.log(`Address: ${businessData.address}`); console.log(`Email: ${businessData.email}`); console.log(`Websites: ${businessData.websites}`); ```