Help Desk
  • Getting Started
    • 🙌Welcome to Whapi.Cloud
    • 💰Pricing
    • ☕Partners
    • 🚀Getting started
    • 👨‍💻API Docs
      • Developer hubs
      • Swagger environment
      • Postman collection
  • Sending
    • Introduction
    • Send text message
      • Whatsapp API send message PHP
      • Whatsapp API send message Python
      • Whatsapp API send message Node JS
      • Whatsapp API send message С#
      • Whatsapp API send message Java
      • API integration with VB6
      • Whatsapp API send message GO (Golang)
    • Send video, audio, image, document
    • Send Group message
    • Send post to WhatsApp Channel
    • Send message with Buttons
    • Send Emoji
    • Overview of other methods for sending
      • Send Voice message
      • Send contact (vCard)
      • Send message reactions
  • Receiving
    • Introduction
    • Webhooks
      • Our webhooks (Tracked events)
      • Where to Find the Webhook URL?
      • Set the webhook link to the channel
      • Detailed webhook settings
      • How to check the webhook?
      • Incoming webhooks format
        • Incoming message
        • Sent message
        • Chats
        • Groups
        • Account and device status
        • Other
          • Presences
          • Views of stories (statuses)
          • Story (status) from your contacts
          • Calls
      • Receive messages
        • Receive WhatsApp messages using PHP
        • Receive WhatsApp messages using Node js
        • Receive WhatsApp messages using Python
    • HTTP API
      • Retrieve a Specific User's Chat History
      • Get a full-size picture in the response
      • Get order items
      • Get a profile picture of a chat or user
    • File expiration period
  • Groups
    • Send Group message
      • Mentioning all participants in a WhatsApp group
    • Get list of group members
    • Add new member to Group
  • Channels
    • Send post to WhatsApp Channel
    • Get messages from Channels
    • Get votes from polls in the Channel
  • Communities
    • Introduction
    • Create a community
    • Add a member to a community
    • Send announcement
    • Get info on community participants
    • Add a group / Exclude a group from the community
  • Account
    • Setting "Auto Download"
    • Customizable Webhook Headers
    • How to find out the IP channel
    • How to Delete a Channel
    • Add Business Info to Invoice
  • Source code
    • WhatsApp ChatBot
      • WhatsApp Python Bot
      • WhatsApp PHP Bot
      • WhatsApp Node JS Bot
      • WhatsApp Java Bot
    • WhatsApp API Google Sheets
    • WhatsApp Phone Number Checker
    • Request Distributor (Balancer)
  • FAQ
    • Chat ID. What is it and how to get it?
    • Current status of Buttons on WhatsApp
    • How to send a paragraph (line break)
    • Inactive Links in WhatsApp Messages
    • WhatsApp Text Formatting
    • Checking if the number has Whatsapp
    • Specifics of sending messages to numbers of different countries
    • Why aren't participants being added to the group?
  • Does WhatsApp API Work with the Phone Turned Off?
  • Hints
    • Android Emulators
    • Virtual Numbers for WhatsApp
    • How to use polls as buttons?
    • How to check who blocked you in Whatsapp?
    • Setting up a WhatsApp proxy
  • Integrations
    • Make.com
      • Ready-Made Scenarios
        • WhatsApp & Whisper API: Voice-to-Text Integration
        • Automated WhatsApp Group Message Forwarding in Make.com
      • Request Scenario Setup
    • Pabbly Connect
    • Google Contacts
    • DialogFlow
    • n8n
  • Tools
    • WhatsApp Number Checker
    • Automatic warm-up module
    • WhatsApp Activity Safety Meter
    • Residential Proxies from Whapi.Cloud
  • Troubleshooting
    • Couldn't Link Device – WhatsApp QR Code or Pairing Code Fails
    • Channel status “SYNC_ERROR”
    • Not getting a READ status on webhook
    • 429 (Too Many Requests) - Soft Ban
    • “Waiting for this message. This may take a while” – WhatsApp Message Error
    • Missing push notifications after connecting to API
  • Blocking
    • How to not get Banned?
    • How to do mailings without the risk of being blocked?
    • If My Number Is Banned, Can It Be Restored?
    • Unlocking Your WhatsApp Number
    • Connecting a New WhatsApp Number After a Ban: Steps and Recommendations
    • Warming Up New Phone Numbers for WhatsApp API
  • Partner Documentation
    • Introduction
    • Partner Dashboard Overview
    • Partner Program Guidelines
      • Workflow: Step-by-Step
      • Billing for Partners
      • Allocating Days to Customer Channels: Best Practices & Guide
      • Interface for channel management
    • Partner Documentation
      • Channel creation
      • Changing channel mode
      • Channel extension
      • Channel deletion
      • Getting the list of channels
      • Notices of end of days on balance
Powered by GitBook
On this page
  • Introduction
  • What You'll Need
  • Set Up Your Webhook on Whapi.Cloud
  • Wrapping Up

Was this helpful?

  1. Receiving
  2. Webhooks
  3. Receive messages

Receive WhatsApp messages using Node js

How to Receive WhatsApp messages using Node.js and webhook

PreviousReceive WhatsApp messages using PHPNextReceive WhatsApp messages using Python

Last updated 1 year ago

Was this helpful?

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: . 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.

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.

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!

Detailed manual about webhooks

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

here
sign up here
https://github.com/Whapi-Cloud/nodejs-whatsapp-chatbot
How to receive messages from WhatsApp API Webhook locally using Ngrok
Settings on your channel
Webhook settings