whatsapp-api-js - v6.1.1
    Preparing search index...

    Interface API<EmittersReturnType>

    interface API<EmittersReturnType> {
        get(params: GetParams): string;
        post(
            data: PostData,
            raw_body: string,
            signature: string,
        ): Promise<undefined | EmittersReturnType>;
        post(data: PostData): Promise<undefined | EmittersReturnType>;
    }

    Type Parameters

    • EmittersReturnType

    Implemented by

    Index

    Methods

    Methods

    • GET helper, must be called inside the get function of your code. Used once at the first webhook setup.

      Parameters

      • params: GetParams

        The request object sent by Whatsapp

      Returns string

      The challenge string, it must be the http response body

      // Simple http example implementation with Whatsapp.get() on Node@^19
      import { WhatsAppAPI } from "whatsapp-api-js";
      import { WhatsAppAPIError } from "whatsapp-api-js/errors";
      import { NodeNext } from "whatsapp-api-js/setup/node";

      import { createServer } from "http";

      const token = "token";
      const appSecret = "appSecret";
      const Whatsapp = new WhatsAppAPI(NodeNext({ token, appSecret }));

      function handler(req, res) {
      if (req.method == "GET") {
      const params = new URLSearchParams(req.url.split("?")[1]);

      try {
      const response = Whatsapp.get(Object.fromEntries(params));
      res.writeHead(200, {"Content-Type": "text/html"});
      res.write(response);
      } catch (err) {
      res.writeHead(err instanceof WhatsAppAPIError ? err.httpStatus : 500);
      }

      res.end();
      } else res.writeHead(501).end();
      };

      const server = createServer(handler);
      server.listen(3000);

      Class Errors.WhatsAppAPIMissingVerifyTokenError if webhookVerifyToken is not specified

      Class Errors.WhatsAppAPIMissingSearchParamsError if the request is missing data

      Class Errors.WhatsAppAPIFailedToVerifyTokenError if the verification tokens don't match

    post

    • post(
          data: PostData,
          raw_body: string,
          signature: string,
      ): Promise<undefined | EmittersReturnType>

      POST helper, must be called inside the post function of your server. When setting up the webhook, you can subscribe to messages and calls. Unexpected events will throw an Errors.WhatsAppAPIUnexpectedError.

      raw_body and signature are required when secure is true on initialization (default).

      Parameters

      • data: PostData

        The POSTed data object sent by Whatsapp

      • raw_body: string

        The raw body of the POST request

      • signature: string

        The x-hub-signature-256 header signature sent by Whatsapp

      Returns Promise<undefined | EmittersReturnType>

      The emitter's return value, undefined if the corresponding emitter isn't set

      // author arivanbastos on issue #114
      // Simple http example implementation with Whatsapp.post() on Node@^19
      import { WhatsAppAPI } from "whatsapp-api-js";
      import { WhatsAppAPIError } from "whatsapp-api-js/errors";
      import { NodeNext } from "whatsapp-api-js/setup/node";

      import { createServer } from "http";

      const token = "token";
      const appSecret = "appSecret";
      const Whatsapp = new WhatsAppAPI<number>(NodeNext({ token, appSecret }));

      function handler(req, res) {
      if (req.method == "POST") {
      const chunks = [];
      req.on("data", (chunk) => chunks.push(chunk));

      req.on("end", async () => {
      const body = Buffer.concat(chunks).toString();

      try {
      const response = await Whatsapp.post(JSON.parse(body), body, req.headers["x-hub-signature-256"]);
      res.writeHead(response);
      } catch (err) {
      res.writeHead(err instanceof WhatsAppAPIError ? err.httpStatus : 500);
      }

      res.end();
      });
      } else res.writeHead(501).end();
      };

      Whatsapp.on.message = ({ phoneID, from, message, name, reply, offload }) => {
      console.log(`User ${name} (${from}) sent to bot ${phoneID} a(n) ${message.type}`);
      offload(() => reply(new Text("Hello!")));
      return 202;
      };

      const server = createServer(handler);
      server.listen(3000);

      Class Errors.WhatsAppAPIMissingRawBodyError if the raw body is missing

      Class Errors.WhatsAppAPIMissingSignatureError if the signature is missing

      Class Errors.WhatsAppAPIMissingAppSecretError if the appSecret isn't defined

      Class Errors.WhatsAppAPIMissingCryptoSubtleError if crypto.subtle or ponyfill isn't available

      Class Errors.WhatsAppAPIFailedToVerifyError if the signature doesn't match the hash

      Class Errors.WhatsAppAPIUnexpectedError if the POSTed data is not a valid Whatsapp API request

      Any error generated within the user's callbacks

      Class Errors.WhatsAppAPIUnexpectedError if the POSTed data is valid but not a message or status update (ignored)

    • post(data: PostData): Promise<undefined | EmittersReturnType>

      POST helper, must be called inside the post function of your server. When setting up the webhook, you can subscribe to messages and calls. Unexpected events will throw an Errors.WhatsAppAPIUnexpectedError.

      raw_body and signature are NOT required when secure is false on initialization.

      Parameters

      • data: PostData

        The POSTed data object sent by Whatsapp

      Returns Promise<undefined | EmittersReturnType>

      The emitter's return value, undefined if the corresponding emitter isn't set

      The method isn't deprecated, but it's strongly discouraged to use the server without signature verification. It's a security risk.

      Provide an appSecret and set secure to true on WhatsAppAPI initialization.

      Class Errors.WhatsAppAPIUnexpectedError if the POSTed data is not a valid Whatsapp API request

      Any error generated within the user's callbacks

      Class Errors.WhatsAppAPIUnexpectedError if the POSTed data is valid but not a message, call or status update (ignored)