How to Set Up Webhooks for Inbound SMS & Voice on Glitch
Published on October 17, 2024

In this tutorial, you'll learn how to set up webhooks to handle inbound voice calls and SMS messages using Glitch and a Node.js server, with Vonage as your communication platform. A webhook is a way for one application to send real-time data to another when a specific event occurs. It acts as a listener, waiting for an event—like an incoming call or SMS—and triggers a predefined action when that event happens. This allows your server to react instantly to external triggers, ensuring timely responses to user interactions.

Implementing webhooks provides significant benefits for your application. By enabling real-time handling of voice calls and SMS messages, you can create more interactive and responsive communication experiences for your users. For example, you can automate customer support responses, integrate with CRM systems to log interactions, or trigger workflows based on incoming messages. This can enhance user engagement and efficiency by reducing manual tasks.

By the end of this guide, you'll have a fully functional web server that listens for and processes inbound calls and SMS messages through Vonage. Let’s get started!

Prerequisites

Vonage API Account

To complete this tutorial, you will need a Vonage API account. If you don’t have one already, you can sign up today and start building with free credit. Once you have an account, you can find your API Key and API Secret at the top of the Vonage API Dashboard.

Set Up and Configure Your Project

We'll walk through the following steps:

  1. Create a new project.

  2. Configure your server.

  3. Install dependencies.

  4. Share and configure your project.

  5. Integrate webhooks into your Vonage application.

  6. Test your new features.

Step 1: Create a New Project

Log into your Glitch account.

Click “New project” on the top right, then click “glitch-hello-node”.

Once done, you will see the new project created.

Screen showing Glitch website with starter app options (including glitch-hello-node) and list of projects belowGlitch Hello Node

Step 2: Configure Your Server

To set up your server for handling inbound and outbound calls and SMS, follow these steps:

  1. On the left pane, locate and click on server.js.

    IDE project folder with server.js circledserverjs file

  2. In the right pane, select all the content of server.js and delete it.

  3. Copy and paste the provided code snippet into server.js. This code will configure a web server capable of processing web requests for handling inbound and outbound calls and SMS.

const path = require("path");
const app = require('express')();
const bodyParser = require('body-parser');
const fastify = require("fastify")({ logger: true });

fastify.register(require("@fastify/static"), {
  root: path.join(__dirname, "public"),
  prefix: "/",
});

fastify.register(require("@fastify/formbody"));

fastify.register(require('@fastify/express')).after(() => {
  fastify.use(bodyParser.urlencoded({ extended: false })); // for Postman x-www-form-urlencoded
  fastify.use(bodyParser.json());
  fastify.use(app);
});

app.get("/webhooks/answer", function (request, reply) {
  const from = request.query.from;
  const fromSplitIntoCharacters = from.split('').join(' ');
  const ncco = [{
    action: 'talk',
    text: `Thank you for calling from ${fromSplitIntoCharacters}`,
    loop: 10
  }];
  console.log(`logging call from ${fromSplitIntoCharacters}`);
  reply.json(ncco);
});

app.get("/webhooks/inbound-sms", function (request, reply) {
  console.log(`logging incoming sms`);
  const params = Object.assign(request.query, request.body);
  console.log(params);
  reply.status(200).end();
});

app.post("/webhooks/inbound-sms", function (request, reply) {
  console.log(`logging incoming sms`);
  console.log(request.body);
  reply.status(200).end();
});

fastify.listen(
  { port: process.env.PORT, host: "0.0.0.0" },
  function (err, address) {
    if (err) {
      console.error(err);
      process.exit(1);
    }
    console.log(`Your app is listening on ${address}`);
  }
);

If you wish to increase the call duration, look for the loop parameter in the code snippet and adjust its value.

const ncco = [{
  action: 'talk',
  text: `Thank you for calling from ${fromSplitIntoCharacters}`,
  loop: 10
}];
console.log(`logging call from ${fromSplitIntoCharacters}`);
reply.json(ncco);

Verify that you are using the correct Node.js version in your package.json file:

  1. Click on package.json in the left pane.

  2. In the right pane, locate the lines specifying the Node.js version.

  3. Check if the Node.js version is set to 16.x. If it is not, update it to 16.x.

