Skip to contentSkip to navigationSkip to topbar
On this page

Masked Phone Numbers with PHP and Laravel


This PHP Laravel(link takes you to an external page) sample application is modeled after the amazing rental experience created by AirBnB(link takes you to an external page), but with more Klingons(link takes you to an external page).

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(link takes you to an external page).

(warning)

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(link takes you to an external page).

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.(link takes you to an external page)


Create a Reservation

create-a-reservation page anchor

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.

Create a Reservation

create-a-reservation-1 page anchor

app/Http/Controllers/ReservationController.php

1
<?php
2
namespace App\Http\Controllers;
3
use Illuminate\Http\Request;
4
use App\Http\Requests;
5
use App\Http\Controllers\Controller;
6
use Illuminate\Contracts\Auth\Authenticatable;
7
use App\Reservation;
8
use App\User;
9
use App\VacationProperty;
10
use DB;
11
use Twilio\Rest\Client;
12
use Twilio\Twiml;
13
use Log;
14
15
class ReservationController extends Controller
16
{
17
public function index(Authenticatable $user)
18
{
19
$reservations = array();
20
21
foreach ($user->propertyReservations as $reservation)
22
{
23
array_push($reservations, $reservation->fresh());
24
}
25
return view(
26
'reservation.index',
27
[
28
'hostReservations' => $reservations,
29
'guestReservations' => $user->reservations
30
]
31
);
32
}
33
34
/**
35
* Store a new reservation
36
*
37
* @param \Illuminate\Http\Request $request
38
* @return \Illuminate\Http\Response
39
*/
40
public 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());
49
50
$reservation->user()->associate($user);
51
52
$property->reservations()->save($reservation);
53
54
$this->notifyHost($client, $reservation);
55
56
$request->session()->flash(
57
'status',
58
"Sending your reservation request now."
59
);
60
return redirect()->route('reservation-index', ['id' => $property->id]);
61
}
62
63
public 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();
70
71
$reservation = $host->pendingReservations()->first();
72
$smsResponse = null;
73
if (!is_null($reservation))
74
{
75
$reservation = $reservation->fresh();
76
77
if (strpos($smsInput, 'yes') !== false || strpos($smsInput, 'accept') !== false)
78
{
79
$reservation->confirm($this->getNewTwilioNumber($client, $host));
80
}
81
else
82
{
83
$reservation->reject();
84
}
85
86
$smsResponse = 'You have successfully ' . $reservation->status . ' the reservation.';
87
}
88
else
89
{
90
$smsResponse = 'Sorry, it looks like you don\'t have any reservations to respond to.';
91
}
92
93
return response($this->respond($smsResponse, $reservation))->header('Content-Type', 'application/xml');
94
}
95
96
public function connectSms(Request $request)
97
{
98
$twilioNumber = $request->input('To');
99
$incomingNumber = $request->input('From');
100
$messageBody = $request->input('Body');
101
102
$reservation = $this->getReservationFromNumber($twilioNumber);
103
$host = $reservation->property->user;
104
$guest = $reservation->user;
105
106
if ($incomingNumber === $host->fullNumber())
107
{
108
$outgoingNumber = $guest->fullNumber();
109
}
110
else
111
{
112
$outgoingNumber = $host->fullNumber();
113
}
114
115
return response($this->connectSmsResponse($messageBody, $outgoingNumber))->header('Content-Type', 'application/xml');
116
}
117
118
public function connectVoice(Request $request)
119
{
120
$twilioNumber = $request->input('To');
121
$incomingNumber = $request->input('From');
122
123
$reservation = $this->getReservationFromNumber($twilioNumber);
124
$host = $reservation->property->user;
125
$guest = $reservation->user;
126
127
if ($incomingNumber === $host->fullNumber())
128
{
129
$outgoingNumber = $guest->fullNumber();
130
}
131
else
132
{
133
$outgoingNumber = $host->fullNumber();
134
}
135
136
return response($this->connectVoiceResponse($outgoingNumber))->header('Content-Type', 'application/xml');
137
}
138
139
private function getReservationFromNumber($twilioNumber)
140
{
141
return Reservation::where('twilio_number', '=', $twilioNumber)->first();
142
}
143
144
private function connectVoiceResponse($outgoingNumber)
145
{
146
$response = new Twiml();
147
$response->play('http://howtodocs.s3.amazonaws.com/howdy-tng.mp3');
148
$response->dial($outgoingNumber);
149
150
return $response;
151
}
152
153
private function connectSmsResponse($messageBody, $outgoingNumber)
154
{
155
$response = new Twiml();
156
$response->message(
157
$messageBody,
158
['to' => $outgoingNumber]
159
);
160
161
return $response;
162
}
163
164
private function respond($smsResponse, $reservation)
165
{
166
$response = new Twiml();
167
$response->message($smsResponse);
168
169
if (!is_null($reservation))
170
{
171
$response->message(
172
'Your reservation has been ' . $reservation->status . '.',
173
['to' => $reservation->user->fullNumber()]
174
);
175
}
176
return $response;
177
}
178
179
private function notifyHost($client, $reservation)
180
{
181
$host = $reservation->property->user;
182
183
$twilioNumber = config('services.twilio')['number'];
184
185
$messageBody = $reservation->message . ' - Reply \'yes\' or \'accept\' to confirm the reservation, or anything else to reject it.';
186
187
try {
188
$client->messages->create(
189
$host->fullNumber(), // Text any number
190
[
191
'from' => $twilioNumber, // From a Twilio number in your account
192
'body' => $messageBody
193
]
194
);
195
} catch (Exception $e) {
196
Log::error($e->getMessage());
197
}
198
}
199
200
private 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
);
209
210
if (empty($numbers)) {
211
$numbers = $client->availablePhoneNumbers('US')->local->read(
212
[
213
'voiceEnabled' => 'true',
214
"smsEnabled" => 'true'
215
]
216
);
217
}
218
$twilioNumber = $numbers[0]->phoneNumber;
219
220
$newNumber = $client->incomingPhoneNumbers->create(
221
[
222
"phoneNumber" => $twilioNumber,
223
"smsApplicationSid" => config('services.twilio')['applicationSid'],
224
"voiceApplicationSid" => config('services.twilio')['applicationSid']
225
]
226
);
227
228
if ($newNumber) {
229
return $twilioNumber;
230
} else {
231
return 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(link takes you to an external page).

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.

Confirm Reservation Method

confirm-reservation-method page anchor

app/Http/Controllers/ReservationController.php

1
<?php
2
namespace App\Http\Controllers;
3
use Illuminate\Http\Request;
4
use App\Http\Requests;
5
use App\Http\Controllers\Controller;
6
use Illuminate\Contracts\Auth\Authenticatable;
7
use App\Reservation;
8
use App\User;
9
use App\VacationProperty;
10
use DB;
11
use Twilio\Rest\Client;
12
use Twilio\Twiml;
13
use Log;
14
15
class ReservationController extends Controller
16
{
17
public function index(Authenticatable $user)
18
{
19
$reservations = array();
20
21
foreach ($user->propertyReservations as $reservation)
22
{
23
array_push($reservations, $reservation->fresh());
24
}
25
return view(
26
'reservation.index',
27
[
28
'hostReservations' => $reservations,
29
'guestReservations' => $user->reservations
30
]
31
);
32
}
33
34
/**
35
* Store a new reservation
36
*
37
* @param \Illuminate\Http\Request $request
38
* @return \Illuminate\Http\Response
39
*/
40
public 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());
49
50
$reservation->user()->associate($user);
51
52
$property->reservations()->save($reservation);
53
54
$this->notifyHost($client, $reservation);
55
56
$request->session()->flash(
57
'status',
58
"Sending your reservation request now."
59
);
60
return redirect()->route('reservation-index', ['id' => $property->id]);
61
}
62
63
public 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();
70
71
$reservation = $host->pendingReservations()->first();
72
$smsResponse = null;
73
if (!is_null($reservation))
74
{
75
$reservation = $reservation->fresh();
76
77
if (strpos($smsInput, 'yes') !== false || strpos($smsInput, 'accept') !== false)
78
{
79
$reservation->confirm($this->getNewTwilioNumber($client, $host));
80
}
81
else
82
{
83
$reservation->reject();
84
}
85
86
$smsResponse = 'You have successfully ' . $reservation->status . ' the reservation.';
87
}
88
else
89
{
90
$smsResponse = 'Sorry, it looks like you don\'t have any reservations to respond to.';
91
}
92
93
return response($this->respond($smsResponse, $reservation))->header('Content-Type', 'application/xml');
94
}
95
96
public function connectSms(Request $request)
97
{
98
$twilioNumber = $request->input('To');
99
$incomingNumber = $request->input('From');
100
$messageBody = $request->input('Body');
101
102
$reservation = $this->getReservationFromNumber($twilioNumber);
103
$host = $reservation->property->user;
104
$guest = $reservation->user;
105
106
if ($incomingNumber === $host->fullNumber())
107
{
108
$outgoingNumber = $guest->fullNumber();
109
}
110
else
111
{
112
$outgoingNumber = $host->fullNumber();
113
}
114
115
return response($this->connectSmsResponse($messageBody, $outgoingNumber))->header('Content-Type', 'application/xml');
116
}
117
118
public function connectVoice(Request $request)
119
{
120
$twilioNumber = $request->input('To');
121
$incomingNumber = $request->input('From');
122
123
$reservation = $this->getReservationFromNumber($twilioNumber);
124
$host = $reservation->property->user;
125
$guest = $reservation->user;
126
127
if ($incomingNumber === $host->fullNumber())
128
{
129
$outgoingNumber = $guest->fullNumber();
130
}
131
else
132
{
133
$outgoingNumber = $host->fullNumber();
134
}
135
136
return response($this->connectVoiceResponse($outgoingNumber))->header('Content-Type', 'application/xml');
137
}
138
139
private function getReservationFromNumber($twilioNumber)
140
{
141
return Reservation::where('twilio_number', '=', $twilioNumber)->first();
142
}
143
144
private function connectVoiceResponse($outgoingNumber)
145
{
146
$response = new Twiml();
147
$response->play('http://howtodocs.s3.amazonaws.com/howdy-tng.mp3');
148
$response->dial($outgoingNumber);
149
150
return $response;
151
}
152
153
private function connectSmsResponse($messageBody, $outgoingNumber)
154
{
155
$response = new Twiml();
156
$response->message(
157
$messageBody,
158
['to' => $outgoingNumber]
159
);
160
161
return $response;
162
}
163
164
private function respond($smsResponse, $reservation)
165
{
166
$response = new Twiml();
167
$response->message($smsResponse);
168
169
if (!is_null($reservation))
170
{
171
$response->message(
172
'Your reservation has been ' . $reservation->status . '.',
173
['to' => $reservation->user->fullNumber()]
174
);
175
}
176
return $response;
177
}
178
179
private function notifyHost($client, $reservation)
180
{
181
$host = $reservation->property->user;
182
183
$twilioNumber = config('services.twilio')['number'];
184
185
$messageBody = $reservation->message . ' - Reply \'yes\' or \'accept\' to confirm the reservation, or anything else to reject it.';
186
187
try {
188
$client->messages->create(
189
$host->fullNumber(), // Text any number
190
[
191
'from' => $twilioNumber, // From a Twilio number in your account
192
'body' => $messageBody
193
]
194
);
195
} catch (Exception $e) {
196
Log::error($e->getMessage());
197
}
198
}
199
200
private 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
);
209
210
if (empty($numbers)) {
211
$numbers = $client->availablePhoneNumbers('US')->local->read(
212
[
213
'voiceEnabled' => 'true',
214
"smsEnabled" => 'true'
215
]
216
);
217
}
218
$twilioNumber = $numbers[0]->phoneNumber;
219
220
$newNumber = $client->incomingPhoneNumbers->create(
221
[
222
"phoneNumber" => $twilioNumber,
223
"smsApplicationSid" => config('services.twilio')['applicationSid'],
224
"voiceApplicationSid" => config('services.twilio')['applicationSid']
225
]
226
);
227
228
if ($newNumber) {
229
return $twilioNumber;
230
} else {
231
return 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.


Purchase a Twilio Number

purchase-a-twilio-number page anchor

Here we use a Twilio REST API Client(link takes you to an external page) 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(link takes you to an external page) 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
<?php
2
namespace App\Http\Controllers;
3
use Illuminate\Http\Request;
4
use App\Http\Requests;
5
use App\Http\Controllers\Controller;
6
use Illuminate\Contracts\Auth\Authenticatable;
7
use App\Reservation;
8
use App\User;
9
use App\VacationProperty;
10
use DB;
11
use Twilio\Rest\Client;
12
use Twilio\Twiml;
13
use Log;
14
15
class ReservationController extends Controller
16
{
17
public function index(Authenticatable $user)
18
{
19
$reservations = array();
20
21
foreach ($user->propertyReservations as $reservation)
22
{
23
array_push($reservations, $reservation->fresh());
24
}
25
return view(
26
'reservation.index',
27
[
28
'hostReservations' => $reservations,
29
'guestReservations' => $user->reservations
30
]
31
);
32
}
33
34
/**
35
* Store a new reservation
36
*
37
* @param \Illuminate\Http\Request $request
38
* @return \Illuminate\Http\Response
39
*/
40
public 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());
49
50
$reservation->user()->associate($user);
51
52
$property->reservations()->save($reservation);
53
54
$this->notifyHost($client, $reservation);
55
56
$request->session()->flash(
57
'status',
58
"Sending your reservation request now."
59
);
60
return redirect()->route('reservation-index', ['id' => $property->id]);
61
}
62
63
public 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();
70
71
$reservation = $host->pendingReservations()->first();
72
$smsResponse = null;
73
if (!is_null($reservation))
74
{
75
$reservation = $reservation->fresh();
76
77
if (strpos($smsInput, 'yes') !== false || strpos($smsInput, 'accept') !== false)
78
{
79
$reservation->confirm($this->getNewTwilioNumber($client, $host));
80
}
81
else
82
{
83
$reservation->reject();
84
}
85
86
$smsResponse = 'You have successfully ' . $reservation->status . ' the reservation.';
87
}
88
else
89
{
90
$smsResponse = 'Sorry, it looks like you don\'t have any reservations to respond to.';
91
}
92
93
return response($this->respond($smsResponse, $reservation))->header('Content-Type', 'application/xml');
94
}
95
96
public function connectSms(Request $request)
97
{
98
$twilioNumber = $request->input('To');
99
$incomingNumber = $request->input('From');
100
$messageBody = $request->input('Body');
101
102
$reservation = $this->getReservationFromNumber($twilioNumber);
103
$host = $reservation->property->user;
104
$guest = $reservation->user;
105
106
if ($incomingNumber === $host->fullNumber())
107
{
108
$outgoingNumber = $guest->fullNumber();
109
}
110
else
111
{
112
$outgoingNumber = $host->fullNumber();
113
}
114
115
return response($this->connectSmsResponse($messageBody, $outgoingNumber))->header('Content-Type', 'application/xml');
116
}
117
118
public function connectVoice(Request $request)
119
{
120
$twilioNumber = $request->input('To');
121
$incomingNumber = $request->input('From');
122
123
$reservation = $this->getReservationFromNumber($twilioNumber);
124
$host = $reservation->property->user;
125
$guest = $reservation->user;
126
127
if ($incomingNumber === $host->fullNumber())
128
{
129
$outgoingNumber = $guest->fullNumber();
130
}
131
else
132
{
133
$outgoingNumber = $host->fullNumber();
134
}
135
136
return response($this->connectVoiceResponse($outgoingNumber))->header('Content-Type', 'application/xml');
137
}
138
139
private function getReservationFromNumber($twilioNumber)
140
{
141
return Reservation::where('twilio_number', '=', $twilioNumber)->first();
142
}
143
144
private function connectVoiceResponse($outgoingNumber)
145
{
146
$response = new Twiml();
147
$response->play('http://howtodocs.s3.amazonaws.com/howdy-tng.mp3');
148
$response->dial($outgoingNumber);
149
150
return $response;
151
}
152
153
private function connectSmsResponse($messageBody, $outgoingNumber)
154
{
155
$response = new Twiml();
156
$response->message(
157
$messageBody,
158
['to' => $outgoingNumber]
159
);
160
161
return $response;
162
}
163
164
private function respond($smsResponse, $reservation)
165
{
166
$response = new Twiml();
167
$response->message($smsResponse);
168
169
if (!is_null($reservation))
170
{
171
$response->message(
172
'Your reservation has been ' . $reservation->status . '.',
173
['to' => $reservation->user->fullNumber()]
174
);
175
}
176
return $response;
177
}
178
179
private function notifyHost($client, $reservation)
180
{
181
$host = $reservation->property->user;
182
183
$twilioNumber = config('services.twilio')['number'];
184
185
$messageBody = $reservation->message . ' - Reply \'yes\' or \'accept\' to confirm the reservation, or anything else to reject it.';
186
187
try {
188
$client->messages->create(
189
$host->fullNumber(), // Text any number
190
[
191
'from' => $twilioNumber, // From a Twilio number in your account
192
'body' => $messageBody
193
]
194
);
195
} catch (Exception $e) {
196
Log::error($e->getMessage());
197
}
198
}
199
200
private 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
);
209
210
if (empty($numbers)) {
211
$numbers = $client->availablePhoneNumbers('US')->local->read(
212
[
213
'voiceEnabled' => 'true',
214
"smsEnabled" => 'true'
215
]
216
);
217
}
218
$twilioNumber = $numbers[0]->phoneNumber;
219
220
$newNumber = $client->incomingPhoneNumbers->create(
221
[
222
"phoneNumber" => $twilioNumber,
223
"smsApplicationSid" => config('services.twilio')['applicationSid'],
224
"voiceApplicationSid" => config('services.twilio')['applicationSid']
225
]
226
);
227
228
if ($newNumber) {
229
return $twilioNumber;
230
} else {
231
return 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:

  • the From number that originally called or sent an SMS
  • the 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.

app/Http/Controllers/ReservationController.php

1
<?php
2
namespace App\Http\Controllers;
3
use Illuminate\Http\Request;
4
use App\Http\Requests;
5
use App\Http\Controllers\Controller;
6
use Illuminate\Contracts\Auth\Authenticatable;
7
use App\Reservation;
8
use App\User;
9
use App\VacationProperty;
10
use DB;
11
use Twilio\Rest\Client;
12
use Twilio\Twiml;
13
use Log;
14
15
class ReservationController extends Controller
16
{
17
public function index(Authenticatable $user)
18
{
19
$reservations = array();
20
21
foreach ($user->propertyReservations as $reservation)
22
{
23
array_push($reservations, $reservation->fresh());
24
}
25
return view(
26
'reservation.index',
27
[
28
'hostReservations' => $reservations,
29
'guestReservations' => $user->reservations
30
]
31
);
32
}
33
34
/**
35
* Store a new reservation
36
*
37
* @param \Illuminate\Http\Request $request
38
* @return \Illuminate\Http\Response
39
*/
40
public 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());
49
50
$reservation->user()->associate($user);
51
52
$property->reservations()->save($reservation);
53
54
$this->notifyHost($client, $reservation);
55
56
$request->session()->flash(
57
'status',
58
"Sending your reservation request now."
59
);
60
return redirect()->route('reservation-index', ['id' => $property->id]);
61
}
62
63
public 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();
70
71
$reservation = $host->pendingReservations()->first();
72
$smsResponse = null;
73
if (!is_null($reservation))
74
{
75
$reservation = $reservation->fresh();
76
77
if (strpos($smsInput, 'yes') !== false || strpos($smsInput, 'accept') !== false)
78
{
79
$reservation->confirm($this->getNewTwilioNumber($client, $host));
80
}
81
else
82
{
83
$reservation->reject();
84
}
85
86
$smsResponse = 'You have successfully ' . $reservation->status . ' the reservation.';
87
}
88
else
89
{
90
$smsResponse = 'Sorry, it looks like you don\'t have any reservations to respond to.';
91
}
92
93
return response($this->respond($smsResponse, $reservation))->header('Content-Type', 'application/xml');
94
}
95
96
public function connectSms(Request $request)
97
{
98
$twilioNumber = $request->input('To');
99
$incomingNumber = $request->input('From');
100
$messageBody = $request->input('Body');
101
102
$reservation = $this->getReservationFromNumber($twilioNumber);
103
$host = $reservation->property->user;
104
$guest = $reservation->user;
105
106
if ($incomingNumber === $host->fullNumber())
107
{
108
$outgoingNumber = $guest->fullNumber();
109
}
110
else
111
{
112
$outgoingNumber = $host->fullNumber();
113
}
114
115
return response($this->connectSmsResponse($messageBody, $outgoingNumber))->header('Content-Type', 'application/xml');
116
}
117
118
public function connectVoice(Request $request)
119
{
120
$twilioNumber = $request->input('To');
121
$incomingNumber = $request->input('From');
122
123
$reservation = $this->getReservationFromNumber($twilioNumber);
124
$host = $reservation->property->user;
125
$guest = $reservation->user;
126
127
if ($incomingNumber === $host->fullNumber())
128
{
129
$outgoingNumber = $guest->fullNumber();
130
}
131
else
132
{
133
$outgoingNumber = $host->fullNumber();
134
}
135
136
return response($this->connectVoiceResponse($outgoingNumber))->header('Content-Type', 'application/xml');
137
}
138
139
private function getReservationFromNumber($twilioNumber)
140
{
141
return Reservation::where('twilio_number', '=', $twilioNumber)->first();
142
}
143
144
private function connectVoiceResponse($outgoingNumber)
145
{
146
$response = new Twiml();
147
$response->play('http://howtodocs.s3.amazonaws.com/howdy-tng.mp3');
148
$response->dial($outgoingNumber);
149
150
return $response;
151
}
152
153
private function connectSmsResponse($messageBody, $outgoingNumber)
154
{
155
$response = new Twiml();
156
$response->message(
157
$messageBody,
158
['to' => $outgoingNumber]
159
);
160
161
return $response;
162
}
163
164
private function respond($smsResponse, $reservation)
165
{
166
$response = new Twiml();
167
$response->message($smsResponse);
168
169
if (!is_null($reservation))
170
{
171
$response->message(
172
'Your reservation has been ' . $reservation->status . '.',
173
['to' => $reservation->user->fullNumber()]
174
);
175
}
176
return $response;
177
}
178
179
private function notifyHost($client, $reservation)
180
{
181
$host = $reservation->property->user;
182
183
$twilioNumber = config('services.twilio')['number'];
184
185
$messageBody = $reservation->message . ' - Reply \'yes\' or \'accept\' to confirm the reservation, or anything else to reject it.';
186
187
try {
188
$client->messages->create(
189
$host->fullNumber(), // Text any number
190
[
191
'from' => $twilioNumber, // From a Twilio number in your account
192
'body' => $messageBody
193
]
194
);
195
} catch (Exception $e) {
196
Log::error($e->getMessage());
197
}
198
}
199
200
private 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
);
209
210
if (empty($numbers)) {
211
$numbers = $client->availablePhoneNumbers('US')->local->read(
212
[
213
'voiceEnabled' => 'true',
214
"smsEnabled" => 'true'
215
]
216
);
217
}
218
$twilioNumber = $numbers[0]->phoneNumber;
219
220
$newNumber = $client->incomingPhoneNumbers->create(
221
[
222
"phoneNumber" => $twilioNumber,
223
"smsApplicationSid" => config('services.twilio')['applicationSid'],
224
"voiceApplicationSid" => config('services.twilio')['applicationSid']
225
]
226
);
227
228
if ($newNumber) {
229
return $twilioNumber;
230
} else {
231
return 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
<?php
2
namespace App\Http\Controllers;
3
use Illuminate\Http\Request;
4
use App\Http\Requests;
5
use App\Http\Controllers\Controller;
6
use Illuminate\Contracts\Auth\Authenticatable;
7
use App\Reservation;
8
use App\User;
9
use App\VacationProperty;
10
use DB;
11
use Twilio\Rest\Client;
12
use Twilio\Twiml;
13
use Log;
14
15
class ReservationController extends Controller
16
{
17
public function index(Authenticatable $user)
18
{
19
$reservations = array();
20
21
foreach ($user->propertyReservations as $reservation)
22
{
23
array_push($reservations, $reservation->fresh());
24
}
25
return view(
26
'reservation.index',
27
[
28
'hostReservations' => $reservations,
29
'guestReservations' => $user->reservations
30
]
31
);
32
}
33
34
/**
35
* Store a new reservation
36
*
37
* @param \Illuminate\Http\Request $request
38
* @return \Illuminate\Http\Response
39
*/
40
public 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());
49
50
$reservation->user()->associate($user);
51
52
$property->reservations()->save($reservation);
53
54
$this->notifyHost($client, $reservation);
55
56
$request->session()->flash(
57
'status',
58
"Sending your reservation request now."
59
);
60
return redirect()->route('reservation-index', ['id' => $property->id]);
61
}
62
63
public 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();
70
71
$reservation = $host->pendingReservations()->first();
72
$smsResponse = null;
73
if (!is_null($reservation))
74
{
75
$reservation = $reservation->fresh();
76
77
if (strpos($smsInput, 'yes') !== false || strpos($smsInput, 'accept') !== false)
78
{
79
$reservation->confirm($this->getNewTwilioNumber($client, $host));
80
}
81
else
82
{
83
$reservation->reject();
84
}
85
86
$smsResponse = 'You have successfully ' . $reservation->status . ' the reservation.';
87
}
88
else
89
{
90
$smsResponse = 'Sorry, it looks like you don\'t have any reservations to respond to.';
91
}
92
93
return response($this->respond($smsResponse, $reservation))->header('Content-Type', 'application/xml');
94
}
95
96
public function connectSms(Request $request)
97
{
98
$twilioNumber = $request->input('To');
99
$incomingNumber = $request->input('From');
100
$messageBody = $request->input('Body');
101
102
$reservation = $this->getReservationFromNumber($twilioNumber);
103
$host = $reservation->property->user;
104
$guest = $reservation->user;
105
106
if ($incomingNumber === $host->fullNumber())
107
{
108
$outgoingNumber = $guest->fullNumber();
109
}
110
else
111
{
112
$outgoingNumber = $host->fullNumber();
113
}
114
115
return response($this->connectSmsResponse($messageBody, $outgoingNumber))->header('Content-Type', 'application/xml');
116
}
117
118
public function connectVoice(Request $request)
119
{
120
$twilioNumber = $request->input('To');
121
$incomingNumber = $request->input('From');
122
123
$reservation = $this->getReservationFromNumber($twilioNumber);
124
$host = $reservation->property->user;
125
$guest = $reservation->user;
126
127
if ($incomingNumber === $host->fullNumber())
128
{
129
$outgoingNumber = $guest->fullNumber();
130
}
131
else
132
{
133
$outgoingNumber = $host->fullNumber();
134
}
135
136
return response($this->connectVoiceResponse($outgoingNumber))->header('Content-Type', 'application/xml');
137
}
138
139
private function getReservationFromNumber($twilioNumber)
140
{
141
return Reservation::where('twilio_number', '=', $twilioNumber)->first();
142
}
143
144
private function connectVoiceResponse($outgoingNumber)
145
{
146
$response = new Twiml();
147
$response->play('http://howtodocs.s3.amazonaws.com/howdy-tng.mp3');
148
$response->dial($outgoingNumber);
149
150
return $response;
151
}
152
153
private function connectSmsResponse($messageBody, $outgoingNumber)
154
{
155
$response = new Twiml();
156
$response->message(
157
$messageBody,
158
['to' => $outgoingNumber]
159
);
160
161
return $response;
162
}
163
164
private function respond($smsResponse, $reservation)
165
{
166
$response = new Twiml();
167
$response->message($smsResponse);
168
169
if (!is_null($reservation))
170
{
171
$response->message(
172
'Your reservation has been ' . $reservation->status . '.',
173
['to' => $reservation->user->fullNumber()]
174
);
175
}
176
return $response;
177
}
178
179
private function notifyHost($client, $reservation)
180
{
181
$host = $reservation->property->user;
182
183
$twilioNumber = config('services.twilio')['number'];
184
185
$messageBody = $reservation->message . ' - Reply \'yes\' or \'accept\' to confirm the reservation, or anything else to reject it.';
186
187
try {
188
$client->messages->create(
189
$host->fullNumber(), // Text any number
190
[
191
'from' => $twilioNumber, // From a Twilio number in your account
192
'body' => $messageBody
193
]
194
);
195
} catch (Exception $e) {
196
Log::error($e->getMessage());
197
}
198
}
199
200
private 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
);
209
210
if (empty($numbers)) {
211
$numbers = $client->availablePhoneNumbers('US')->local->read(
212
[
213
'voiceEnabled' => 'true',
214
"smsEnabled" => 'true'
215
]
216
);
217
}
218
$twilioNumber = $numbers[0]->phoneNumber;
219
220
$newNumber = $client->incomingPhoneNumbers->create(
221
[
222
"phoneNumber" => $twilioNumber,
223
"smsApplicationSid" => config('services.twilio')['applicationSid'],
224
"voiceApplicationSid" => config('services.twilio')['applicationSid']
225
]
226
);
227
228
if ($newNumber) {
229
return $twilioNumber;
230
} else {
231
return 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
<?php
2
namespace App\Http\Controllers;
3
use Illuminate\Http\Request;
4
use App\Http\Requests;
5
use App\Http\Controllers\Controller;
6
use Illuminate\Contracts\Auth\Authenticatable;
7
use App\Reservation;
8
use App\User;
9
use App\VacationProperty;
10
use DB;
11
use Twilio\Rest\Client;
12
use Twilio\Twiml;
13
use Log;
14
15
class ReservationController extends Controller
16
{
17
public function index(Authenticatable $user)
18
{
19
$reservations = array();
20
21
foreach ($user->propertyReservations as $reservation)
22
{
23
array_push($reservations, $reservation->fresh());
24
}
25
return view(
26
'reservation.index',
27
[
28
'hostReservations' => $reservations,
29
'guestReservations' => $user->reservations
30
]
31
);
32
}
33
34
/**
35
* Store a new reservation
36
*
37
* @param \Illuminate\Http\Request $request
38
* @return \Illuminate\Http\Response
39
*/
40
public 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());
49
50
$reservation->user()->associate($user);
51
52
$property->reservations()->save($reservation);
53
54
$this->notifyHost($client, $reservation);
55
56
$request->session()->flash(
57
'status',
58
"Sending your reservation request now."
59
);
60
return redirect()->route('reservation-index', ['id' => $property->id]);
61
}
62
63
public 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();
70
71
$reservation = $host->pendingReservations()->first();
72
$smsResponse = null;
73
if (!is_null($reservation))
74
{
75
$reservation = $reservation->fresh();
76
77
if (strpos($smsInput, 'yes') !== false || strpos($smsInput, 'accept') !== false)
78
{
79
$reservation->confirm($this->getNewTwilioNumber($client, $host));
80
}
81
else
82
{
83
$reservation->reject();
84
}
85
86
$smsResponse = 'You have successfully ' . $reservation->status . ' the reservation.';
87
}
88
else
89
{
90
$smsResponse = 'Sorry, it looks like you don\'t have any reservations to respond to.';
91
}
92
93
return response($this->respond($smsResponse, $reservation))->header('Content-Type', 'application/xml');
94
}
95
96
public function connectSms(Request $request)
97
{
98
$twilioNumber = $request->input('To');
99
$incomingNumber = $request->input('From');
100
$messageBody = $request->input('Body');
101
102
$reservation = $this->getReservationFromNumber($twilioNumber);
103
$host = $reservation->property->user;
104
$guest = $reservation->user;
105
106
if ($incomingNumber === $host->fullNumber())
107
{
108
$outgoingNumber = $guest->fullNumber();
109
}
110
else
111
{
112
$outgoingNumber = $host->fullNumber();
113
}
114
115
return response($this->connectSmsResponse($messageBody, $outgoingNumber))->header('Content-Type', 'application/xml');
116
}
117
118
public function connectVoice(Request $request)
119
{
120
$twilioNumber = $request->input('To');
121
$incomingNumber = $request->input('From');
122
123
$reservation = $this->getReservationFromNumber($twilioNumber);
124
$host = $reservation->property->user;
125
$guest = $reservation->user;
126
127
if ($incomingNumber === $host->fullNumber())
128
{
129
$outgoingNumber = $guest->fullNumber();
130
}
131
else
132
{
133
$outgoingNumber = $host->fullNumber();
134
}
135
136
return response($this->connectVoiceResponse($outgoingNumber))->header('Content-Type', 'application/xml');
137
}
138
139
private function getReservationFromNumber($twilioNumber)
140
{
141
return Reservation::where('twilio_number', '=', $twilioNumber)->first();
142
}
143
144
private function connectVoiceResponse($outgoingNumber)
145
{
146
$response = new Twiml();
147
$response->play('http://howtodocs.s3.amazonaws.com/howdy-tng.mp3');
148
$response->dial($outgoingNumber);
149
150
return $response;
151
}
152
153
private function connectSmsResponse($messageBody, $outgoingNumber)
154
{
155
$response = new Twiml();
156
$response->message(
157
$messageBody,
158
['to' => $outgoingNumber]
159
);
160
161
return $response;
162
}
163
164
private function respond($smsResponse, $reservation)
165
{
166
$response = new Twiml();
167
$response->message($smsResponse);
168
169
if (!is_null($reservation))
170
{
171
$response->message(
172
'Your reservation has been ' . $reservation->status . '.',
173
['to' => $reservation->user->fullNumber()]
174
);
175
}
176
return $response;
177
}
178
179
private function notifyHost($client, $reservation)
180
{
181
$host = $reservation->property->user;
182
183
$twilioNumber = config('services.twilio')['number'];
184
185
$messageBody = $reservation->message . ' - Reply \'yes\' or \'accept\' to confirm the reservation, or anything else to reject it.';
186
187
try {
188
$client->messages->create(
189
$host->fullNumber(), // Text any number
190
[
191
'from' => $twilioNumber, // From a Twilio number in your account
192
'body' => $messageBody
193
]
194
);
195
} catch (Exception $e) {
196
Log::error($e->getMessage());
197
}
198
}
199
200
private 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
);
209
210
if (empty($numbers)) {
211
$numbers = $client->availablePhoneNumbers('US')->local->read(
212
[
213
'voiceEnabled' => 'true',
214
"smsEnabled" => 'true'
215
]
216
);
217
}
218
$twilioNumber = $numbers[0]->phoneNumber;
219
220
$newNumber = $client->incomingPhoneNumbers->create(
221
[
222
"phoneNumber" => $twilioNumber,
223
"smsApplicationSid" => config('services.twilio')['applicationSid'],
224
"voiceApplicationSid" => config('services.twilio')['applicationSid']
225
]
226
);
227
228
if ($newNumber) {
229
return $twilioNumber;
230
} else {
231
return 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:

Click-To-Call

Put a button on your web page that connects visitors to live support or sales people via telephone.

Automated Survey

Instantly collect structured data from your users with a survey conducted over a voice call or SMS text messages.

Did this help?

did-this-help page anchor

Thanks for checking out this tutorial! If you have any feedback to share with us, we'd love to hear it. Tweet @twilio(link takes you to an external page) to let us know what you think.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.