LINUX, FOSS AND LIBRARY TECHNOLOGY ENTHUSIAST

Tuesday, May 13, 2025

How to Set Up WhatsApp HTTP API for Sending Messages Programmatically

0 comments

 


WhatsApp has become one of the most popular messaging platforms worldwide, making it a great choice for businesses and individuals who want to communicate with their audience. However, automating WhatsApp messaging can be tricky as WhatsApp doesn't offer a native API for all users. With the help of WhatsApp Web and a few essential tools, you can set up your own WhatsApp HTTP API that allows you to send messages programmatically.

In this guide, we'll walk you through how to set up a WhatsApp HTTP API server using Node.js, WhatsApp Web, and Express. This server will enable you to send WhatsApp messages via HTTP requests (e.g., POST requests), which you can integrate into your projects or systems.

Prerequisites

Before we start, make sure you have the following installed:

  • A Linux-based system (we're using Ubuntu/Debian for this example)
  • Node.js (v18.x)
  • Chromium (for WhatsApp Web automation)
  • Basic understanding of the command line

1. Update and Install Prerequisites

Start by updating your system and installing the necessary dependencies:

sudo apt update && sudo apt -y upgrade
sudo apt -y install git curl wget

Next, install Node.js (v18.x):

curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs

Check the installation:

node -v
npm -v

Now, install Chromium (needed for WhatsApp Web automation):

sudo apt install -y chromium

Then, install the required libraries for Chromium to work:

sudo apt install -y gconf-service libgbm-dev libasound2 libatk1.0-0 libc6 libcairo2 \
libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 \
libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 \
libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 \
libxrandr2 libxrender1 libxss1 libxtst6 ca-certificates fonts-liberation libappindicator1 \
libnss3 lsb-release xdg-utils wget

2. Set Up the Project Folder

Create a directory to store your project:

sudo mkdir -p /opt/whatsapp-api
sudo chown -R $USER:$USER /opt/whatsapp-api
cd /opt/whatsapp-api

3. Initialize a Node Project

Initialize the project by creating a package.json file:

npm init -y

4. Install Required Packages

You need to install a few dependencies to interact with WhatsApp Web and build the API:

npm install whatsapp-web.js express qrcode-terminal

Explanation of the packages:
  • whatsapp-web.js: A library for controlling WhatsApp Web programmatically.
  • express: A web framework for Node.js to create HTTP routes.
  • qrcode-terminal: A library to generate the QR code in the terminal for WhatsApp authentication.

5. Create server.js File

Create a file named server.js:

nano server.js

Paste the following code into the file:

const { Client, LocalAuth } = require('whatsapp-web.js');
const express = require('express');
const qrcode = require('qrcode-terminal');

const app = express();
app.use(express.json());

// Create WhatsApp client with persistent session
const client = new Client({
    authStrategy: new LocalAuth({ clientId: 'whatsapp-session' }),
    puppeteer: {
        args: ['--no-sandbox', '--disable-setuid-sandbox']
    }
});

let isClientReady = false;

// Generate and display the QR code for WhatsApp authentication
client.on('qr', (qr) => {
    console.log('📲 Scan this QR code with your WhatsApp:');
    qrcode.generate(qr, { small: true });
});

// When the client is ready, log the success
client.on('ready', () => {
    isClientReady = true;
    console.log('✅ WhatsApp client is ready!');
});

// Basic route to confirm server is running
app.get('/', (req, res) => {
    res.send('📞 WhatsApp HTTP API is running!');
});

// POST route to send messages
app.post('/send', async (req, res) => {
    const { number, message } = req.body;

    if (!number || !message) {
        return res.status(400).send({ error: 'Missing number or message' });
    }

    if (!isClientReady) {
        return res.status(503).send({ error: 'WhatsApp client is not ready' });
    }

    const chatId = number + '@c.us'; // Format the chat ID for WhatsApp

    try {
        await client.sendMessage(chatId, message);
        res.status(200).send({ status: '✅ Message sent' });
    } catch (err) {
        console.error(err);
        res.status(500).send({ error: '❌ Failed to send message', details: err.toString() });
    }
});

// Start the Express server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`🚀 WhatsApp HTTP API listening on http://localhost:${PORT}`);
});

// Initialize the WhatsApp client
client.initialize();

This script sets up a basic Express server and a WhatsApp Web client using the whatsapp-web.js library. It also generates a QR code for WhatsApp authentication and exposes a POST route to send messages via the WhatsApp API.

6. Start the Server

Run the server with the following command:

node server.js

Scan the QR code shown in the terminal with your WhatsApp mobile app to authenticate.

7. Run Server in the Background with PM2

To ensure that your WhatsApp HTTP API server keeps running in the background and restarts on boot, you can use PM2.

Install PM2 globally:

sudo npm install -g pm2

Start the server with PM2:

cd /opt/whatsapp-api
pm2 start server.js --name whatsapp-api

Save the PM2 process list:

pm2 save

Enable PM2 to start automatically on reboot:

sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u mahesh --hp /home/mahesh

pm2 save

8. Test the API

You can now test your WhatsApp API.

GET request to check if the server is running:

curl http://localhost:3000/

POST request to send a message (replace with your own number):

curl -X POST http://localhost:3000/send \
-H "Content-Type: application/json" \
-d '{"number":"919567664972","message":"Hello from my WhatsApp HTTP API!"}'

9. Reboot & Auto-Start Check

Reboot your system:

sudo reboot

After rebooting, check the app status:

pm2 list

Test the API again to make sure everything is working:

curl http://localhost:3000/

Congratulations! You've successfully set up your own WhatsApp HTTP API. You can now send WhatsApp messages programmatically by sending HTTP POST requests. This setup is ideal for automation tasks, integration with other systems, or even building a chatbot.

By using PM2, you ensure that the server runs in the background and starts automatically after a reboot. Enjoy automating WhatsApp messaging with ease!

Reference: 

No comments:

Post a Comment