"engines": {

  "node": "16.x"

}

Step 3: Install Dependencies

Click on the “Terminal” button at the bottom of the screen.

list of tabs including status, logs, terminal, tools, and previewbuttonRun the following command to update existing packages:

npm update

Install the required dependencies with the following command:

npm i express @fastify/express body-parser dotenv @vonage/server-sdk @vonage/voice

Run the refresh command to apply changes:

refresh

Step 4: Share and Configure Your Project

Click on the blue “Share” button on the top right and copy the link to the site.

Open your favorite text editor and paste the link you just copied. Then, paste the following URLs:

  • Answer URL:{your link}/webhooks/answer

  • Inbound URL:{your link}/webhooks/inbound-sms

Screenshot of share project window with project linksShare Project

Step 5: Integrate Webhooks into Your Vonage Application

Log into your Vonage developer account.

To purchase a Vonage phone number, go to the left pane menu and select “Numbers”, then “Buy Numbers”. Select the country from which you want to purchase the number. Under Features, select SMS and Voice.

Click “Search” and “Buy” for the number you want to purchase.

On the left pane menu, click “Applications”, then “Create a new application” on the right pane.

Update your application with the following information:

  • Give your application a user-friendly name.

  • Click the “Generate public and private key” button. This will download a private key file named private.key to your desktop. Save this file in a secure folder as it will be needed later.

  • In the “Capabilities” section, toggle on:

    • Voice

    • Messages

  • Set up Voice capabilities:

    • Answer URL: Paste the Answer URL you copied earlier.

    • Event URL: Paste the same Answer URL.

    • Fallback URL: Paste the same Answer URL.

  • Set up Messages capabilities:

    • Inbound URL: Paste the Inbound URL you copied earlier.

    • Status URL: Paste the same Inbound URL.

  • Click “Generate new application” at the bottom right.

Screenshot of application capabilities for voice and messages turned on with URLs for webhooks.capabilitiesOnce the application is created, link the number you purchased to the application by clicking the “Link” button. Copy the linked Vonage number and save it as you will need to call it later.

Link numbers tab with phone numbers listed, their type, features, state, and manage (show what applications they are linked to)link numberOn the left pane, click “API Settings”, select “Messages API” in the toggle, and save your changes.

Step 6: Test your new features.

Now that you’ve integrated a webhook for inbound voice calls, let’s test it!

  1. Make a voice call from your phone to the Vonage number.

  2. Upon connection, you should hear a prompt like “Thank you for calling from…”

  3. Go to the Vonage Dashboard, and on the left-hand panel, click on Logs. Here, you can confirm the call was received successfully.

Call log showing call information including Call ID, direction (inbound) from phone number, to phone number, network, country, and the time and date the call started.Inbound Call LogIf you wish to increase the call duration, change the value of the ‘loop’ parameter.

Now that you’ve integrated a webhook for inbound SMS, let’s test it!

  1. Send an SMS from any number to the Vonage number.

  2. Go to the Vonage Dashboard, and on the left-hand panel, click on Logs. Here, you can confirm the test was received successfully.

SMS log showing message ID & API Key, from number, to number, network and body (the text sent)SMS log

Conclusion

And, that’s it! You just set up webhooks to manage these communications in real time. Your application can now respond to inbound events as they occur. You can even further expand on this application by following our tutorial on how to add client code for outbound voice calls and outbound SMS and how to make an outbound voice call and send an outbound SMS. If you followed this tutorial for your own projects, we’d love to hear about it! Join the conversation on our Vonage Community Slack or send us a message on X, formerly known as Twitter.

Prashant Agrawal Technical Account Manager

Prashant is a member of the API Partner Sales Team at Vonage. He is based in Singapore. He drives the enablement of customers and partners to leverage Vonage CPaaS capabilities for their businesses. In his spare time, Prashant enjoys cycling the scenic island or sweating out in badminton games.

Ready to start building?

Experience seamless connectivity, real-time messaging, and crystal-clear voice and video calls-all at your fingertips.

Subscribe to Our Developer Newsletter

Subscribe to our monthly newsletter to receive our latest updates on tutorials, releases, and events. No spam.