How to set up webhooks

Kacper Wiacek Product Expert Lead
Kacper Wiacek
7 min read
updated: Dec 4, 2024

Webhooks in ChatBot allow you to connect your bot with external data sources. It can be another product, your internal CRM, or a customer database. With webhooks, you can pass information about the chat at any point of the bot flow. Optionally, you can also return a response back to the customer and send a message in the chat directly from your server.

In this article, you’ll learn how to set up a basic webhook on your local machine. We’ll show you how to collect and log data about the current chat and return a message to the customer.

Getting startedLink icon

In this tutorial, we’ll use NodeJS as the core of our server, but you can write your webhook in whatever server-side language you like. You can see ready-to-use examples in different languages on this page.
In this tutorial, we’ll use NodeJS as the core of our server, but you can write your webhook in whatever server-side language you like. You can see ready-to-use examples in different languages on this page.

To complete the setup described in the next steps, you will need to prepare your local machine first. The requirements are:

Step 1 | Create a new NodeJS projectLink icon

Run the following code on the command line to create the needed files and dependencies:

Creating NodeJS project
$ mkdir chatbot-webhooks // create a new directory
$ cd chatbot-webhooks // go to the created directory
$ touch index.js // create empty index.js file
$ npm init // create package.json
$ npm install express body-parser --save // install required dependencies

Step 2 | Create HTTP serverLink icon

Add the following code to your index.js file and put your verification token into the token variable.

index.js
'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const app = express().use(bodyParser.json()); // creates http server
const token = 'VERIFICATION_TOKEN'; // type your verification token here

// app.listen() part should always be located in the last line of your code
app.listen(3000, () => console.log('[ChatBot] Webhook is listening')); 

This code creates an HTTP server that listens for requests on port 3000. For this guide, we’re using Express.js, but you can do it using only Node.js or any other framework you use.

A verification token is used to verify if the request comes from a trusted source. It’s required and can’t be empty.
A verification token is used to verify if the request comes from a trusted source. It’s required and can’t be empty.

Step 3 | Return the challengeLink icon

Add the following code to your index.js file right above the app.listen line:

index.js
app.get('/', (req, res) => {
    // check if verification token is correct
    if (req.query.token !== token) {
        return res.sendStatus(401); // if not, return unauthorized error
    }

    // return challenge
    return res.end(req.query.challenge);
});

This code is required to ensure your webhook is authentic and working. In this code, we’re checking that your verification token is correct with the one sent in the request. We’re also returning a challenge response to confirm that your webhook works correctly.

Passing the verification is required to make your webhook work in your bot. You can learn more about the verification process in this article.
Passing the verification is required to make your webhook work in your bot. You can learn more about the verification process in this article.

Step 4 | Webhook endpointLink icon

Add the following code to your index.js file right above the app.listen line:

index.js
app.post('/', (req, res) => {
    // check if verification token is correct
    if (req.query.token !== token) {
        return res.sendStatus(401);
    }

    // print request body
    console.log(req.body);

    // return a text response
    const data = {
        responses: [
            {
                type: 'randomText',
                messages: ['Hi', 'Hello']
            }
        ]
    };

    res.json(data);
});

This code creates your webhook endpoint.

Similarly, as in the previous step, we have to check if your verification code and received tokens are the same. If these tokens are identical, ChatBot returns the object and an example bot response.

Note that the endpoint returns a 200 OK response, which tells ChatBot about the event that has been received.

Main steps in the verification process:

  1. To create a verification token, choose a random string and assign its value to the token parameter in your code.

  2. Go to the Webhooks configuration section in ChatBot and enter the same verification token in the appropriate field.

  3. ChatBot will send a GET request to your webhook URL with the verification token in the token parameter of the query string.

  4. Verify the received token with the verification token. If both strings match, ChatBot will respond with the challenge parameter.

  5. Your webhook has been verified successfully.

If you’re having problems with the verification process, see our Troubleshooting Webhooks article.
If you’re having problems with the verification process, see our Troubleshooting Webhooks article.

Step 5 | Publish your webhook serverLink icon

In this tutorial, we’re using ngrok, which exposes local servers behind NATs and firewalls to the public internet over secure tunnels. For production usage, you should deploy your webhook code to the server of your choice. This can be your own hardware or a cloud-based service like AWS or Heroku.

Before continuing, start your webhook server by typing node index.js in the terminal/command prompt.
Before continuing, start your webhook server by typing node index.js in the terminal/command prompt.

To publish your webhook server, follow these steps:

  1. Install ngrok on your machine to expose the web server you’ve just created on your local machine to the internet. On Windows, just double-click ngrok.zip to unzip it. On Linux and macOS, you can unzip ngrok from a terminal with the following command:

Terminal
$ unzip /path/to/ngrok.zip
  1. Make sure you’re logged in to your ngrok account. If you’re not sure, follow this step to connect your account to your local machine.

  2. Double-check if your webhook server is up and running. In your terminal window, there should be a “[ChatBot] Webhook is listening” message.

  3. Open up a new terminal window/tab and keep the previous one open. In the new terminal window, type:

Terminal
$ ./ngrok http 3000
  1. Now you should see a screen similar to the one below. The address in the Forwarding line states the public address of your webhook. In this case, it is https://<unique_url>.eu.ngrok.io. Save this address for later.Terminal with ngrok

Make sure that you’re logged in to your ngrok account. If you are, you should see the “Account” line in your ngrok session screen (see the screen above).
Make sure that you’re logged in to your ngrok account. If you are, you should see the “Account” line in your ngrok session screen (see the screen above).

Step 6 | Add your webhook to ChatBotLink icon

  1. Go to the Chatbots section and select your chatbot or create a new one.ChatBot Dashboard

  2. Click on the Integrations icon at the top right corner.ChatBot Integrations

  3. Select “Webhook” from the list. Then, confirm your selection by clicking on the “Create new webhook” button.ChatBot Webhooks

  4. Insert your webhook name (1) and copy the ngrok public URL (2) mentioned in the previous steps. Make sure to set the verification token (3) to the same value as in your webhook code, then click on the “Add integration.” button (4)
    Webhook configuration

  5. You will get a confirmation message if the webhook was added successfully.

Having trouble saving your webhook? See our Troubleshooting Webhooks article for possible solutions.
Having trouble saving your webhook? See our Troubleshooting Webhooks article for possible solutions.

Step 7 | Adding webhook to your chatbotLink icon

Once the webhook is added, go back to your chatbot, and add a webhook action. Next, select your webhook from the list. Then click save to finish the configuration process.Adding webhook to your bot

Step 8 | Test your webhookLink icon

Your webhook is ready to test. Use the Testing Tool to trigger your webhook interaction. A triggered interaction that has a webhook should be reflected in your terminal and should send a message in the chat as a response.

Advanced UsageLink icon

If you plan to continue using webhooks after this tutorial and customize them to your use case, visit our documentation for more information about advanced usage. You can find the documentation under this link.

Next stepsLink icon

Was this article helpful?

Got it!

Thanks for your feedback.

Thank you!

We’re happy to help.

Start a free ChatBot trial
and build your first chatbot today!

Free 14-day trial No credit card required

Discover our text| products