In this MessageBird Developer Tutorial, you’ll learn how to build an SMS appointment reminder application and improve your users’ experience with the MessageBird SMS Messaging API.
Booking appointments online from a website or mobile app is quick and easy. Customers just have to select their desired date and time, personal details and hit a button. The problem, however, is that easy-to-book appointments are often just as easy to forget.
For appointment-based services, no-shows are annoying and costly because of the time and revenue lost waiting for a customer instead of serving them or another customer. Timely SMS reminders simple and discrete nudges, which can go a long way in the prevention of costly no-shows.
This sample application in build Node.js and represents the order website for our fictitious online beauty salon, BeautyBird. To reduce the growing number of no-shows, BeautyBird now collects appointment bookings through a form on their website and schedules timely SMS reminders to be sent out three hours before the selected date and time.
To look at the full sample application or run it on your computer, go to the MessageBird Developer Tutorials GitHub repository and clone it or download the source code as a ZIP archive.
You’ll need Node and npm, you can easily install them for free.
Open a console pointed at the directory into which you've placed the sample application and run the following command to install the MessageBird SDK for Node.js and other dependencies:
npm install
The SDK is loaded with the following require() statement inindex.js:
// Load and initialize MessageBird SDKvar messagebird = require('messagebird')(process.env.MESSAGEBIRD_API_KEY);
The MessageBird API key needs to be provided as a parameter.
Pro-tip: Hardcoding your credentials in the code is a risky practice that should never be used in production applications. A better method, also recommended by the Twelve-Factor App Definition, is to use environment variables.
We've added dotenv to the sample application so that you can supply your API key in a file named .env as well:
MESSAGEBIRD_API_KEY=YOUR-API-KEY
API keys can be created or retrieved from the API access (REST) tab in the Developers section of the MessageBird Dashboard. There you can create new API keys and manage your existing ones.
If you are having any issues creating your API key, please reach out to support@messagebird.com; we’ll make sure to help you out.
To send SMS messages to users, you need to collect their phone number as part of the booking process. We’ve created a sample form that asks the user for their name, desired treatment, number, date and time. For HTML forms it's recommended to use type="tel" for the phone number input. You can see the template for the complete form in the file views/home.handlebars and the route that drives it’s defined as app.get('/') in index.js.
The user's input is sent to the route app.post('/book') defined in index.js. The implementation covers the following steps:
Validate that the user has entered a value for every field in the form.
Confirm that the date and time are valid and at least three hours and five minutes in the future—BeautyBird won't take bookings on shorter notice. Also, since we want to schedule reminders three hours before the treatment, anything else doesn't make sense from a testing perspective. We recommend you using a library such as moment, which makes working with date and time calculations a breeze. Don't worry; we've already integrated it into our sample application:
// Check if date/time is correct and at least 3:05 hours in the futurevar earliestPossibleDT = moment().add({hours:3, minutes:5});var appointmentDT = moment(req.body.date+" "+req.body.time);if (appointmentDT.isBefore(earliestPossibleDT)) {// If not, show an error// …
Check whether the phone number is correct. This can be done with MessageBird Lookup API, which takes a phone number entered by a user, validates the format and returns information about the number, such as whether it is a mobile or fixed line number. This API doesn't enforce a specific format for the number but rather understands a variety of different variants for writing a phone number, for example using different separator characters between digits gives your users the flexibility to enter their number in various ways. In the SDK, you can call messagebird.lookup.read():
// Check if phone number is validmessagebird.lookup.read(req.body.number, process.env.COUNTRY_CODE, function (err, response) {// …
The function takes three arguments: the phone number, a country code, and a callback function. Providing a default country code enables users to supply their number in a local format without the country code.
To add a country code, add the following line to you .env file, replacing NL with your own ISO country code:
COUNTRY_CODE=NL
In the callback function, we handle four different cases:
if (err && err.errors[0].code == 21) {// This error code indicates that the phone number has an unknown formatres.render('home', {error : "You need to enter a valid phone number!",name : req.body.name,treatment : req.body.treatment,number: req.body.number,date : req.body.date,time : req.body.time});return;} elseif (err) {// Some other error occurredres.render('home', {error : "Something went wrong while checking your phone number!",name : req.body.name,treatment : req.body.treatment,number: req.body.number,date : req.body.date,time : req.body.time});} elseif (response.type != "mobile") {// The number lookup was successful but it is not a mobile numberres.render('home', {error : "You have entered a valid phone number, but it's not a mobile number! Provide a mobile number so we can contact you via SMS.",name : req.body.name,treatment : req.body.treatment,number: req.body.number,date : req.body.date,time : req.body.time});} else {// Everything OK
The implementation for the following steps is contained within the last else block.
Using moment, we can easily specify the time for our reminder:
// Schedule reminder 3 hours prior to the treatmentvar reminderDT = appointmentDT.clone().subtract({hours: 3});
Then it's time to call the MessageBird API:
// Send scheduled message with MessageBird APImessagebird.messages.create({originator : "BeautyBird",recipients : [ response.phoneNumber ], // normalized phone number from lookup requestscheduledDatetime : reminderDT.format(),body : req.body.name + ", here's a reminder that you have a " + req.body.treatment + " scheduled for " + appointmentDT.format('HH:mm') + ". See you soon!"}, function (err, response) {// …
Let's break down the parameters that are set with this call of messagebird.messages.create():
The application's logic continues in the callback function for the messagebird.messages.create() API call, where we need to handle both success and error cases:
}, function (err, response) {if (err) {// Request has failedconsole.log(err);res.send("Error occured while sending message!");} else {// Request was successfulconsole.log(response);// Create and persist appointment objectvar appointment = {name : req.body.name,treatment : req.body.treatment,number: req.body.number,appointmentDT : appointmentDT.format('Y-MM-DD HH:mm'),reminderDT : reminderDT.format('Y-MM-DD HH:mm')}AppointmentDatabase.push(appointment);// Render confirmation pageres.render('confirm', appointment);}});
As you can see, for the purpose of the sample application we simply "persist" the appointment to a global variable in memory. This is where in practical applications you would write the appointment to a persistence layer such as a file or database. We also show a confirmation page, which is defined in views/confirm.handlebars.
You’re done! To test your application, let's run the following command from your console:
node index.js
Then, open http://localhost:8080/ in your browser to see the form and schedule your appointment! If you've used a live API key, a message will arrive at your phone three hours before the appointment! But don't actually leave the house, this is just a demo. 😜
Awesome! You can use the flow, code snippets, and UI examples from this tutorial as an inspiration to build your own SMS reminder system. Don't forget to download the code from the MessageBird Developer Tutorials GitHub repository.
Nice work!🎉 You now have a running SMS appointment reminder application using Node.js!
Want to build something similar but not quite sure how to get started? Feel free to let us know at support@messagebird.com; we'd love to help!