Send WhatsApp messages using NodeJS
There are many social messaging platforms in the market and each provide tools for developers so that they can integrate those platforms either of the way. Today I’ll be talking about how to use WhatsApp APIs to send messages to users using NodeJS.
Note: A business WhatsApp account is required getting started docs for details on WhatsApp business account process.
Before we start I’ll suggest you to clone the Postman collection on your machine and then import in your Postman.
$ git clone https://github.com/fbsamples/WhatsApp-Business-API-Postman-Collection
After git clone
is successful the next steps would be
- Open Postman, click on Import and select the two json files one would be
collection.json
andenvironment.json
. - Once imported, a new API collection will be created, along with the environment.
The provided environment contains the list of variables referenced by the API collection.
From the above postman collection I’ll just be using the Login API to get the bearer token so that it can be used in further APIs calls.
Acquiring the Bearer Token
If this is the first time sending API calls, you need to log in and change the admin password. Update the AdminUsername
, AdminPassword
environment variables to their factory defaults of admin and secret and the NewAdminPassword
environment variable to whatever your chose.
Set Authorization to Basic Auth and the username/password variables as shown below. In the Body tab, the new_password
value should be filled from variable NewAdminPassword
. Click Send to send request and get the auth token response.
Once you get a successful response, copy the token
somewhere as it will be used in our application.
Bootstrapping the NodeJS application and also TypeScript
npm init
npm i dotenv axios
tsc --init
Now create a new file index.js
or main.js
as per your choice and also .env
file which contains your secrets.
API_URL=api-url
TOKEN=token
Create a constants.ts
file where we can read the env
variables and use them
require("dotenv").config();export const API_URL = process.env.API_URL;
export const TOKEN = process.env.TOKEN;
Now it’s time to create index.ts
where we’ll try to make the API calls.
Before that the procedure would be:-
- First verify whether that’s a valid WhatsApp number or not by hitting the API
/v1/contacts
. If it’s a valid number then it will returnwa_id
on which we are going to send message. - After the above API is successful then we can go ahead and hit the API
/v1/messages
.
import axios from "axios";
import { API_URL, TOKEN } from "./constants";
require("dotenv").config();async function checkContact(mobileNumber: string) {
let obj = {
blocking: "wait",
contacts: [mobileNumber],
force_check: true,
};
let x: any = await axios.post(`${API_URL}/v1/contacts`, obj, {
headers: {
Authorization: `Bearer ${TOKEN}`,
},
});
return x.data;
}async function sendMessage(mobileNumber: string, name: string, id: string) {
let obj = {
to: mobileNumber,
type: "text",
recipient_type: "individual",
text: {
body: `Welcome ${name} your ID is ${id}`
}
};
let resp: any = await axios.post(`${API_URL}/v1/messages/`, obj, {
headers: {
Authorization: `Bearer ${TOKEN}`,
},
});
return resp.data;
}async function main() {
const mobileNumber = "+xx xxxxxxxxxx";
let mobileStatus = await checkContact(mobileNumber);
if (mobileStatus.contacts[0].status === "valid") {
let whatsAppID = mobileStatus.contacts[0].wa_id;
let msgSentStatus = await sendMessage(whatsAppID, "name", "123");
console.log(msgSentStatus);
if (msgSentStatus.errors !== undefined) {
console.log("----------------------");
console.log(`Error for ${whatsAppID}`);
console.log(`${msgSentStatus.errors[0].title}`);
console.log(`${msgSentStatus.errors[0].details}`);
console.log("----------------------");
}
let messageId: string = msgSentStatus.messages[0].id;
console.log("message sent successfully");
}
}main();
There are other set of APIs as well which you can use. Probably you refer to the following links for more
Contacts API endpoint(To generate wa_ba id against each valid Whatsapp contact number): Link
Creating Message Templates : Link_1 | Link_2
Sending Message Templates: Text | Media
Also you can find the source code for above application here.
In case you have any doubts feel free to open an issue on the repository and we can discuss over there 😄 and don’t forget to clap if you like the blog 😉.