whatsapp-api-js

repository·main·Indexed 43 days ago

https://github.com/secreto31126/whatsapp-api-js

A lightweight, dependency-free TypeScript library for interacting with the official WhatsApp Cloud API. It simplifies webhook handling, message sending, and event listening for developers building WhatsApp bots. Supports various message types including text, media, interactive messages, and templates. Compatible with Node.js, Deno, Bun, and Google App Script.

Tokens
26.6K
Snippets
93
Records
113
Agent score
55%

What's inside whatsapp-api-js

  1. Explore whatsapp-api-js tutorials

    main

    The whatsapp-api-js repository provides a comprehensive set of tutorials covering various message types and core features. You can use these tutorials to learn how to implement:

    • Core Operations: Simple WhatsApp creation, setup helpers, middlewares, sending/replying to messages, and initiating/connecting to calls.
    • Message Types:
      • Text: Simple text and text with URL previews.
      • Reactions: Adding and removing reactions.
      • Location: Sending coordinates with or without names.
      • Media: Images, videos, audio, documents, and stickers.
      • Interactive Messages: Reply buttons, options lists, product messages (single/multi), catalogs, Call to Action, Flows (Navigate/Data Exchange), and permission requests (Location/Call/Payments).
      • Contacts: Simple, multiple, or complex contact sharing.
    • Templates: A wide range of WhatsApp Template implementations, from simple templates with variables to complex templates featuring headers, buttons, flows, catalogs, carousels, and OTP prefabs.
  2. Manage errors in message and status emitters (v5.0.0+)

    main

    In version 5.0.0 and later, the post() method no longer catches errors thrown inside message or status emitters. If your handler code throws an error, it will propagate directly to the caller of post(). This allows you to distinguish between library-level errors (WhatsAppAPIError) and errors within your own custom logic.

    import { WhatsAppAPIError } from "whatsapp-api-js/errors";
    
    const Whatsapp = new WhatsAppAPI({ token, secure: false });
    
    Whatsapp.on.message = () => {
        throw new Error("This is an error on my code");
    };
    
    async function post(e) {
        try {
            await Whatsapp.post(e.data);
        } catch (e) {
            if (e instanceof WhatsAppAPIError) {
                console.log("This is a library error");
            } else {
                console.log("This is my faulty code");
            }
        }
    
        return 418;
    }
  3. Use Catalog and Product components in Templates

    main

    Templates can showcase products using Catalog or Multi-Product Message (MPM) components.

    Single-Product Message

    Use CatalogProduct within a HeaderParameter to highlight one specific product.

    import {
        Template,
        HeaderComponent,
        HeaderParameter,
        CatalogProduct
    } from "whatsapp-api-js/messages";
    
    const template_single_product_message = new Template(
        "template_name",
        "en",
        new HeaderComponent(
            new HeaderParameter(new CatalogProduct("product_id", "catalog_id"))
        )
    );

    Multi-Product Message (MPM)

    Use MPMComponent to organize multiple products into sections.

    import {
        Template,
        MPMComponent,
        Product,
        ProductSection
    } from "whatsapp-api-js/messages";
    
    const template_multi_product_message = new Template(
        "template_name",
        "en",
        new MPMComponent(
            new Product("thumbnail"),
            new ProductSection(
                "Section Title",
                new Product("product_1"),
                new Product("product_2")
            ),
            new ProductSection(
                "Another Section",
                new Product("product_3"),
                new Product("product_4")
            )
        )
    );
  4. Initialize WhatsAppAPI using Node18 setup helper

    main

    For Node.js 18+ environments, use the Node18 setup helper from whatsapp-api-js/setup/node to wrap your credentials. This ensures the environment is correctly configured for the runtime.

    import { WhatsAppAPI } from "whatsapp-api-js";
    import { Node18 } from "whatsapp-api-js/setup/node";
    
    const Whatsapp = new WhatsAppAPI(
        Node18({
            token: "",
            appSecret: ""
        })
    );
  5. Use variables in Template headers and bodies

    main

    Templates can include dynamic variables in the header and body using HeaderComponent and BodyComponent. You can pass positional parameters or named parameters to match the template definition.

    Positional Variables

    Use HeaderParameter and BodyParameter to pass values like strings, Currency, or DateTime.

    import {
        Template,
        HeaderComponent,
        HeaderParameter,
        BodyComponent,
        BodyParameter,
        Currency,
        DateTime
    } from "whatsapp-api-js/messages";
    
    const template_variables_message = new Template(
        "template_name",
        "en",
        new HeaderComponent(
            new HeaderParameter("Hello"),
            new HeaderParameter(new Currency(1.5 * 1000, "USD", "U$1.5")),
            new HeaderParameter(new DateTime("01/01/2023"))
        ),
        new BodyComponent(
            new BodyParameter("Hello"),
            new BodyParameter(new Currency(1.5 * 1000, "USD", "U$1.5")),
            new BodyParameter(new DateTime("01/01/2023"))
        )
    );

    Named Variables

    If your template uses named variables (e.g., {{name}}), provide the name as the second argument to the parameter constructor.

    const template_variables_message = new Template(
        "template_name",
        "en",
        new HeaderComponent(
            new HeaderParameter("1234", "delivery_id"),
            new HeaderParameter(new DateTime("07/09/2025"), "date")
        ),
        new BodyComponent(
            new BodyParameter("User", "name"),
            new BodyParameter(new Currency(1.5 * 1000, "USD", "U$1.5"), "cost")
        )
    );
  6. Integrate WhatsAppAPI with Express middleware

    main

    To use the API within an Express application, use the middleware from whatsapp-api-js/middleware/express. You must provide a webhookVerifyToken in the configuration. Use Whatsapp.handle_post(req) within your webhook route handler to process incoming requests.

    import express from "express";
    import { WhatsAppAPI } from "whatsapp-api-js/middleware/express";
    
    const Whatsapp = new WhatsAppAPI({
        token: "",
        appSecret: "",
        webhookVerifyToken: ""
    });
    
    const app = express();
    
    app.post("/webhook", async (req, res) => {
        res.sendStatus(await Whatsapp.handle_post(req));
    });
  7. Configure the WhatsAppAPI client

    main

    To initialize the WhatsAppAPI client, you need credentials from your Meta Business App with WhatsApp API activated:

    1. API Token: A temporary or permanent token.
    2. App Secret: Found in your Meta dashboard under App Settings > Basic > App Secret.
    3. Webhook Verify Token (Optional): A string you define to authenticate webhook GET requests.

    Basic initialization:

    import { WhatsAppAPI } from "whatsapp-api-js";
    
    const Whatsapp = new WhatsAppAPI({
        token: "YOUR_TOKEN",
        appSecret: "YOUR_SECRET"
    });
  8. Set up whatsapp-api-js in Deno

    main

    For Deno 1.25.0 and above, you can import the package directly via npm. For older versions, use esm.sh.

    To use the Deno-specific setup and middleware, import from npm:whatsapp-api-js/middleware/deno and whatsapp-api-js/setup/deno.

    import { WhatsAppAPI } from "npm:whatsapp-api-js/middleware/deno";
    import { Deno } from "whatsapp-api-js/setup/deno";
    
    const Whatsapp = new WhatsAppAPI(
        Deno({
            token: "123",
            appSecret: "123"
        })
    );
    
    Deno.serve(async (req) => {
        if (req.url === "/message" && req.method === "POST") {
            return new Response(null, {
                status: await Whatsapp.handle_post(req)
            });
        }
    });
  9. Handle incoming WhatsApp messages and webhooks

    main

    To receive message updates, you must set up a webhook in your Meta App dashboard (WhatsApp > Settings) and subscribe to the messages event.

    Processing POST requests

    Use Whatsapp.post() to process incoming webhook data. It requires the parsed JSON body, the raw data, and the x-hub-signature-256 header for security.

    Handling Webhook Authentication (GET)

    If you provide webhookVerifyToken in the constructor, use Whatsapp.get(e.query) to handle the GET request used by Meta for webhook verification.

    Event Listeners

    Use Whatsapp.on.message to react to incoming messages and Whatsapp.on.sent to track outgoing messages.

    import { WhatsAppAPI } from "whatsapp-api-js";
    import { Document, Image, Text } from "whatsapp-api-js/messages";
    
    const Whatsapp = new WhatsAppAPI({
        token: "YOUR_TOKEN",
        appSecret: "YOUR_SECRET",
        webhookVerifyToken: "YOUR_VERIFY_TOKEN"
    });
    
    // Handle Webhook GET (Verification)
    function get(e) {
        return Whatsapp.get(e.query);
    }
    
    // Handle Webhook POST (Messages)
    async function post(e) {
        return await Whatsapp.post(
            JSON.parse(e.data),
            e.data,
            e.headers["x-hub-signature-256"]
        );
    }
    
    // Listen for messages
    Whatsapp.on.message = async ({ phoneID, from, message, name, reply }) => {
        if (message.type === "text") {
            await reply(new Text(`Hello ${name}`), true);
        }
        
        // Mark as read
        Whatsapp.markAsRead(phoneID, message.id);
    };
    
    // Listen for sent messages
    Whatsapp.on.sent = ({ phoneID, to, message }) => {
        console.log(`Sent to ${to}: ${message}`);
    };
  10. Set up whatsapp-api-js in Node.js

    main

    The library is server-agnostic and supports various Node.js versions and module systems.

    Module Imports

    • ESM: import { WhatsAppAPI } from "whatsapp-api-js";
    • CommonJS: const { WhatsAppAPI } = require("whatsapp-api-js");

    Version-Specific Setup

    Use the setup helpers to configure the environment correctly based on your Node.js version.

    • Node 19+ (Recommended): Use NodeNext from whatsapp-api-js/setup/node and the Express middleware from whatsapp-api-js/middleware/express.
    • Node 18 (Deprecated): Use Node18 from whatsapp-api-js/setup/node.
    • Node 15 to 17 (Deprecated): Use Node15 from whatsapp-api-js/setup/node. Since fetch is not natively available in these versions, you must provide a fetch ponyfill (e.g., node-fetch).
    // Node 19+ with Express
    import { WhatsAppAPI } from "whatsapp-api-js/middleware/express";
    import { NodeNext } from "whatsapp-api-js/setup/node";
    import express from "express";
    
    const Whatsapp = new WhatsAppAPI(
        NodeNext({
            token: "123",
            appSecret: "123"
        })
    );
    
    const app = express();
    app.post("/message", async (req, res) => {
        res.status(await Whatsapp.handle_post(req));
    });