DEV Community

Cover image for Build A Product Rating Service Using Twilio SMS Webhooks
Oluwatobi for Hookdeck

Posted on • Edited on • Originally published at hookdeck.com

Build A Product Rating Service Using Twilio SMS Webhooks

Twilio APIs have a wide range of uses! In this article, we will see how to build a simple product rating service using Twilio’s SMS webhooks. The service we are building is for an imaginary company Sweetburger, that sells tasty burgers. Sweetburger sends an SMS message to their customers asking for a review of the burger they purchased and expects a response SMS from their customers. For this use case, we would be using NodeJS & the ExpressJS framework along with Twilio’s SMS API webhooks.

Getting Started

The above Image is a rough sketch of the demo service we would be building, to get started we need to send an SMS message to the customer using Twilio’s SMS API.

Sending An SMS Message

In this section, we would wire up the logic to send the first SMS message to the customer. To get started, add the following lines of code below

    const accountSid = process.env.TWILIO_ACCOUNT_SID;
    const authToken = process.env.TWILIO_AUTH_TOKEN;
    const client = require("twilio")(accountSid, authToken);
    client.messages
      .create({
        body:
          "Hey, Thank you for purchasing a SweetBurger! Please leave a review by replying what you think about the burger on a scale of 1-5",
        from: "Your Twilio Number",
        to: "Customers Number",
      })
      .then((message) => console.log(message.sid));
Enter fullscreen mode Exit fullscreen mode

The above code snippet sends the first SMS to the customer requesting a review! You can get the Twilio phone number, account SID & authentication token from the Twilio console.

Create an HTTP endpoint to receive the webhooks & conditionally respond to incoming SMS

The next step is to wire up an HTTP endpoint that would receive webhook notifications when a customer replies to the SMS and rates a burger.

    const express = require("express");
    const app = express();
    const bodyParser = require("body-parser");
    const MessagingResponse = require("twilio").twiml.MessagingResponse;
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.post("/webhook", async (req, res) => {
      const twiml = new MessagingResponse();
      const rating = parseInt(payload.body);
      if (rating === 5) {
        twiml.message("We are glad you enjoyed SweetBurger! Thank You");
      } else if (rating === 1) {
        twiml.message("We are sorry to see you didn’t enjoy your SweetBurger! Thank You");
      } else if (rating <= 0 || rating > 5) {
        twiml.message("oooops! This is not a valid burger rating");
      }
      res.writeHead(200, { "Content-Type": "text/xml" });
      res.end(twiml.toString());
    });
    app.listen(3000, () => console.log("App is running on port 3000!"));
Enter fullscreen mode Exit fullscreen mode

As seen in the above code snippet, we have wired up the logic to conditionally respond to ratings customers give our burger using the switch statement. We use the Twilio SDK to automatically generate TwiML which is the response format required by Twilio.

Register A Webhook On Twilio

Although we have set up our logic for responding to incoming SMS messages locally, we have to wire it up such that we get webhook notifications. Twilio requires we provide an SSL secure HTTPS endpoint — To learn more about working with Twilio webhooks, check our guide. Since this is just a demo application, we could use a tool like Ngrok to expose our local server publicly(Here’s a guide we wrote that shows how to setup Ngrok).
Next, head over to the phone number tab on the Twilio console, scroll to the messaging section, and change the “configure with” fields value to Webhooks. Next, input your Ngrok URL into the “A message Comes In” field.

Once the service is ready for deployment, going to production has its challenges specifically with webhooks. Missing one or failing to receive a rating has consequences.
we've built Hookdeck to help developers instantly manage webhook integrations in production reliably. Check out this guide we wrote to help you get started with creating webhook connections on Hookdeck

Conclusion

Congratulations! We have leveraged Twilio Webhooks to build a simple rating service that responds to SMS messages conditionally.

Interested to learn more? Follow Hookdeck where I'll be sharing tutorials and guide about webhooks!
Try Hookdeck For Free. Receive, monitor and manage all your webhooks from a single place. We handle the complexity so you can focus on building your product.

Top comments (0)