# Receive WhatsApp messages using Node js

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!

{% embed url="<https://youtu.be/OnLtP2tHOk4>" %}

{% hint style="success" %}
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!
{% endhint %}

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

{% hint style="info" %}
Detailed manual about webhooks [here](/help-desk/receiving/webhooks.md)
{% endhint %}

### 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](https://panel.whapi.cloud/register).

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

<figure><img src="/files/v3LrSMlIfD99P8l5faJz" alt=""><figcaption><p>Settings on your channel</p></figcaption></figure>

<figure><img src="/files/GnlIokc7ncef04TiSZCI" alt=""><figcaption><p>Webhook settings</p></figcaption></figure>

{% embed url="<https://youtu.be/gql85pOlYs4>" %}
How to receive messages from WhatsApp API Webhook locally using Ngrok
{% endembed %}

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

```json
{
  "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:

```javascript
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!


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://support.whapi.cloud/help-desk/receiving/webhooks/receive-messages/receive-whatsapp-messages-using-node-js.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
