Receive WhatsApp messages using Node js

How to Receive WhatsApp messages using Node.js and webhook

Welcome to our hands-on tutorial on setting up your server to receive WhatsApp messages using Node.js and a webhook. This method can vastly simplify your interaction with customers and make your business more responsive. Let's dive in!

By the way, we have the source code of a great NodeJS chatbot: https://github.com/Whapi-Cloud/nodejs-whatsapp-chatbot. It can handle incoming messages, try it!

Introduction

Webhooks are the perfect tool for getting real-time updates, as they send data whenever a particular event happens. In this guide, we'll walk you through crafting a simple Node.js app to serve as your webhook, which will receive incoming WhatsApp messages.

Detailed manual about webhooks here

What You'll Need

  1. Node.js: Ensure you have Node.js installed on your server or local machine. This tutorial uses Node.js v14.16.1, but the code should be compatible with other versions.

  2. Express: Express is a web application framework for Node.js that we will use to handle incoming HTTP requests. You can install it using npm (Node.js package manager) with the command npm install express.

  3. A Whapi.Cloud Account: We'll be using the Whapi.Cloud service to interact with WhatsApp. If you're not registered already, sign up here.

Set Up Your Webhook on Whapi.Cloud

Before we delve into coding, set up a webhook URL on Whapi.Cloud by following these steps:

  1. Log in to your Whapi.Cloud account and navigate to your Channel Dashboard.

  2. Select 'Settings', then 'Webhook'.

  3. Specify the URL where Whapi.Cloud will send the incoming messages. This should point to the Node.js app we're about to create.

  4. Don't forget to save your changes.

Sample Message Format

When utilizing the Whapi.Cloud WhatsApp API and configuring a webhook URL, incoming messages are delivered in a well-defined JSON structure.

{
  "messages": [
    {
      "id": "IINCYddajIbJxaBbi0gwXQ-gOUSdTZG3w",
      "from_me": false,
      "type": "text",
      "chat_id": "15055913687@s.whatsapp.net",
      "timestamp": 1696502988,
      "text": {
        "body": "Hello"
      },
      "from_name": "Alexander"
    }
  ]
}

Sample Node.js Script

Let's create a new file named webhook.js in your project's root directory. Below is the code for your webhook:

const express = require('express');
const bodyParser = require('body-parser');

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

app.post('/webhook', (req, res) => {
    const messages = req.body.messages;
    
    messages.forEach(message => {
        if (!message.from_me) {
            const chat_id = message.chat_id.split('@')[0];  // Extracting phone number from chat_id
            const text = message.text.body;
            
            console.log(`Received message from ${chat_id}: ${text}`);
            
            // Further processing: Database insertion, email forwarding, etc.
        }
    });

    res.status(200).json({ status: 'success' });
});

const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

The Node.js script, using the Express framework, initiates a server ready to accept incoming POST requests on the /webhook endpoint. Upon receiving a request, indicating a new WhatsApp message, the script deduces the sender's phone number and the content of the message. While the current script logs this information, the code can be enriched—for instance, by merging with a database or devising automated response logic centered on the message's essence.

For this script to function, make sure you have Express and body-parser installed in your Node.js environment:

npm install express body-parser

Run the script to spark the server, which, by default, will be accessible at http://127.0.0.1:3000/. Configure your webhook URL to route to this endpoint to start processing incoming messages seamlessly.

Wrapping Up

Congratulations! You've successfully configured a Node.js webhook to accept incoming WhatsApp messages. By integrating this powerful tool, you'll make your customer interaction processes more efficient, particularly when dealing with large volumes of messages.

Feel free to tinker with your new setup and discover its potential. If you stumble upon any issues or have any questions, don't hesitate to reach out. Our team is always ready to assist!

Last updated