This PHP Laravel 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 guest's name and phone number.
app/Http/Controllers/ReservationController.php
1<?php2namespace App\Http\Controllers;3use Illuminate\Http\Request;4use App\Http\Requests;5use App\Http\Controllers\Controller;6use Illuminate\Contracts\Auth\Authenticatable;7use App\Reservation;8use App\User;9use App\VacationProperty;10use DB;11use Twilio\Rest\Client;12use Twilio\Twiml;13use Log;1415class ReservationController extends Controller16{17public function index(Authenticatable $user)18{19$reservations = array();2021foreach ($user->propertyReservations as $reservation)22{23array_push($reservations, $reservation->fresh());24}25return view(26'reservation.index',27[28'hostReservations' => $reservations,29'guestReservations' => $user->reservations30]31);32}3334/**35* Store a new reservation36*37* @param \Illuminate\Http\Request $request38* @return \Illuminate\Http\Response39*/40public function create(Client $client, Request $request, Authenticatable $user, $id)41{42$this->validate(43$request, [44'message' => 'required|string'45]46);47$property = VacationProperty::find($id);48$reservation = new Reservation($request->all());4950$reservation->user()->associate($user);5152$property->reservations()->save($reservation);5354$this->notifyHost($client, $reservation);5556$request->session()->flash(57'status',58"Sending your reservation request now."59);60return redirect()->route('reservation-index', ['id' => $property->id]);61}6263public function acceptReject(Client $client, Request $request)64{65$hostNumber = $request->input('From');66$smsInput = strtolower($request->input('Body'));67$host = User::where(DB::raw("CONCAT('+',country_code::text, phone_number::text)"), 'LIKE', "%".$hostNumber."%")68->get()69->first();7071$reservation = $host->pendingReservations()->first();72$smsResponse = null;73if (!is_null($reservation))74{75$reservation = $reservation->fresh();7677if (strpos($smsInput, 'yes') !== false || strpos($smsInput, 'accept') !== false)78{79$reservation->confirm($this->getNewTwilioNumber($client, $host));80}81else82{83$reservation->reject();84}8586$smsResponse = 'You have successfully ' . $reservation->status . ' the reservation.';87}88else89{90$smsResponse = 'Sorry, it looks like you don\'t have any reservations to respond to.';91}9293return response($this->respond($smsResponse, $reservation))->header('Content-Type', 'application/xml');94}9596public function connectSms(Request $request)97{98$twilioNumber = $request->input('To');99$incomingNumber = $request->input('From');100$messageBody = $request->input('Body');101102$reservation = $this->getReservationFromNumber($twilioNumber);103$host = $reservation->property->user;104$guest = $reservation->user;105106if ($incomingNumber === $host->fullNumber())107{108$outgoingNumber = $guest->fullNumber();109}110else111{112$outgoingNumber = $host->fullNumber();113}114115return response($this->connectSmsResponse($messageBody, $outgoingNumber))->header('Content-Type', 'application/xml');116}117118public function connectVoice(Request $request)119{120$twilioNumber = $request->input('To');121$incomingNumber = $request->input('From');122123$reservation = $this->getReservationFromNumber($twilioNumber);124$host = $reservation->property->user;125$guest = $reservation->user;126127if ($incomingNumber === $host->fullNumber())128{129$outgoingNumber = $guest->fullNumber();130}131else132{133$outgoingNumber = $host->fullNumber();134}135136return response($this->connectVoiceResponse($outgoingNumber))->header('Content-Type', 'application/xml');137}138139private function getReservationFromNumber($twilioNumber)140{141return Reservation::where('twilio_number', '=', $twilioNumber)->first();142}143144private function connectVoiceResponse($outgoingNumber)145{146$response = new Twiml();147$response->play('http://howtodocs.s3.amazonaws.com/howdy-tng.mp3');148$response->dial($outgoingNumber);149150return $response;151}152153private function connectSmsResponse($messageBody, $outgoingNumber)154{155$response = new Twiml();156$response->message(157$messageBody,158['to' => $outgoingNumber]159);160161return $response;162}163164private function respond($smsResponse, $reservation)165{166$response = new Twiml();167$response->message($smsResponse);168169if (!is_null($reservation))170{171$response->message(172'Your reservation has been ' . $reservation->status . '.',173['to' => $reservation->user->fullNumber()]174);175}176return $response;177}178179private function notifyHost($client, $reservation)180{181$host = $reservation->property->user;182183$twilioNumber = config('services.twilio')['number'];184185$messageBody = $reservation->message . ' - Reply \'yes\' or \'accept\' to confirm the reservation, or anything else to reject it.';186187try {188$client->messages->create(189$host->fullNumber(), // Text any number190[191'from' => $twilioNumber, // From a Twilio number in your account192'body' => $messageBody193]194);195} catch (Exception $e) {196Log::error($e->getMessage());197}198}199200private function getNewTwilioNumber($client, $host)201{202$numbers = $client->availablePhoneNumbers('US')->local->read(203[204'areaCode' => $host->areaCode(),205'voiceEnabled' => 'true',206"smsEnabled" => 'true'207]208);209210if (empty($numbers)) {211$numbers = $client->availablePhoneNumbers('US')->local->read(212[213'voiceEnabled' => 'true',214"smsEnabled" => 'true'215]216);217}218$twilioNumber = $numbers[0]->phoneNumber;219220$newNumber = $client->incomingPhoneNumbers->create(221[222"phoneNumber" => $twilioNumber,223"smsApplicationSid" => config('services.twilio')['applicationSid'],224"voiceApplicationSid" => config('services.twilio')['applicationSid']225]226);227228if ($newNumber) {229return $twilioNumber;230} else {231return 0;232}233}234}
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 is still available. Learn how to automate this process in our first AirTNG tutorial, Workflow Automation.
Once the reservation is confirmed, we need to create a Twilio number that the guest and host can use to communicate in the getNewTwilioNumber
method.
app/Http/Controllers/ReservationController.php
1<?php2namespace App\Http\Controllers;3use Illuminate\Http\Request;4use App\Http\Requests;5use App\Http\Controllers\Controller;6use Illuminate\Contracts\Auth\Authenticatable;7use App\Reservation;8use App\User;9use App\VacationProperty;10use DB;11use Twilio\Rest\Client;12use Twilio\Twiml;13use Log;1415class ReservationController extends Controller16{17public function index(Authenticatable $user)18{19$reservations = array();2021foreach ($user->propertyReservations as $reservation)22{23array_push($reservations, $reservation->fresh());24}25return view(26'reservation.index',27[28'hostReservations' => $reservations,29'guestReservations' => $user->reservations30]31);32}3334/**35* Store a new reservation36*37* @param \Illuminate\Http\Request $request38* @return \Illuminate\Http\Response39*/40public function create(Client $client, Request $request, Authenticatable $user, $id)41{42$this->validate(43$request, [44'message' => 'required|string'45]46);47$property = VacationProperty::find($id);48$reservation = new Reservation($request->all());4950$reservation->user()->associate($user);5152$property->reservations()->save($reservation);5354$this->notifyHost($client, $reservation);5556$request->session()->flash(57'status',58"Sending your reservation request now."59);60return redirect()->route('reservation-index', ['id' => $property->id]);61}6263public function acceptReject(Client $client, Request $request)64{65$hostNumber = $request->input('From');66$smsInput = strtolower($request->input('Body'));67$host = User::where(DB::raw("CONCAT('+',country_code::text, phone_number::text)"), 'LIKE', "%".$hostNumber."%")68->get()69->first();7071$reservation = $host->pendingReservations()->first();72$smsResponse = null;73if (!is_null($reservation))74{75$reservation = $reservation->fresh();7677if (strpos($smsInput, 'yes') !== false || strpos($smsInput, 'accept') !== false)78{79$reservation->confirm($this->getNewTwilioNumber($client, $host));80}81else82{83$reservation->reject();84}8586$smsResponse = 'You have successfully ' . $reservation->status . ' the reservation.';87}88else89{90$smsResponse = 'Sorry, it looks like you don\'t have any reservations to respond to.';91}9293return response($this->respond($smsResponse, $reservation))->header('Content-Type', 'application/xml');94}9596public function connectSms(Request $request)97{98$twilioNumber = $request->input('To');99$incomingNumber = $request->input('From');100$messageBody = $request->input('Body');101102$reservation = $this->getReservationFromNumber($twilioNumber);103$host = $reservation->property->user;104$guest = $reservation->user;105106if ($incomingNumber === $host->fullNumber())107{108$outgoingNumber = $guest->fullNumber();109}110else111{112$outgoingNumber = $host->fullNumber();113}114115return response($this->connectSmsResponse($messageBody, $outgoingNumber))->header('Content-Type', 'application/xml');116}117118public function connectVoice(Request $request)119{120$twilioNumber = $request->input('To');121$incomingNumber = $request->input('From');122123$reservation = $this->getReservationFromNumber($twilioNumber);124$host = $reservation->property->user;125$guest = $reservation->user;126127if ($incomingNumber === $host->fullNumber())128{129$outgoingNumber = $guest->fullNumber();130}131else132{133$outgoingNumber = $host->fullNumber();134}135136return response($this->connectVoiceResponse($outgoingNumber))->header('Content-Type', 'application/xml');137}138139private function getReservationFromNumber($twilioNumber)140{141return Reservation::where('twilio_number', '=', $twilioNumber)->first();142}143144private function connectVoiceResponse($outgoingNumber)145{146$response = new Twiml();147$response->play('http://howtodocs.s3.amazonaws.com/howdy-tng.mp3');148$response->dial($outgoingNumber);149150return $response;151}152153private function connectSmsResponse($messageBody, $outgoingNumber)154{155$response = new Twiml();156$response->message(157$messageBody,158['to' => $outgoingNumber]159);160161return $response;162}163164private function respond($smsResponse, $reservation)165{166$response = new Twiml();167$response->message($smsResponse);168169if (!is_null($reservation))170{171$response->message(172'Your reservation has been ' . $reservation->status . '.',173['to' => $reservation->user->fullNumber()]174);175}176return $response;177}178179private function notifyHost($client, $reservation)180{181$host = $reservation->property->user;182183$twilioNumber = config('services.twilio')['number'];184185$messageBody = $reservation->message . ' - Reply \'yes\' or \'accept\' to confirm the reservation, or anything else to reject it.';186187try {188$client->messages->create(189$host->fullNumber(), // Text any number190[191'from' => $twilioNumber, // From a Twilio number in your account192'body' => $messageBody193]194);195} catch (Exception $e) {196Log::error($e->getMessage());197}198}199200private function getNewTwilioNumber($client, $host)201{202$numbers = $client->availablePhoneNumbers('US')->local->read(203[204'areaCode' => $host->areaCode(),205'voiceEnabled' => 'true',206"smsEnabled" => 'true'207]208);209210if (empty($numbers)) {211$numbers = $client->availablePhoneNumbers('US')->local->read(212[213'voiceEnabled' => 'true',214"smsEnabled" => 'true'215]216);217}218$twilioNumber = $numbers[0]->phoneNumber;219220$newNumber = $client->incomingPhoneNumbers->create(221[222"phoneNumber" => $twilioNumber,223"smsApplicationSid" => config('services.twilio')['applicationSid'],224"voiceApplicationSid" => config('services.twilio')['applicationSid']225]226);227228if ($newNumber) {229return $twilioNumber;230} else {231return 0;232}233}234}
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 REST API Client 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.
app/Http/Controllers/ReservationController.php
1<?php2namespace App\Http\Controllers;3use Illuminate\Http\Request;4use App\Http\Requests;5use App\Http\Controllers\Controller;6use Illuminate\Contracts\Auth\Authenticatable;7use App\Reservation;8use App\User;9use App\VacationProperty;10use DB;11use Twilio\Rest\Client;12use Twilio\Twiml;13use Log;1415class ReservationController extends Controller16{17public function index(Authenticatable $user)18{19$reservations = array();2021foreach ($user->propertyReservations as $reservation)22{23array_push($reservations, $reservation->fresh());24}25return view(26'reservation.index',27[28'hostReservations' => $reservations,29'guestReservations' => $user->reservations30]31);32}3334/**35* Store a new reservation36*37* @param \Illuminate\Http\Request $request38* @return \Illuminate\Http\Response39*/40public function create(Client $client, Request $request, Authenticatable $user, $id)41{42$this->validate(43$request, [44'message' => 'required|string'45]46);47$property = VacationProperty::find($id);48$reservation = new Reservation($request->all());4950$reservation->user()->associate($user);5152$property->reservations()->save($reservation);5354$this->notifyHost($client, $reservation);5556$request->session()->flash(57'status',58"Sending your reservation request now."59);60return redirect()->route('reservation-index', ['id' => $property->id]);61}6263public function acceptReject(Client $client, Request $request)64{65$hostNumber = $request->input('From');66$smsInput = strtolower($request->input('Body'));67$host = User::where(DB::raw("CONCAT('+',country_code::text, phone_number::text)"), 'LIKE', "%".$hostNumber."%")68->get()69->first();7071$reservation = $host->pendingReservations()->first();72$smsResponse = null;73if (!is_null($reservation))74{75$reservation = $reservation->fresh();7677if (strpos($smsInput, 'yes') !== false || strpos($smsInput, 'accept') !== false)78{79$reservation->confirm($this->getNewTwilioNumber($client, $host));80}81else82{83$reservation->reject();84}8586$smsResponse = 'You have successfully ' . $reservation->status . ' the reservation.';87}88else89{90$smsResponse = 'Sorry, it looks like you don\'t have any reservations to respond to.';91}9293return response($this->respond($smsResponse, $reservation))->header('Content-Type', 'application/xml');94}9596public function connectSms(Request $request)97{98$twilioNumber = $request->input('To');99$incomingNumber = $request->input('From');100$messageBody = $request->input('Body');101102$reservation = $this->getReservationFromNumber($twilioNumber);103$host = $reservation->property->user;104$guest = $reservation->user;105106if ($incomingNumber === $host->fullNumber())107{108$outgoingNumber = $guest->fullNumber();109}110else111{112$outgoingNumber = $host->fullNumber();113}114115return response($this->connectSmsResponse($messageBody, $outgoingNumber))->header('Content-Type', 'application/xml');116}117118public function connectVoice(Request $request)119{120$twilioNumber = $request->input('To');121$incomingNumber = $request->input('From');122123$reservation = $this->getReservationFromNumber($twilioNumber);124$host = $reservation->property->user;125$guest = $reservation->user;126127if ($incomingNumber === $host->fullNumber())128{129$outgoingNumber = $guest->fullNumber();130}131else132{133$outgoingNumber = $host->fullNumber();134}135136return response($this->connectVoiceResponse($outgoingNumber))->header('Content-Type', 'application/xml');137}138139private function getReservationFromNumber($twilioNumber)140{141return Reservation::where('twilio_number', '=', $twilioNumber)->first();142}143144private function connectVoiceResponse($outgoingNumber)145{146$response = new Twiml();147$response->play('http://howtodocs.s3.amazonaws.com/howdy-tng.mp3');148$response->dial($outgoingNumber);149150return $response;151}152153private function connectSmsResponse($messageBody, $outgoingNumber)154{155$response = new Twiml();156$response->message(157$messageBody,158['to' => $outgoingNumber]159);160161return $response;162}163164private function respond($smsResponse, $reservation)165{166$response = new Twiml();167$response->message($smsResponse);168169if (!is_null($reservation))170{171$response->message(172'Your reservation has been ' . $reservation->status . '.',173['to' => $reservation->user->fullNumber()]174);175}176return $response;177}178179private function notifyHost($client, $reservation)180{181$host = $reservation->property->user;182183$twilioNumber = config('services.twilio')['number'];184185$messageBody = $reservation->message . ' - Reply \'yes\' or \'accept\' to confirm the reservation, or anything else to reject it.';186187try {188$client->messages->create(189$host->fullNumber(), // Text any number190[191'from' => $twilioNumber, // From a Twilio number in your account192'body' => $messageBody193]194);195} catch (Exception $e) {196Log::error($e->getMessage());197}198}199200private function getNewTwilioNumber($client, $host)201{202$numbers = $client->availablePhoneNumbers('US')->local->read(203[204'areaCode' => $host->areaCode(),205'voiceEnabled' => 'true',206"smsEnabled" => 'true'207]208);209210if (empty($numbers)) {211$numbers = $client->availablePhoneNumbers('US')->local->read(212[213'voiceEnabled' => 'true',214"smsEnabled" => 'true'215]216);217}218$twilioNumber = $numbers[0]->phoneNumber;219220$newNumber = $client->incomingPhoneNumbers->create(221[222"phoneNumber" => $twilioNumber,223"smsApplicationSid" => config('services.twilio')['applicationSid'],224"voiceApplicationSid" => config('services.twilio')['applicationSid']225]226);227228if ($newNumber) {229return $twilioNumber;230} else {231return 0;232}233}234}
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 SMSTo
Twilio number that triggered this requestTake 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.
app/Http/Controllers/ReservationController.php
1<?php2namespace App\Http\Controllers;3use Illuminate\Http\Request;4use App\Http\Requests;5use App\Http\Controllers\Controller;6use Illuminate\Contracts\Auth\Authenticatable;7use App\Reservation;8use App\User;9use App\VacationProperty;10use DB;11use Twilio\Rest\Client;12use Twilio\Twiml;13use Log;1415class ReservationController extends Controller16{17public function index(Authenticatable $user)18{19$reservations = array();2021foreach ($user->propertyReservations as $reservation)22{23array_push($reservations, $reservation->fresh());24}25return view(26'reservation.index',27[28'hostReservations' => $reservations,29'guestReservations' => $user->reservations30]31);32}3334/**35* Store a new reservation36*37* @param \Illuminate\Http\Request $request38* @return \Illuminate\Http\Response39*/40public function create(Client $client, Request $request, Authenticatable $user, $id)41{42$this->validate(43$request, [44'message' => 'required|string'45]46);47$property = VacationProperty::find($id);48$reservation = new Reservation($request->all());4950$reservation->user()->associate($user);5152$property->reservations()->save($reservation);5354$this->notifyHost($client, $reservation);5556$request->session()->flash(57'status',58"Sending your reservation request now."59);60return redirect()->route('reservation-index', ['id' => $property->id]);61}6263public function acceptReject(Client $client, Request $request)64{65$hostNumber = $request->input('From');66$smsInput = strtolower($request->input('Body'));67$host = User::where(DB::raw("CONCAT('+',country_code::text, phone_number::text)"), 'LIKE', "%".$hostNumber."%")68->get()69->first();7071$reservation = $host->pendingReservations()->first();72$smsResponse = null;73if (!is_null($reservation))74{75$reservation = $reservation->fresh();7677if (strpos($smsInput, 'yes') !== false || strpos($smsInput, 'accept') !== false)78{79$reservation->confirm($this->getNewTwilioNumber($client, $host));80}81else82{83$reservation->reject();84}8586$smsResponse = 'You have successfully ' . $reservation->status . ' the reservation.';87}88else89{90$smsResponse = 'Sorry, it looks like you don\'t have any reservations to respond to.';91}9293return response($this->respond($smsResponse, $reservation))->header('Content-Type', 'application/xml');94}9596public function connectSms(Request $request)97{98$twilioNumber = $request->input('To');99$incomingNumber = $request->input('From');100$messageBody = $request->input('Body');101102$reservation = $this->getReservationFromNumber($twilioNumber);103$host = $reservation->property->user;104$guest = $reservation->user;105106if ($incomingNumber === $host->fullNumber())107{108$outgoingNumber = $guest->fullNumber();109}110else111{112$outgoingNumber = $host->fullNumber();113}114115return response($this->connectSmsResponse($messageBody, $outgoingNumber))->header('Content-Type', 'application/xml');116}117118public function connectVoice(Request $request)119{120$twilioNumber = $request->input('To');121$incomingNumber = $request->input('From');122123$reservation = $this->getReservationFromNumber($twilioNumber);124$host = $reservation->property->user;125$guest = $reservation->user;126127if ($incomingNumber === $host->fullNumber())128{129$outgoingNumber = $guest->fullNumber();130}131else132{133$outgoingNumber = $host->fullNumber();134}135136return response($this->connectVoiceResponse($outgoingNumber))->header('Content-Type', 'application/xml');137}138139private function getReservationFromNumber($twilioNumber)140{141return Reservation::where('twilio_number', '=', $twilioNumber)->first();142}143144private function connectVoiceResponse($outgoingNumber)145{146$response = new Twiml();147$response->play('http://howtodocs.s3.amazonaws.com/howdy-tng.mp3');148$response->dial($outgoingNumber);149150return $response;151}152153private function connectSmsResponse($messageBody, $outgoingNumber)154{155$response = new Twiml();156$response->message(157$messageBody,158['to' => $outgoingNumber]159);160161return $response;162}163164private function respond($smsResponse, $reservation)165{166$response = new Twiml();167$response->message($smsResponse);168169if (!is_null($reservation))170{171$response->message(172'Your reservation has been ' . $reservation->status . '.',173['to' => $reservation->user->fullNumber()]174);175}176return $response;177}178179private function notifyHost($client, $reservation)180{181$host = $reservation->property->user;182183$twilioNumber = config('services.twilio')['number'];184185$messageBody = $reservation->message . ' - Reply \'yes\' or \'accept\' to confirm the reservation, or anything else to reject it.';186187try {188$client->messages->create(189$host->fullNumber(), // Text any number190[191'from' => $twilioNumber, // From a Twilio number in your account192'body' => $messageBody193]194);195} catch (Exception $e) {196Log::error($e->getMessage());197}198}199200private function getNewTwilioNumber($client, $host)201{202$numbers = $client->availablePhoneNumbers('US')->local->read(203[204'areaCode' => $host->areaCode(),205'voiceEnabled' => 'true',206"smsEnabled" => 'true'207]208);209210if (empty($numbers)) {211$numbers = $client->availablePhoneNumbers('US')->local->read(212[213'voiceEnabled' => 'true',214"smsEnabled" => 'true'215]216);217}218$twilioNumber = $numbers[0]->phoneNumber;219220$newNumber = $client->incomingPhoneNumbers->create(221[222"phoneNumber" => $twilioNumber,223"smsApplicationSid" => config('services.twilio')['applicationSid'],224"voiceApplicationSid" => config('services.twilio')['applicationSid']225]226);227228if ($newNumber) {229return $twilioNumber;230} else {231return 0;232}233}234}
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.
app/Http/Controllers/ReservationController.php
1<?php2namespace App\Http\Controllers;3use Illuminate\Http\Request;4use App\Http\Requests;5use App\Http\Controllers\Controller;6use Illuminate\Contracts\Auth\Authenticatable;7use App\Reservation;8use App\User;9use App\VacationProperty;10use DB;11use Twilio\Rest\Client;12use Twilio\Twiml;13use Log;1415class ReservationController extends Controller16{17public function index(Authenticatable $user)18{19$reservations = array();2021foreach ($user->propertyReservations as $reservation)22{23array_push($reservations, $reservation->fresh());24}25return view(26'reservation.index',27[28'hostReservations' => $reservations,29'guestReservations' => $user->reservations30]31);32}3334/**35* Store a new reservation36*37* @param \Illuminate\Http\Request $request38* @return \Illuminate\Http\Response39*/40public function create(Client $client, Request $request, Authenticatable $user, $id)41{42$this->validate(43$request, [44'message' => 'required|string'45]46);47$property = VacationProperty::find($id);48$reservation = new Reservation($request->all());4950$reservation->user()->associate($user);5152$property->reservations()->save($reservation);5354$this->notifyHost($client, $reservation);5556$request->session()->flash(57'status',58"Sending your reservation request now."59);60return redirect()->route('reservation-index', ['id' => $property->id]);61}6263public function acceptReject(Client $client, Request $request)64{65$hostNumber = $request->input('From');66$smsInput = strtolower($request->input('Body'));67$host = User::where(DB::raw("CONCAT('+',country_code::text, phone_number::text)"), 'LIKE', "%".$hostNumber."%")68->get()69->first();7071$reservation = $host->pendingReservations()->first();72$smsResponse = null;73if (!is_null($reservation))74{75$reservation = $reservation->fresh();7677if (strpos($smsInput, 'yes') !== false || strpos($smsInput, 'accept') !== false)78{79$reservation->confirm($this->getNewTwilioNumber($client, $host));80}81else82{83$reservation->reject();84}8586$smsResponse = 'You have successfully ' . $reservation->status . ' the reservation.';87}88else89{90$smsResponse = 'Sorry, it looks like you don\'t have any reservations to respond to.';91}9293return response($this->respond($smsResponse, $reservation))->header('Content-Type', 'application/xml');94}9596public function connectSms(Request $request)97{98$twilioNumber = $request->input('To');99$incomingNumber = $request->input('From');100$messageBody = $request->input('Body');101102$reservation = $this->getReservationFromNumber($twilioNumber);103$host = $reservation->property->user;104$guest = $reservation->user;105106if ($incomingNumber === $host->fullNumber())107{108$outgoingNumber = $guest->fullNumber();109}110else111{112$outgoingNumber = $host->fullNumber();113}114115return response($this->connectSmsResponse($messageBody, $outgoingNumber))->header('Content-Type', 'application/xml');116}117118public function connectVoice(Request $request)119{120$twilioNumber = $request->input('To');121$incomingNumber = $request->input('From');122123$reservation = $this->getReservationFromNumber($twilioNumber);124$host = $reservation->property->user;125$guest = $reservation->user;126127if ($incomingNumber === $host->fullNumber())128{129$outgoingNumber = $guest->fullNumber();130}131else132{133$outgoingNumber = $host->fullNumber();134}135136return response($this->connectVoiceResponse($outgoingNumber))->header('Content-Type', 'application/xml');137}138139private function getReservationFromNumber($twilioNumber)140{141return Reservation::where('twilio_number', '=', $twilioNumber)->first();142}143144private function connectVoiceResponse($outgoingNumber)145{146$response = new Twiml();147$response->play('http://howtodocs.s3.amazonaws.com/howdy-tng.mp3');148$response->dial($outgoingNumber);149150return $response;151}152153private function connectSmsResponse($messageBody, $outgoingNumber)154{155$response = new Twiml();156$response->message(157$messageBody,158['to' => $outgoingNumber]159);160161return $response;162}163164private function respond($smsResponse, $reservation)165{166$response = new Twiml();167$response->message($smsResponse);168169if (!is_null($reservation))170{171$response->message(172'Your reservation has been ' . $reservation->status . '.',173['to' => $reservation->user->fullNumber()]174);175}176return $response;177}178179private function notifyHost($client, $reservation)180{181$host = $reservation->property->user;182183$twilioNumber = config('services.twilio')['number'];184185$messageBody = $reservation->message . ' - Reply \'yes\' or \'accept\' to confirm the reservation, or anything else to reject it.';186187try {188$client->messages->create(189$host->fullNumber(), // Text any number190[191'from' => $twilioNumber, // From a Twilio number in your account192'body' => $messageBody193]194);195} catch (Exception $e) {196Log::error($e->getMessage());197}198}199200private function getNewTwilioNumber($client, $host)201{202$numbers = $client->availablePhoneNumbers('US')->local->read(203[204'areaCode' => $host->areaCode(),205'voiceEnabled' => 'true',206"smsEnabled" => 'true'207]208);209210if (empty($numbers)) {211$numbers = $client->availablePhoneNumbers('US')->local->read(212[213'voiceEnabled' => 'true',214"smsEnabled" => 'true'215]216);217}218$twilioNumber = $numbers[0]->phoneNumber;219220$newNumber = $client->incomingPhoneNumbers->create(221[222"phoneNumber" => $twilioNumber,223"smsApplicationSid" => config('services.twilio')['applicationSid'],224"voiceApplicationSid" => config('services.twilio')['applicationSid']225]226);227228if ($newNumber) {229return $twilioNumber;230} else {231return 0;232}233}234}
Let's see how to connect the guest and the host via phone call next.
Our Twilio application will send HTTP requests to this method on any incoming voice call. Our app responds with TwiML instructions that tell Twilio to Play
an introductory MP3 audio file and thenDial
either the guest or host, depending on who initiated the call.
app/Http/Controllers/ReservationController.php
1<?php2namespace App\Http\Controllers;3use Illuminate\Http\Request;4use App\Http\Requests;5use App\Http\Controllers\Controller;6use Illuminate\Contracts\Auth\Authenticatable;7use App\Reservation;8use App\User;9use App\VacationProperty;10use DB;11use Twilio\Rest\Client;12use Twilio\Twiml;13use Log;1415class ReservationController extends Controller16{17public function index(Authenticatable $user)18{19$reservations = array();2021foreach ($user->propertyReservations as $reservation)22{23array_push($reservations, $reservation->fresh());24}25return view(26'reservation.index',27[28'hostReservations' => $reservations,29'guestReservations' => $user->reservations30]31);32}3334/**35* Store a new reservation36*37* @param \Illuminate\Http\Request $request38* @return \Illuminate\Http\Response39*/40public function create(Client $client, Request $request, Authenticatable $user, $id)41{42$this->validate(43$request, [44'message' => 'required|string'45]46);47$property = VacationProperty::find($id);48$reservation = new Reservation($request->all());4950$reservation->user()->associate($user);5152$property->reservations()->save($reservation);5354$this->notifyHost($client, $reservation);5556$request->session()->flash(57'status',58"Sending your reservation request now."59);60return redirect()->route('reservation-index', ['id' => $property->id]);61}6263public function acceptReject(Client $client, Request $request)64{65$hostNumber = $request->input('From');66$smsInput = strtolower($request->input('Body'));67$host = User::where(DB::raw("CONCAT('+',country_code::text, phone_number::text)"), 'LIKE', "%".$hostNumber."%")68->get()69->first();7071$reservation = $host->pendingReservations()->first();72$smsResponse = null;73if (!is_null($reservation))74{75$reservation = $reservation->fresh();7677if (strpos($smsInput, 'yes') !== false || strpos($smsInput, 'accept') !== false)78{79$reservation->confirm($this->getNewTwilioNumber($client, $host));80}81else82{83$reservation->reject();84}8586$smsResponse = 'You have successfully ' . $reservation->status . ' the reservation.';87}88else89{90$smsResponse = 'Sorry, it looks like you don\'t have any reservations to respond to.';91}9293return response($this->respond($smsResponse, $reservation))->header('Content-Type', 'application/xml');94}9596public function connectSms(Request $request)97{98$twilioNumber = $request->input('To');99$incomingNumber = $request->input('From');100$messageBody = $request->input('Body');101102$reservation = $this->getReservationFromNumber($twilioNumber);103$host = $reservation->property->user;104$guest = $reservation->user;105106if ($incomingNumber === $host->fullNumber())107{108$outgoingNumber = $guest->fullNumber();109}110else111{112$outgoingNumber = $host->fullNumber();113}114115return response($this->connectSmsResponse($messageBody, $outgoingNumber))->header('Content-Type', 'application/xml');116}117118public function connectVoice(Request $request)119{120$twilioNumber = $request->input('To');121$incomingNumber = $request->input('From');122123$reservation = $this->getReservationFromNumber($twilioNumber);124$host = $reservation->property->user;125$guest = $reservation->user;126127if ($incomingNumber === $host->fullNumber())128{129$outgoingNumber = $guest->fullNumber();130}131else132{133$outgoingNumber = $host->fullNumber();134}135136return response($this->connectVoiceResponse($outgoingNumber))->header('Content-Type', 'application/xml');137}138139private function getReservationFromNumber($twilioNumber)140{141return Reservation::where('twilio_number', '=', $twilioNumber)->first();142}143144private function connectVoiceResponse($outgoingNumber)145{146$response = new Twiml();147$response->play('http://howtodocs.s3.amazonaws.com/howdy-tng.mp3');148$response->dial($outgoingNumber);149150return $response;151}152153private function connectSmsResponse($messageBody, $outgoingNumber)154{155$response = new Twiml();156$response->message(157$messageBody,158['to' => $outgoingNumber]159);160161return $response;162}163164private function respond($smsResponse, $reservation)165{166$response = new Twiml();167$response->message($smsResponse);168169if (!is_null($reservation))170{171$response->message(172'Your reservation has been ' . $reservation->status . '.',173['to' => $reservation->user->fullNumber()]174);175}176return $response;177}178179private function notifyHost($client, $reservation)180{181$host = $reservation->property->user;182183$twilioNumber = config('services.twilio')['number'];184185$messageBody = $reservation->message . ' - Reply \'yes\' or \'accept\' to confirm the reservation, or anything else to reject it.';186187try {188$client->messages->create(189$host->fullNumber(), // Text any number190[191'from' => $twilioNumber, // From a Twilio number in your account192'body' => $messageBody193]194);195} catch (Exception $e) {196Log::error($e->getMessage());197}198}199200private function getNewTwilioNumber($client, $host)201{202$numbers = $client->availablePhoneNumbers('US')->local->read(203[204'areaCode' => $host->areaCode(),205'voiceEnabled' => 'true',206"smsEnabled" => 'true'207]208);209210if (empty($numbers)) {211$numbers = $client->availablePhoneNumbers('US')->local->read(212[213'voiceEnabled' => 'true',214"smsEnabled" => 'true'215]216);217}218$twilioNumber = $numbers[0]->phoneNumber;219220$newNumber = $client->incomingPhoneNumbers->create(221[222"phoneNumber" => $twilioNumber,223"smsApplicationSid" => config('services.twilio')['applicationSid'],224"voiceApplicationSid" => config('services.twilio')['applicationSid']225]226);227228if ($newNumber) {229return $twilioNumber;230} else {231return 0;232}233}234}
That's it! We've just implemented anonymous communications that allow your customers to connect while protecting their privacy.
If you're a PHP developer working with Twilio, you might want to check out these other tutorials:
Put a button on your web page that connects visitors to live support or sales people via telephone.
Instantly collect structured data from your users with a survey conducted over a voice call or SMS text messages.
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.