trysoftwacloudapi
v1.1.8
Published
TrySoft Whatsapp Cloud Api Wrapper
Maintainers
Readme
trysoftwacloudapi
trysoftwacloudapi is a Node.js library for creating bots and sending/receiving messages using the Whatsapp Cloud API.
Contains built-in Typescript declarations.
Install
Using npm:
npm i trysoftwacloudapiUsing yarn:
yarn add trysoftwacloudapiUsage
import { createBot } from 'trysoftwacloudapi';
// or if using require:
// const { createBot } = require('trysoftwacloudapi');
(async () => {
try {
// replace the values below
const from = 'YOUR_WHATSAPP_PHONE_NUMBER_ID';
const token = 'YOUR_TEMPORARY_OR_PERMANENT_ACCESS_TOKEN';
const to = 'PHONE_NUMBER_OF_RECIPIENT';
const webhookVerifyToken = 'YOUR_WEBHOOK_VERIFICATION_TOKEN';
// Create a bot that can send messages
const bot = createBot(from, token);
// Send text message
const result = await bot.sendText(to, 'Hello world');
// Start express server to listen for incoming messages
// NOTE: See below under `Documentation/Tutorial` to learn how
// you can verify the webhook URL and make the server publicly available
await bot.startExpressServer({
webhookVerifyToken,
});
// Listen to ALL incoming messages
// NOTE: remember to always run: await bot.startExpressServer() first
bot.on('message', async (msg) => {
console.log(msg);
if (msg.type === 'text') {
await bot.sendText(msg.from, 'Received your text message!');
} else if (msg.type === 'image') {
await bot.sendText(msg.from, 'Received your image!');
}
});
} catch (err) {
console.log(err);
}
})();Documentation
- API Reference.
- Tutorial for a step-by-step on how to get everything set up.
Examples
Sending other message types (read more in API reference):
// Send image
const result = await bot.sendImage(to, 'https://picsum.photos/200/300', {
caption: 'Random jpg',
});
// Send location
const result = await bot.sendLocation(to, 40.7128, -74.0060, {
name: 'New York',
});
// Send template
const result = await bot.sendTemplate(to, 'hello_world', 'en_us');
// Send reply buttons
const result = await bot.sendReplyButtons(
to,
'How can we help you?',
{
support: 'Support',
sales: 'Sales',
pricing: 'Pricing',
},
{
footerText: 'Choose an option',
header: {
type: 'text',
text: 'Menu',
},
},
);Additional message types:
// React to a message
const result = await bot.sendReaction(to, messageId, '👍');
// Show typing indicator (also marks the message as read)
const result = await bot.sendTypingIndicator(messageId);
// CTA URL button
const result = await bot.sendCtaUrl(
to,
'Check out our website',
'Visit site',
'https://example.com',
{ footerText: 'Opens in browser' },
);
// WhatsApp voice call button
const result = await bot.sendVoiceCall(to, 'Call us on WhatsApp for faster help', {
displayText: 'Call now',
ttlMinutes: 10080,
});
// Address request (India only)
const result = await bot.sendAddress(
to,
'Thanks for your order! Where should we deliver?',
'IN',
{ values: { name: 'Customer', phone_number: '+91xxxxxxxxxx' } },
);
// Single product
const result = await bot.sendProduct(to, catalogId, productRetailerId, {
bodyText: 'Check out this item',
});
// Multi-product list
const result = await bot.sendProductList(
to,
catalogId,
'Our picks',
'Browse these products',
[
{
title: 'Section 1',
product_items: [{ product_retailer_id: 'sku-1' }],
},
],
);
// Full catalog
const result = await bot.sendCatalog(to, 'Browse our catalog', {
thumbnailProductRetailerId: 'sku-1',
});Groups API
Requires an Official Business Account (OBA). Subscribe your app to group_lifecycle_update, group_participants_update, group_settings_update, and group_status_update.
If the phone number has not been allow-listed for Groups, every call throws with error code 131215 (This phone number is not eligible to access Groups APIs). Check eligibility in the Groups getting started guide.
// Create a group (invite link arrives via group_lifecycle_update webhook)
await bot.createGroup({
subject: 'Support room',
description: 'Customer support',
joinApprovalMode: 'auto_approve',
});
// Send text / media / templates to a group
await bot.sendText(groupId, 'Hello group', { recipientType: 'group' });
await bot.sendImage(groupId, 'https://picsum.photos/200/300', {
recipientType: 'group',
caption: 'Photo',
});
await bot.sendTemplate(groupId, 'hello_world', 'en_US', undefined, {
recipientType: 'group',
});
// Invite a user with a group invite link template
await bot.sendGroupInviteTemplate(to, 'group_invite_template', 'en', groupId);
// Pin / unpin
await bot.pinGroupMessage(groupId, messageId, 7);
await bot.unpinGroupMessage(groupId, messageId);
// Manage
await bot.getInviteLink(groupId);
await bot.listGroups();
await bot.getGroup(groupId, ['subject', 'description', 'participants']);
await bot.removeParticipants(groupId, ['263774166961']);
await bot.deleteGroup(groupId);
// Listen for group messages and metadata
bot.on('message', (msg) => {
if (msg.group_id) {
console.log('group message', msg.group_id, msg);
}
});
bot.on('group_lifecycle_update', (event) => console.log(event));
bot.on('group_participants_update', (event) => console.log(event));Calling API
Signaling and settings for WhatsApp Cloud API Calling. Audio media still needs your own WebRTC stack or SIP PBX — this library only handles Graph call actions and webhooks.
Prerequisites: messaging limit ≥ 2,000/day (or sandbox/test number), subscribe the app to the calls webhook field, and enable calling on the phone number via settings.
// Enable calling on the business number
await bot.updateCallSettings({
status: 'ENABLED',
call_icon_visibility: 'DEFAULT',
callback_permission_status: 'ENABLED',
});
await bot.getCallSettings();
// Ask the user for permission to call them (customer service window)
await bot.sendCallPermissionRequest(
to,
'We would like to call you about your order.',
);
await bot.getCallPermissions({ userWaId: to });
// User-initiated: after calls webhook with event=connect + SDP offer
bot.on('calls', async (event) => {
const call = event.data.calls?.[0];
if (call?.event === 'connect' && call.session) {
const answer = { sdp_type: 'answer', sdp: myWebRtcSdpAnswer };
await bot.preAcceptCall(call.id, answer);
await bot.acceptCall(call.id, answer);
}
if (call?.event === 'terminate') {
console.log('call ended', call.duration);
}
});
// Business-initiated (requires approved call permission + SDP offer from WebRTC)
await bot.connectCall(to, { sdp_type: 'offer', sdp: myWebRtcSdpOffer });
// Hang up / decline
await bot.rejectCall(callId);
await bot.terminateCall(callId);
// Call button CTA (already available)
await bot.sendVoiceCall(to, 'Call us on WhatsApp', { displayText: 'Call now' });
// Permission reply arrives as a normal interactive message
bot.on('call_permission_reply', (msg) => console.log(msg.data));Customized express server (read more below):
import cors from 'cors';
// Create bot...
const bot = createBot(...);
// Customize server
await bot.startExpressServer({
webhookVerifyToken: 'my-verification-token',
port: 3000,
webhookPath: `/custom/webhook`,
useMiddleware: (app) => {
app.use(cors()),
},
});Listening to other message types (read more in API reference):
const bot = createBot(...);
await bot.startExpressServer({ webhookVerifyToken });
// Listen to incoming text messages ONLY
bot.on('text', async (msg) => {
console.log(msg);
await bot.sendText(msg.from, 'Received your text!');
});
// Listen to incoming image messages ONLY
bot.on('image', async (msg) => {
console.log(msg);
await bot.sendText(msg.from, 'Received your image!');
});Notes
1. Verifying your Webhook URL
By default, the endpoint for whatsapp-related requests will be: /webhook/whatsapp.
This means that locally, your URL will be: http://localhost/webhook/whatsapp.
You can use a reverse proxy to make the server publicly available. An example of this is ngrok.
You can read more on the Tutorial.
2. Handling incoming messages
The implementation above creates an express server for you through which it listens to incoming messages. There may be plans to support other types of server in future (PRs are welcome! :)).
You can change the port as follows:
await bot.startExpressServer({
port: 3000,
});By default, all requests are handled by the POST|GET /webhook/whatsapp endpoint. You can change this as below:
await bot.startExpressServer({
webhookPath: `/custom/webhook`,
});Note: Remember the leading /; i.e. don't use custom/whatsapp; instead use /custom/whatsapp.
If you are already running an express server in your application, you can avoid creating a new one by using it as below:
// your code...
import express from 'express';
const app = express();
...
// use the `app` variable below:
await bot.startExpressServer({
app,
});To add middleware:
import cors from 'cors';
await bot.startExpressServer({
useMiddleware: (app) => {
app.use(cors()),
},
});Full customized setup:
import cors from 'cors';
await bot.startExpressServer({
webhookVerifyToken: 'my-verification-token',
port: 3000,
webhookPath: `/custom/webhook`,
useMiddleware: (app) => {
app.use(cors()),
},
});3. on() listener
This library uses a single process pubsub, which means that it won't work well if you're deploying on multi-instance clusters, e.g. distributed Kubernetes clusters. In future, there may be plans to export/support a pubsub reference which can be stored in extenal storage, e.g. redis (PRs are welcome! :)).
Development
# install npm modules
npm i
# eslint
npm run lint
# typescript check
npm run ts-check
# test
## Read 'Local Testing' below before running this
npm t
# build
npm run buildLocal Testing
Create a .env file in the root of your project:
FROM_PHONE_NUMBER_ID=""
ACCESS_TOKEN=""
VERSION=""
TO=""
WEBHOOK_VERIFY_TOKEN=""
WEBHOOK_PATH=""