This Express sample application is modeled after the amazing rental experience created by AirBnB, but with more Klingons.
Host users can offer rental properties which other guest users can reserve. The guest and the host can then anonymously communicate via a disposable Twilio phone number created just for a reservation. In this tutorial, we'll show you the key bits of code to make this work.
To run this sample app yourself, download the code and follow the instructions on GitHub.
If you choose to manage communications between your users, including voice calls, text-based messages (e.g., SMS), and chat, you may need to comply with certain laws and regulations, including those regarding obtaining consent. Additional information regarding legal compliance considerations and best practices for using Twilio to manage and record communications between your users, such as when using Twilio Proxy, can be found here.
Notice: Twilio recommends that you consult with your legal counsel to make sure that you are complying with all applicable laws in connection with communications you record or store using Twilio.
Read how Lyft uses masked phone numbers to let customers securely contact drivers.
The first step in connecting a guest and host is creating a reservation. Here we handle a form submission for a new reservation which contains the message and the guest's information which is grabbed from the logged in user.
routes/reservations.js
1var twilio = require('twilio');2var MessagingResponse = require('twilio').twiml.MessagingResponse;3var express = require('express');4var router = express.Router();5var Property = require('../models/property');6var Reservation = require('../models/reservation');7var User = require('../models/user');8var notifier = require('../lib/notifier');9var purchaser = require('../lib/purchaser');10var middleware = require('../lib/middleware');1112router.get('/', middleware.isAuthenticated, function (req, res) {13var userId = req.user.id;14Reservation.find({})15.deepPopulate('property property.owner guest')16.then(function (reservations) {17var hostReservations = reservations.filter(function (reservation) {18return reservation.property.owner.id === userId;19});2021res.render('reservations/index', { reservations: hostReservations, user: req.user });22});23});2425// POST: /reservations26router.post('/', function (req, res) {27var propertyId = req.body.propertyId;28var user = req.user;2930Property.findOne({ _id: propertyId })31.then(function (property) {32var reservation = new Reservation({33message: req.body.message,34property: propertyId,35guest: user.id36});3738return reservation.save();39})40.then(function () {41notifier.sendNotification();42res.redirect('/properties');43})44.catch(function(err) {45console.log(err);46});47});4849// POST: /reservations/handle50router.post('/handle', twilio.webhook({validate: false}), function (req, res) {51var from = req.body.From;52var smsRequest = req.body.Body;5354var smsResponse;5556User.findOne({phoneNumber: from})57.then(function (host) {58return Reservation.findOne({status: 'pending'})59.deepPopulate('property property.owner guest')60})61.then(function (reservation) {62if (reservation === null) {63throw 'No pending reservations';64}6566var hostAreaCode = reservation.property.owner.areaCode;6768var phoneNumber = purchaser.purchase(hostAreaCode);69var reservationPromise = Promise.resolve(reservation);7071return Promise.all([phoneNumber, reservationPromise]);72})73.then(function (data) {74var phoneNumber = data[0];75var reservation = data[1];7677if (isSmsRequestAccepted(smsRequest)) {78reservation.status = "confirmed";79reservation.phoneNumber = phoneNumber;80} else {81reservation.status = "rejected";82}83return reservation.save();84})85.then(function (reservation) {86var message = "You have successfully " + reservation.status + " the reservation";87respond(res, message);88})89.catch(function (err) {90console.log(err);91var message = "Sorry, it looks like you do not have any reservations to respond to";92respond(res, message);93});94});9596var isSmsRequestAccepted = function (smsRequest) {97return smsRequest.toLowerCase() === 'accept';98};99100var respond = function(res, message) {101var messagingResponse = new MessagingResponse();102messagingResponse.message(message);103104res.type('text/xml');105res.send(messagingResponse.toString());106}107108module.exports = router;
Part of our reservation system is receiving reservation requests from potential renters. However, these reservations need to be confirmed. Let's see how we would handle this step.
Before the reservation is finalized, the host needs to confirm that the property was reserved. Learn how to automate this process in our first AirTNG tutorial, Workflow Automation.
routes/reservations.js
1var twilio = require('twilio');2var MessagingResponse = require('twilio').twiml.MessagingResponse;3var express = require('express');4var router = express.Router();5var Property = require('../models/property');6var Reservation = require('../models/reservation');7var User = require('../models/user');8var notifier = require('../lib/notifier');9var purchaser = require('../lib/purchaser');10var middleware = require('../lib/middleware');1112router.get('/', middleware.isAuthenticated, function (req, res) {13var userId = req.user.id;14Reservation.find({})15.deepPopulate('property property.owner guest')16.then(function (reservations) {17var hostReservations = reservations.filter(function (reservation) {18return reservation.property.owner.id === userId;19});2021res.render('reservations/index', { reservations: hostReservations, user: req.user });22});23});2425// POST: /reservations26router.post('/', function (req, res) {27var propertyId = req.body.propertyId;28var user = req.user;2930Property.findOne({ _id: propertyId })31.then(function (property) {32var reservation = new Reservation({33message: req.body.message,34property: propertyId,35guest: user.id36});3738return reservation.save();39})40.then(function () {41notifier.sendNotification();42res.redirect('/properties');43})44.catch(function(err) {45console.log(err);46});47});4849// POST: /reservations/handle50router.post('/handle', twilio.webhook({validate: false}), function (req, res) {51var from = req.body.From;52var smsRequest = req.body.Body;5354var smsResponse;5556User.findOne({phoneNumber: from})57.then(function (host) {58return Reservation.findOne({status: 'pending'})59.deepPopulate('property property.owner guest')60})61.then(function (reservation) {62if (reservation === null) {63throw 'No pending reservations';64}6566var hostAreaCode = reservation.property.owner.areaCode;6768var phoneNumber = purchaser.purchase(hostAreaCode);69var reservationPromise = Promise.resolve(reservation);7071return Promise.all([phoneNumber, reservationPromise]);72})73.then(function (data) {74var phoneNumber = data[0];75var reservation = data[1];7677if (isSmsRequestAccepted(smsRequest)) {78reservation.status = "confirmed";79reservation.phoneNumber = phoneNumber;80} else {81reservation.status = "rejected";82}83return reservation.save();84})85.then(function (reservation) {86var message = "You have successfully " + reservation.status + " the reservation";87respond(res, message);88})89.catch(function (err) {90console.log(err);91var message = "Sorry, it looks like you do not have any reservations to respond to";92respond(res, message);93});94});9596var isSmsRequestAccepted = function (smsRequest) {97return smsRequest.toLowerCase() === 'accept';98};99100var respond = function(res, message) {101var messagingResponse = new MessagingResponse();102messagingResponse.message(message);103104res.type('text/xml');105res.send(messagingResponse.toString());106}107108module.exports = router;
Once the reservation is confirmed, we need to purchase a Twilio number that the guest and host can use to communicate.
Here we use a Twilio Node Helper Library to search for and buy a new phone number to associate with the reservation. When we buy the number, we designate a Twilio Application that will handle webhook requests when the new number receives an incoming call or text.
We then save the new phone number on our reservation
model, so when our app receives calls or texts to this number, we'll know which reservation the call or text belongs to.
lib/purchaser.js
1var config = require('../config');2var client = require('twilio')(config.accountSid, config.authToken);34var purchase = function (areaCode) {5var phoneNumber;67return client.availablePhoneNumbers('US').local.list({8areaCode: areaCode,9voiceEnabled: true,10smsEnabled: true11}).then(function(searchResults) {12if (searchResults.availablePhoneNumbers.length === 0) {13throw { message: 'No numbers found with that area code' };14}1516return client.incomingPhoneNumbers.create({17phoneNumber: searchResults.availablePhoneNumbers[0].phoneNumber,18voiceApplicationSid: config.applicationSid,19smsApplicationSid: config.applicationSid20});21}).then(function(number) {22return number.phone_number;23});24}2526exports.purchase = purchase;
Now that each reservation has a Twilio Phone Number, we can see how the application will look up reservations as guest or host calls come in.
When someone sends an SMS or calls one of the Twilio numbers you have configured, Twilio makes a request to the URL you set in the TwiML app. In this request, Twilio includes some useful information including:
From
number that originally called or sent an SMS.To
Twilio number that triggered this request.Take a look at Twilio's SMS Documentation and Twilio's Voice Documentation for a full list of the parameters you can use.
In our controller we use the to
parameter sent by Twilio to find a reservation that has the number we bought stored in it, as this is the number both hosts and guests will call and send SMS to.
routes/commuter.js
1var twilio = require('twilio');2var VoiceResponse = require('twilio').twiml.VoiceResponse;3var MessagingResponse = require('twilio').twiml.MessagingResponse;4var express = require('express');5var router = express.Router();6var Reservation = require('../models/reservation');78// POST: /commuter/use-sms9router.post('/use-sms', twilio.webhook({ validate: false }), function (req, res) {10from = req.body.From;11to = req.body.To;12body = req.body.Body;1314gatherOutgoingNumber(from, to)15.then(function (outgoingPhoneNumber) {16var messagingResponse = new MessagingResponse();17messagingResponse.message({ to: outgoingPhoneNumber }, body);1819res.type('text/xml');20res.send(messagingResponse.toString());21})22});2324// POST: /commuter/use-voice25router.post('/use-voice', twilio.webhook({ validate: false }), function (req, res) {26from = req.body.From;27to = req.body.To;28body = req.body.Body;2930gatherOutgoingNumber(from, to)31.then(function (outgoingPhoneNumber) {32var voiceResponse = new VoiceResponse();33voiceResponse.play('http://howtodocs.s3.amazonaws.com/howdy-tng.mp3');34voiceResponse.dial(outgoingPhoneNumber);3536res.type('text/xml');37res.send(voiceResponse.toString());38})39});4041var gatherOutgoingNumber = function (incomingPhoneNumber, anonymousPhoneNumber) {42var phoneNumber = anonymousPhoneNumber;4344return Reservation.findOne({ phoneNumber: phoneNumber })45.deepPopulate('property property.owner guest')46.then(function (reservation) {47var hostPhoneNumber = formattedPhoneNumber(reservation.property.owner);48var guestPhoneNumber = formattedPhoneNumber(reservation.guest);4950// Connect from Guest to Host51if (guestPhoneNumber === incomingPhoneNumber) {52outgoingPhoneNumber = hostPhoneNumber;53}5455// Connect from Host to Guest56if (hostPhoneNumber === incomingPhoneNumber) {57outgoingPhoneNumber = guestPhoneNumber;58}5960return outgoingPhoneNumber;61})62.catch(function (err) {63console.log(err);64});65}6667var formattedPhoneNumber = function(user) {68return "+" + user.countryCode + user.areaCode + user.phoneNumber;69};7071module.exports = router;
Next, let's see how to connect the guest and the host via SMS.
Our Twilio application should be configured to send HTTP requests to this controller method on any incoming text message. Our app responds with TwiML to tell Twilio what to do in response to the message.
If the initial message sent to the anonymous number was sent by the host, we forward it on to the guest. Conversely, if the original message was sent by the guest, we forward it to the host.
To find the outgoing number we'll use the gatherOutgoingNumber
helper method.
routes/commuter.js
1var twilio = require('twilio');2var VoiceResponse = require('twilio').twiml.VoiceResponse;3var MessagingResponse = require('twilio').twiml.MessagingResponse;4var express = require('express');5var router = express.Router();6var Reservation = require('../models/reservation');78// POST: /commuter/use-sms9router.post('/use-sms', twilio.webhook({ validate: false }), function (req, res) {10from = req.body.From;11to = req.body.To;12body = req.body.Body;1314gatherOutgoingNumber(from, to)15.then(function (outgoingPhoneNumber) {16var messagingResponse = new MessagingResponse();17messagingResponse.message({ to: outgoingPhoneNumber }, body);1819res.type('text/xml');20res.send(messagingResponse.toString());21})22});2324// POST: /commuter/use-voice25router.post('/use-voice', twilio.webhook({ validate: false }), function (req, res) {26from = req.body.From;27to = req.body.To;28body = req.body.Body;2930gatherOutgoingNumber(from, to)31.then(function (outgoingPhoneNumber) {32var voiceResponse = new VoiceResponse();33voiceResponse.play('http://howtodocs.s3.amazonaws.com/howdy-tng.mp3');34voiceResponse.dial(outgoingPhoneNumber);3536res.type('text/xml');37res.send(voiceResponse.toString());38})39});4041var gatherOutgoingNumber = function (incomingPhoneNumber, anonymousPhoneNumber) {42var phoneNumber = anonymousPhoneNumber;4344return Reservation.findOne({ phoneNumber: phoneNumber })45.deepPopulate('property property.owner guest')46.then(function (reservation) {47var hostPhoneNumber = formattedPhoneNumber(reservation.property.owner);48var guestPhoneNumber = formattedPhoneNumber(reservation.guest);4950// Connect from Guest to Host51if (guestPhoneNumber === incomingPhoneNumber) {52outgoingPhoneNumber = hostPhoneNumber;53}5455// Connect from Host to Guest56if (hostPhoneNumber === incomingPhoneNumber) {57outgoingPhoneNumber = guestPhoneNumber;58}5960return outgoingPhoneNumber;61})62.catch(function (err) {63console.log(err);64});65}6667var formattedPhoneNumber = function(user) {68return "+" + user.countryCode + user.areaCode + user.phoneNumber;69};7071module.exports = router;
Let's see how to connect the guest and the host via phone call next.
That's it! We've just implemented anonymous communications that allow your customers to connect while protecting their privacy.
If you're a Node.js developer working with Twilio, you might want to check out these other tutorials:
You can route callers to the right people and information with an IVR (interactive voice response) system.
Instantly collect structured data from your users with a survey conducted over a voice call or SMS text messages. Learn how to create your own survey in the language and framework of your choice.
Thanks for checking out this tutorial! If you have any feedback to share with us, we'd love to hear it. Tweet @twilio to let us know what you think.