npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

whatsapp-business

v1.8.0

Published

Node.js connector for the WhatsApp Business APIs with TypeScript support, integration tests and more.

Downloads

1,109

Readme

GitHub Workflow Status Known Vulnerabilities Codecov GitHub last commit GitHub top language npm bundle size npm GitHub

WhatsApp Business API SDK

Node.js connector for WhatsApp Business Cloud API, with TypeScript support.

This project offers a solution to easily interact with WhatsApp Business Cloud API with Heavy integration testing with real API calls to support implementation stability. Built with Axios and no other extra dependency!

The connector is fully typed, tested and documented!

Installation

npm install whatsapp-business

yarn add whatsapp-business

Documentation

Most methods accept JS objects. These can be populated using parameters specified by WhatsApp's API documentation or following the typescript schema.

Usage

Basic usage

import { WABAClient, WABAErrorAPI } from "whatsapp-business";

//You cant get it from the meta for developers app administration
const client = new WABAClient({
	accountId: "<YOUR_ACCOUNT_ID>",
	apiToken: "<YOUR_API_TOKEN>",
	phoneId: "<YOUR_BUSINESS_PHONE_ID>",
});

const foo = async () => {
	try {
		const res = await client.getBusinessPhoneNumbers();
		console.log(res);
	} catch (err) {
		const error: WABAErrorAPI = err;
		console.error(error.message);
	}
};

foo();

Sending messages

You can send a text message

const sendTextMessage = async (body: string, to: string) => {
	try {
		const res = await client.sendMessage({ to, type: "text", text: { body } });
		console.log(res);
	} catch (err) {
		const error: WABAErrorAPI = err;
		console.error(error.message);
	}
};

or an image

const sendPictureMessage = async ({ link, caption }: MediaObject, to: string) => {
	try {
		const res = await client.sendMessage({ to, type: "image", image: { link, caption } });
		console.log(res);
	} catch (err) {
		const error: WABAErrorAPI = err;
		console.error(error.message);
	}
};

sendPictureMessage(
	{ link: "<url_link_to_your_image>", caption: "<image_description>" },
	"<PHONE_NUMBER>"
);

Webhooks

The webhook client will handle the subscription and setup for the webhooks. You must have an HTTPS connection and add the server URL in your application management.

For more info, checks the docs here.

import { WebhookClient, WABAClient } from "./index";

//The token and path must match the values you set on the application management
const webhookClient = new WebhookClient({
	token: "<YOUR_VALIDATION_TOKEN>",
	path: "/whatsapp/webhook",
	port: 8080,
});

const wabaClient = new WABAClient({
	accountId: "<ACCOUNT_ID>",
	phoneId: "<PHONE_ID>",
	apiToken: "<API_TOKEN>",
});

//Starts a server and triggers the received functions based on the webhook event type
webhookClient.initWebhook({
	onStartListening: () => {
		console.log("Server started listening");
	},
	onTextMessageReceived: async (payload, contact) => {
		try {
			const messageId = payload.id.toString();
			const contactNumber = contact.wa_id;
			//Mark message as read
			await wabaClient.markMessageAsRead(messageId);
			//React to message
			await wabaClient.sendMessage({
				to: contactNumber,
				type: "reaction",
				reaction: { message_id: messageId, emoji: "😄" },
			});
			//Respond to message
			await wabaClient.sendMessage({
				type: "text",
				to: contactNumber,
				text: { body: "Ok!" },
				//This is optional, it enables reply-to feature
				context: {
					message_id: messageId,
				},
			});
		} catch (err) {
			console.log(err);
		}
	},
});

You can also provide your own express app:

import { WebhookClient } from "./index";
import express from "express";

const myApp = express();

const webhookClient = new WebhookClient({
	token: "<YOUR_VALIDATION_TOKEN>",
	path: "/whatsapp/webhook",
	expressApp: {
		//Set to false if you want to initialize the server yourself
		//Otherwise, it will start listening when firing initWebhook()
		shouldStartListening: false,
		app: myApp,
	},
});

myApp.listen(8080, () => {
	console.log("My server nows listens to whatsapp webhooks");
});

If you don't provide a express app the client will create a default app on its own, which you can later access:

import { WebhookClient } from "./index";

const webhookClient = new WebhookClient({
	token: "<YOUR_VALIDATION_TOKEN>",
	path: "/whatsapp/webhook",
	port: 8080,
});

const app = webhookClient.expressApp.app;
//Your configuration...
app.set("trust proxy", true);

webhookClient.initWebhook({
	onStartListening: () => {
		console.log("Server started listening");
	},
});

Support

| Cloud API | | --------------------------------------------- | | - [x] Business profiles endpoints | | - [x] Media endpoints | | - [x] Message endpoints | | - [x] Phone Numbers endpoints | | - [x] Registration endpoints | | - [x] Two-Step-Verification endpoints |

| Webhooks | | --------------------------------- | | - [x] Cloud API | | - [ ] Business Management |

| Business Management API | | ----------------------- | | Currently working on |

| Analytics API | | ------------------------------ | | Planning to add future support |

Project

Structure

This project uses typescript. Resources are stored in 2 key structures:

  • src: the whole connector written in typescript
  • dist the packed bundle of the project for use in nodejs environments (generated when running yarn run build).
  • __tests__ all the tests for the connector

Contribution and thanks

Contributions are encouraged, I will review any incoming pull requests.

If you found this project interesting or useful, you would help so much by giving this project a star. Thank you!