Skip to contentSkip to navigationSkip to topbar
On this page

Dynamic Call Center with PHP and Laravel


In this tutorial we will show how to automate the routing of calls from customers to your support agents. Customers will be able to select a product and wait while TaskRouter tries to contact a product specialist for the best support experience. If no one is available, our application will save the customer's number and selected product so an agent can call them back later on.

This is what the application does at a high level:

  1. Configure a workspace using the Twilio TaskRouter REST API .
  2. Listen for incoming calls and let the user select a product with the dial pad.
  3. Create a Task with the selected product and let TaskRouter handle it.
  4. Store missed calls so agents can return the call to customers.

Configure the Workspace

configure-the-workspace page anchor

In order to instruct TaskRouter to handle the Tasks, we need to configure a Workspace. We can do this in the TaskRouter Console(link takes you to an external page) or programmatically using the TaskRouter REST API.

A Workspace is the container element for any TaskRouter application. The elements are:

  • Tasks - Represents a customer trying to contact an agent.
  • Workers - The agents responsible for handling Tasks.
  • Task Queues - Holds Tasks to be consumed by a set of Workers.
  • Workflows - Responsible for placing Tasks into Task Queues.
  • Activities - Possible states of a Worker, e.g. Idle, Offline, Busy.

Workspace Configuration

workspace-configuration page anchor

resources/workspace.json

1
{
2
"name": "Twilio Workspace",
3
"event_callback": "%(host)s/events",
4
"workers": [
5
{
6
"name": "Bob",
7
"attributes": {
8
"products": [
9
"ProgrammableSMS"
10
],
11
"contact_uri": "%(bob_phone)s"
12
}
13
},
14
{
15
"name": "Alice",
16
"attributes": {
17
"products": [
18
"ProgrammableVoice"
19
],
20
"contact_uri": "%(alice_phone)s"
21
}
22
}
23
],
24
"activities": [
25
{
26
"name": "Offline",
27
"availability": "false"
28
},
29
{
30
"name": "Idle",
31
"availability": "true"
32
},
33
{
34
"name": "Busy",
35
"availability": "false"
36
},
37
{
38
"name": "Reserved",
39
"availability": "false"
40
}
41
],
42
"task_queues": [
43
{
44
"name": "Default",
45
"targetWorkers": "1==1"
46
},
47
{
48
"name": "SMS",
49
"targetWorkers": "products HAS \"ProgrammableSMS\""
50
},
51
{
52
"name": "Voice",
53
"targetWorkers": "products HAS \"ProgrammableVoice\""
54
}
55
],
56
"workflow": {
57
"name": "Sales",
58
"callback": "%(host)s/assignment",
59
"timeout": "15"
60
}
61
}

In order to build a client for this API, we need as system variables a TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN which you can find on Twilio Console. The artisan command workspace:create creates a Twilio\Rest\Client, which is provided by the Twilio PHP library(link takes you to an external page). This client is used by WorkspaceFacade(link takes you to an external page) which encapsulates all logic related to the creation of a Task Router workflow.

Let's take a look at that command next.


The CreateWorkspace Artisan Command

the-createworkspace-artisan-command page anchor

In this application the Artisan command(link takes you to an external page) workspace:create is used to orchestrate calls to our WorkspaceFacade class in order to build a Workspace from scratch. CreateWorkspace is the PHP class behind the Artisan command. It uses data provided by workspace.json and expects 3 arguments:

  1. host - A public URL to which Twilio can send requests. This can be either a cloud service or ngrok(link takes you to an external page) , which can expose a local application to the internet.
  2. bob_phone - The telephone number of Bob, the Programmable SMS specialist.
  3. alice_phone - Same for Alice, the Programmable Voice specialist.

The function createWorkspaceConfig is used to load the configuration of the workspace from workspace.json.

CreateWorkspace Artisan Command

createworkspace-artisan-command page anchor

app/Console/Commands/CreateWorkspace.php

1
<?php
2
3
namespace App\Console\Commands;
4
5
use App\TaskRouter\WorkspaceFacade;
6
use Illuminate\Console\Command;
7
use Illuminate\Support\Facades\File;
8
use TaskRouter_Services_Twilio;
9
use Twilio\Rest\Client;
10
use Twilio\Rest\Taskrouter;
11
use WorkflowRuleTarget;
12
13
class CreateWorkspace extends Command
14
{
15
/**
16
* The name and signature of the console command.
17
*
18
* @var string
19
*/
20
protected $signature = 'workspace:create
21
{host : Server hostname in Internet}
22
{bob_phone : Phone of the first agent (Bob)}
23
{alice_phone : Phone of the secondary agent (Alice)}';
24
25
/**
26
* The console command description.
27
*
28
* @var string
29
*/
30
protected $description = 'Creates a Twilio workspace for 2 call agents';
31
32
private $_twilioClient;
33
34
/**
35
* Create a new command instance.
36
*/
37
public function __construct(Client $twilioClient)
38
{
39
parent::__construct();
40
$this->_twilioClient = $twilioClient;
41
}
42
43
/**
44
* Execute the console command.
45
*
46
* @return mixed
47
*/
48
public function handle()
49
{
50
$this->info("Create workspace.");
51
$this->line("- Server: \t{$this->argument('host')}");
52
$this->line("- Bob phone: \t{$this->argument('bob_phone')}");
53
$this->line("- Alice phone: \t{$this->argument('alice_phone')}");
54
55
//Get the configuration
56
$workspaceConfig = $this->createWorkspaceConfig();
57
58
//Create the workspace
59
$params = array();
60
$params['friendlyName'] = $workspaceConfig->name;
61
$params['eventCallbackUrl'] = $workspaceConfig->event_callback;
62
$workspace = WorkspaceFacade::createNewWorkspace(
63
$this->_twilioClient->taskrouter,
64
$params
65
);
66
$this->addWorkersToWorkspace($workspace, $workspaceConfig);
67
$this->addTaskQueuesToWorkspace($workspace, $workspaceConfig);
68
$workflow = $this->addWorkflowToWorkspace($workspace, $workspaceConfig);
69
70
$this->printSuccessAndInstructions($workspace, $workflow);
71
}
72
73
/**
74
* Get the json configuration of the Workspace
75
*
76
* @return mixed
77
*/
78
function createWorkspaceConfig()
79
{
80
$fileContent = File::get("resources/workspace.json");
81
$interpolatedContent = sprintfn($fileContent, $this->argument());
82
return json_decode($interpolatedContent);
83
}
84
85
/**
86
* Add workers to workspace
87
*
88
* @param $workspace WorkspaceFacade
89
* @param $workspaceConfig string with Json
90
*/
91
function addWorkersToWorkspace($workspace, $workspaceConfig)
92
{
93
$this->line("Add Workers.");
94
$idleActivity = $workspace->findActivityByName("Idle")
95
or die("The activity 'Idle' was not found. Workers cannot be added.");
96
foreach ($workspaceConfig->workers as $workerJson) {
97
$params = array();
98
$params['friendlyName'] = $workerJson->name;
99
$params['activitySid'] = $idleActivity->sid;
100
$params['attributes'] = json_encode($workerJson->attributes);
101
$workspace->addWorker($params);
102
}
103
}
104
105
/**
106
* Add the Task Queues to the workspace
107
*
108
* @param $workspace WorkspaceFacade
109
* @param $workspaceConfig string with Json
110
*/
111
function addTaskQueuesToWorkspace($workspace, $workspaceConfig)
112
{
113
$this->line("Add Task Queues.");
114
$reservedActivity = $workspace->findActivityByName("Reserved");
115
$assignmentActivity = $workspace->findActivityByName("Busy");
116
foreach ($workspaceConfig->task_queues as $taskQueueJson) {
117
$params = array();
118
$params['friendlyName'] = $taskQueueJson->name;
119
$params['targetWorkers'] = $taskQueueJson->targetWorkers;
120
$params['reservationActivitySid'] = $reservedActivity->sid;
121
$params['assignmentActivitySid'] = $assignmentActivity->sid;
122
$workspace->addTaskQueue($params);
123
}
124
}
125
126
/**
127
* Create and configure the workflow to use in the workspace
128
*
129
* @param $workspace WorkspaceFacade
130
* @param $workspaceConfig string with Json
131
*
132
* @return object with added workflow
133
*/
134
function addWorkflowToWorkspace($workspace, $workspaceConfig)
135
{
136
$this->line("Add Worflow.");
137
$workflowJson = $workspaceConfig->workflow;
138
$params = array();
139
$params['friendlyName'] = $workflowJson->name;
140
$params['assignmentCallbackUrl'] = $workflowJson->callback;
141
$params['taskReservationTimeout'] = $workflowJson->timeout;
142
$params['configuration'] = $this->createWorkFlowJsonConfig(
143
$workspace,
144
$workflowJson
145
);
146
return $workspace->addWorkflow($params);
147
}
148
149
/**
150
* Create the workflow configuration in json format
151
*
152
* @param $workspace
153
* @param $workspaceConfig
154
*
155
* @return string configuration of workflow in json format
156
*/
157
function createWorkFlowJsonConfig($workspace, $workspaceConfig)
158
{
159
$params = array();
160
$defaultTaskQueue = $workspace->findTaskQueueByName("Default") or die(
161
"The 'Default' task queue was not found. The Workflow cannot be created."
162
);
163
$smsTaskQueue = $workspace->findTaskQueueByName("SMS") or die(
164
"The 'SMS' task queue was not found. The Workflow cannot be created."
165
);
166
$voiceTaskQueue = $workspace->findTaskQueueByName("Voice") or die(
167
"The 'Voice' task queue was not found. The Workflow cannot be created."
168
);
169
170
$params["default_task_queue_sid"] = $defaultTaskQueue->sid;
171
$params["sms_task_queue_sid"] = $smsTaskQueue->sid;
172
$params["voice_task_queue_sid"] = $voiceTaskQueue->sid;
173
174
$fileContent = File::get("resources/workflow.json");
175
$interpolatedContent = sprintfn($fileContent, $params);
176
return $interpolatedContent;
177
}
178
179
/**
180
* Prints the message indicating the workspace was successfully created and
181
* shows the commands to export the workspace variables into the environment.
182
*
183
* @param $workspace
184
* @param $workflow
185
*/
186
function printSuccessAndInstructions($workspace, $workflow)
187
{
188
$idleActivity = $workspace->findActivityByName("Idle")
189
or die("Somehow the activity 'Idle' was not found.");
190
$successMsg = "Workspace \"{$workspace->friendlyName}\"" .
191
" was created successfully.";
192
$this->printTitle($successMsg);
193
$this->line(
194
"The following variables will be set automatically."
195
);
196
$encondedWorkersPhone = http_build_query($workspace->getWorkerPhones());
197
$envVars = [
198
"WORKFLOW_SID" => $workflow->sid,
199
"POST_WORK_ACTIVITY_SID" => $idleActivity->sid,
200
"WORKSPACE_SID" => $workspace->sid,
201
"PHONE_TO_WORKER" => $encondedWorkersPhone
202
];
203
updateEnv($envVars);
204
foreach ($envVars as $key => $value) {
205
$this->warn("export $key=$value");
206
}
207
}
208
209
/**
210
* Prints a text separated up and doNwn by a token based line, usually "*"
211
*/
212
function printTitle($text)
213
{
214
$lineLength = strlen($text) + 2;
215
$this->line(str_repeat("*", $lineLength));
216
$this->line(" $text ");
217
$this->line(str_repeat("*", $lineLength));
218
}
219
}

Now let's look in more detail at all the steps, starting with the creation of the workspace itself.


Before creating a workspace, we need to delete any others with the same friendlyName as identifier. In order to create a workspace we need to provide a friendlyName, and a eventCallbackUrl which contains a URL to be called every time an event is triggered in the workspace.

app/TaskRouter/WorkspaceFacade.php

1
<?php
2
3
namespace App\TaskRouter;
4
5
use Twilio\Rest\Taskrouter\V1\Workspace;
6
7
8
class WorkspaceFacade
9
{
10
private $_taskRouterClient;
11
12
private $_workspace;
13
14
private $_activities;
15
16
public function __construct($taskRouterClient, $workspace)
17
{
18
$this->_taskRouterClient = $taskRouterClient;
19
$this->_workspace = $workspace;
20
}
21
22
public static function createNewWorkspace($taskRouterClient, $params)
23
{
24
$workspaceName = $params["friendlyName"];
25
$existingWorkspace = $taskRouterClient->workspaces->read(
26
array(
27
"friendlyName" => $workspaceName
28
)
29
);
30
if ($existingWorkspace) {
31
$existingWorkspace[0]->delete();
32
}
33
34
$workspace = $taskRouterClient->workspaces
35
->create($workspaceName, $params);
36
return new WorkspaceFacade($taskRouterClient, $workspace);
37
}
38
39
public static function createBySid($taskRouterClient, $workspaceSid)
40
{
41
$workspace = $taskRouterClient->workspaces($workspaceSid);
42
return new WorkspaceFacade($taskRouterClient, $workspace);
43
}
44
45
/**
46
* Magic getter to lazy load subresources
47
*
48
* @param string $property Subresource to return
49
*
50
* @return \Twilio\ListResource The requested subresource
51
*
52
* @throws \Twilio\Exceptions\TwilioException For unknown subresources
53
*/
54
public function __get($property)
55
{
56
return $this->_workspace->$property;
57
}
58
59
/**
60
* Gets an activity instance by its friendly name
61
*
62
* @param $activityName Friendly name of the activity to search for
63
*
64
* @return ActivityInstance of the activity found or null
65
*/
66
function findActivityByName($activityName)
67
{
68
$this->cacheActivitiesByName();
69
return $this->_activities[$activityName];
70
}
71
72
/**
73
* Caches the activities in an associative array which links friendlyName with
74
* its ActivityInstance
75
*/
76
protected function cacheActivitiesByName()
77
{
78
if (!$this->_activities) {
79
$this->_activities = array();
80
foreach ($this->_workspace->activities->read() as $activity) {
81
$this->_activities[$activity->friendlyName] = $activity;
82
}
83
}
84
}
85
86
/**
87
* Looks for a worker by its SID
88
*
89
* @param $sid string with the Worker SID
90
*
91
* @return mixed worker found or null
92
*/
93
function findWorkerBySid($sid)
94
{
95
return $this->_workspace->workers($sid);
96
}
97
98
/**
99
* Returns an associative array with
100
*
101
* @return mixed array with the relation phone -> workerSid
102
*/
103
function getWorkerPhones()
104
{
105
$worker_phones = array();
106
foreach ($this->_workspace->workers->read() as $worker) {
107
$workerAttribs = json_decode($worker->attributes);
108
$worker_phones[$workerAttribs->contact_uri] = $worker->sid;
109
}
110
return $worker_phones;
111
}
112
113
/**
114
* Looks for a Task Queue by its friendly name
115
*
116
* @param $taskQueueName string with the friendly name of the task queue to
117
* search for
118
*
119
* @return the activity found or null
120
*/
121
function findTaskQueueByName($taskQueueName)
122
{
123
$result = $this->_workspace->taskQueues->read(
124
array(
125
"friendlyName" => $taskQueueName
126
)
127
);
128
if ($result) {
129
return $result[0];
130
}
131
}
132
133
function updateWorkerActivity($worker, $activitySid)
134
{
135
$worker->update(['activitySid' => $activitySid]);
136
}
137
138
/**
139
* Adds workers to the workspace
140
*
141
* @param $params mixed with the attributes to define the new Worker in the
142
* workspace
143
*
144
* @return Workspace\WorkerInstance|Null
145
*/
146
function addWorker($params)
147
{
148
return $this->_workspace->workers->create($params['friendlyName'], $params);
149
}
150
151
/**
152
* Adds a Task Queue to the workspace
153
*
154
* @param $params mixed with attributes to define the new Task Queue in the
155
* workspace
156
*
157
* @return Workspace\TaskQueueInstance|Null
158
*/
159
function addTaskQueue($params)
160
{
161
return $this->_workspace->taskQueues->create(
162
$params['friendlyName'],
163
$params['reservationActivitySid'],
164
$params['assignmentActivitySid'],
165
$params
166
);
167
}
168
169
170
/**
171
* Adds a workflow to the workspace
172
*
173
* @param $params mixed with attributes to define the new Workflow in the
174
* workspace
175
*
176
* @return Workspace\WorkflowInstance|Null
177
*/
178
function addWorkFlow($params)
179
{
180
return $this->_workspace->workflows->create(
181
$params["friendlyName"],
182
$params["configuration"],
183
$params
184
);
185
}
186
187
}

We have a brand new workspace, now we need workers. Let's create them on the next step.


We'll create two workers: Bob and Alice. They each have two attributes: contact_uri, a phone number, and products, a list of products each worker is specialized in. We also need to specify an activity_sid and a name for each worker. The selected activity will define the status of the worker.

app/Console/Commands/CreateWorkspace.php

1
<?php
2
3
namespace App\Console\Commands;
4
5
use App\TaskRouter\WorkspaceFacade;
6
use Illuminate\Console\Command;
7
use Illuminate\Support\Facades\File;
8
use TaskRouter_Services_Twilio;
9
use Twilio\Rest\Client;
10
use Twilio\Rest\Taskrouter;
11
use WorkflowRuleTarget;
12
13
class CreateWorkspace extends Command
14
{
15
/**
16
* The name and signature of the console command.
17
*
18
* @var string
19
*/
20
protected $signature = 'workspace:create
21
{host : Server hostname in Internet}
22
{bob_phone : Phone of the first agent (Bob)}
23
{alice_phone : Phone of the secondary agent (Alice)}';
24
25
/**
26
* The console command description.
27
*
28
* @var string
29
*/
30
protected $description = 'Creates a Twilio workspace for 2 call agents';
31
32
private $_twilioClient;
33
34
/**
35
* Create a new command instance.
36
*/
37
public function __construct(Client $twilioClient)
38
{
39
parent::__construct();
40
$this->_twilioClient = $twilioClient;
41
}
42
43
/**
44
* Execute the console command.
45
*
46
* @return mixed
47
*/
48
public function handle()
49
{
50
$this->info("Create workspace.");
51
$this->line("- Server: \t{$this->argument('host')}");
52
$this->line("- Bob phone: \t{$this->argument('bob_phone')}");
53
$this->line("- Alice phone: \t{$this->argument('alice_phone')}");
54
55
//Get the configuration
56
$workspaceConfig = $this->createWorkspaceConfig();
57
58
//Create the workspace
59
$params = array();
60
$params['friendlyName'] = $workspaceConfig->name;
61
$params['eventCallbackUrl'] = $workspaceConfig->event_callback;
62
$workspace = WorkspaceFacade::createNewWorkspace(
63
$this->_twilioClient->taskrouter,
64
$params
65
);
66
$this->addWorkersToWorkspace($workspace, $workspaceConfig);
67
$this->addTaskQueuesToWorkspace($workspace, $workspaceConfig);
68
$workflow = $this->addWorkflowToWorkspace($workspace, $workspaceConfig);
69
70
$this->printSuccessAndInstructions($workspace, $workflow);
71
}
72
73
/**
74
* Get the json configuration of the Workspace
75
*
76
* @return mixed
77
*/
78
function createWorkspaceConfig()
79
{
80
$fileContent = File::get("resources/workspace.json");
81
$interpolatedContent = sprintfn($fileContent, $this->argument());
82
return json_decode($interpolatedContent);
83
}
84
85
/**
86
* Add workers to workspace
87
*
88
* @param $workspace WorkspaceFacade
89
* @param $workspaceConfig string with Json
90
*/
91
function addWorkersToWorkspace($workspace, $workspaceConfig)
92
{
93
$this->line("Add Workers.");
94
$idleActivity = $workspace->findActivityByName("Idle")
95
or die("The activity 'Idle' was not found. Workers cannot be added.");
96
foreach ($workspaceConfig->workers as $workerJson) {
97
$params = array();
98
$params['friendlyName'] = $workerJson->name;
99
$params['activitySid'] = $idleActivity->sid;
100
$params['attributes'] = json_encode($workerJson->attributes);
101
$workspace->addWorker($params);
102
}
103
}
104
105
/**
106
* Add the Task Queues to the workspace
107
*
108
* @param $workspace WorkspaceFacade
109
* @param $workspaceConfig string with Json
110
*/
111
function addTaskQueuesToWorkspace($workspace, $workspaceConfig)
112
{
113
$this->line("Add Task Queues.");
114
$reservedActivity = $workspace->findActivityByName("Reserved");
115
$assignmentActivity = $workspace->findActivityByName("Busy");
116
foreach ($workspaceConfig->task_queues as $taskQueueJson) {
117
$params = array();
118
$params['friendlyName'] = $taskQueueJson->name;
119
$params['targetWorkers'] = $taskQueueJson->targetWorkers;
120
$params['reservationActivitySid'] = $reservedActivity->sid;
121
$params['assignmentActivitySid'] = $assignmentActivity->sid;
122
$workspace->addTaskQueue($params);
123
}
124
}
125
126
/**
127
* Create and configure the workflow to use in the workspace
128
*
129
* @param $workspace WorkspaceFacade
130
* @param $workspaceConfig string with Json
131
*
132
* @return object with added workflow
133
*/
134
function addWorkflowToWorkspace($workspace, $workspaceConfig)
135
{
136
$this->line("Add Worflow.");
137
$workflowJson = $workspaceConfig->workflow;
138
$params = array();
139
$params['friendlyName'] = $workflowJson->name;
140
$params['assignmentCallbackUrl'] = $workflowJson->callback;
141
$params['taskReservationTimeout'] = $workflowJson->timeout;
142
$params['configuration'] = $this->createWorkFlowJsonConfig(
143
$workspace,
144
$workflowJson
145
);
146
return $workspace->addWorkflow($params);
147
}
148
149
/**
150
* Create the workflow configuration in json format
151
*
152
* @param $workspace
153
* @param $workspaceConfig
154
*
155
* @return string configuration of workflow in json format
156
*/
157
function createWorkFlowJsonConfig($workspace, $workspaceConfig)
158
{
159
$params = array();
160
$defaultTaskQueue = $workspace->findTaskQueueByName("Default") or die(
161
"The 'Default' task queue was not found. The Workflow cannot be created."
162
);
163
$smsTaskQueue = $workspace->findTaskQueueByName("SMS") or die(
164
"The 'SMS' task queue was not found. The Workflow cannot be created."
165
);
166
$voiceTaskQueue = $workspace->findTaskQueueByName("Voice") or die(
167
"The 'Voice' task queue was not found. The Workflow cannot be created."
168
);
169
170
$params["default_task_queue_sid"] = $defaultTaskQueue->sid;
171
$params["sms_task_queue_sid"] = $smsTaskQueue->sid;
172
$params["voice_task_queue_sid"] = $voiceTaskQueue->sid;
173
174
$fileContent = File::get("resources/workflow.json");
175
$interpolatedContent = sprintfn($fileContent, $params);
176
return $interpolatedContent;
177
}
178
179
/**
180
* Prints the message indicating the workspace was successfully created and
181
* shows the commands to export the workspace variables into the environment.
182
*
183
* @param $workspace
184
* @param $workflow
185
*/
186
function printSuccessAndInstructions($workspace, $workflow)
187
{
188
$idleActivity = $workspace->findActivityByName("Idle")
189
or die("Somehow the activity 'Idle' was not found.");
190
$successMsg = "Workspace \"{$workspace->friendlyName}\"" .
191
" was created successfully.";
192
$this->printTitle($successMsg);
193
$this->line(
194
"The following variables will be set automatically."
195
);
196
$encondedWorkersPhone = http_build_query($workspace->getWorkerPhones());
197
$envVars = [
198
"WORKFLOW_SID" => $workflow->sid,
199
"POST_WORK_ACTIVITY_SID" => $idleActivity->sid,
200
"WORKSPACE_SID" => $workspace->sid,
201
"PHONE_TO_WORKER" => $encondedWorkersPhone
202
];
203
updateEnv($envVars);
204
foreach ($envVars as $key => $value) {
205
$this->warn("export $key=$value");
206
}
207
}
208
209
/**
210
* Prints a text separated up and doNwn by a token based line, usually "*"
211
*/
212
function printTitle($text)
213
{
214
$lineLength = strlen($text) + 2;
215
$this->line(str_repeat("*", $lineLength));
216
$this->line(" $text ");
217
$this->line(str_repeat("*", $lineLength));
218
}
219
}

After creating our workers, let's set up the Task Queues.


Next, we set up the Task Queues. Each with a name and a targetWorkers property, which is an expression to match Workers. Our Task Queues are:

  1. SMS - Will target Workers specialized in Programmable SMS, such as Bob, using the expression "products HAS \"ProgrammableSMS\"" .
  2. Voice - Will do the same for Programmable Voice Workers, such as Alice, using the expression "products HAS \"ProgrammableVoice\"" .
  3. All - This queue targets all users and can be used when there are no specialist around for the chosen product. We can use the "1==1" expression here.

app/Console/Commands/CreateWorkspace.php

1
<?php
2
3
namespace App\Console\Commands;
4
5
use App\TaskRouter\WorkspaceFacade;
6
use Illuminate\Console\Command;
7
use Illuminate\Support\Facades\File;
8
use TaskRouter_Services_Twilio;
9
use Twilio\Rest\Client;
10
use Twilio\Rest\Taskrouter;
11
use WorkflowRuleTarget;
12
13
class CreateWorkspace extends Command
14
{
15
/**
16
* The name and signature of the console command.
17
*
18
* @var string
19
*/
20
protected $signature = 'workspace:create
21
{host : Server hostname in Internet}
22
{bob_phone : Phone of the first agent (Bob)}
23
{alice_phone : Phone of the secondary agent (Alice)}';
24
25
/**
26
* The console command description.
27
*
28
* @var string
29
*/
30
protected $description = 'Creates a Twilio workspace for 2 call agents';
31
32
private $_twilioClient;
33
34
/**
35
* Create a new command instance.
36
*/
37
public function __construct(Client $twilioClient)
38
{
39
parent::__construct();
40
$this->_twilioClient = $twilioClient;
41
}
42
43
/**
44
* Execute the console command.
45
*
46
* @return mixed
47
*/
48
public function handle()
49
{
50
$this->info("Create workspace.");
51
$this->line("- Server: \t{$this->argument('host')}");
52
$this->line("- Bob phone: \t{$this->argument('bob_phone')}");
53
$this->line("- Alice phone: \t{$this->argument('alice_phone')}");
54
55
//Get the configuration
56
$workspaceConfig = $this->createWorkspaceConfig();
57
58
//Create the workspace
59
$params = array();
60
$params['friendlyName'] = $workspaceConfig->name;
61
$params['eventCallbackUrl'] = $workspaceConfig->event_callback;
62
$workspace = WorkspaceFacade::createNewWorkspace(
63
$this->_twilioClient->taskrouter,
64
$params
65
);
66
$this->addWorkersToWorkspace($workspace, $workspaceConfig);
67
$this->addTaskQueuesToWorkspace($workspace, $workspaceConfig);
68
$workflow = $this->addWorkflowToWorkspace($workspace, $workspaceConfig);
69
70
$this->printSuccessAndInstructions($workspace, $workflow);
71
}
72
73
/**
74
* Get the json configuration of the Workspace
75
*
76
* @return mixed
77
*/
78
function createWorkspaceConfig()
79
{
80
$fileContent = File::get("resources/workspace.json");
81
$interpolatedContent = sprintfn($fileContent, $this->argument());
82
return json_decode($interpolatedContent);
83
}
84
85
/**
86
* Add workers to workspace
87
*
88
* @param $workspace WorkspaceFacade
89
* @param $workspaceConfig string with Json
90
*/
91
function addWorkersToWorkspace($workspace, $workspaceConfig)
92
{
93
$this->line("Add Workers.");
94
$idleActivity = $workspace->findActivityByName("Idle")
95
or die("The activity 'Idle' was not found. Workers cannot be added.");
96
foreach ($workspaceConfig->workers as $workerJson) {
97
$params = array();
98
$params['friendlyName'] = $workerJson->name;
99
$params['activitySid'] = $idleActivity->sid;
100
$params['attributes'] = json_encode($workerJson->attributes);
101
$workspace->addWorker($params);
102
}
103
}
104
105
/**
106
* Add the Task Queues to the workspace
107
*
108
* @param $workspace WorkspaceFacade
109
* @param $workspaceConfig string with Json
110
*/
111
function addTaskQueuesToWorkspace($workspace, $workspaceConfig)
112
{
113
$this->line("Add Task Queues.");
114
$reservedActivity = $workspace->findActivityByName("Reserved");
115
$assignmentActivity = $workspace->findActivityByName("Busy");
116
foreach ($workspaceConfig->task_queues as $taskQueueJson) {
117
$params = array();
118
$params['friendlyName'] = $taskQueueJson->name;
119
$params['targetWorkers'] = $taskQueueJson->targetWorkers;
120
$params['reservationActivitySid'] = $reservedActivity->sid;
121
$params['assignmentActivitySid'] = $assignmentActivity->sid;
122
$workspace->addTaskQueue($params);
123
}
124
}
125
126
/**
127
* Create and configure the workflow to use in the workspace
128
*
129
* @param $workspace WorkspaceFacade
130
* @param $workspaceConfig string with Json
131
*
132
* @return object with added workflow
133
*/
134
function addWorkflowToWorkspace($workspace, $workspaceConfig)
135
{
136
$this->line("Add Worflow.");
137
$workflowJson = $workspaceConfig->workflow;
138
$params = array();
139
$params['friendlyName'] = $workflowJson->name;
140
$params['assignmentCallbackUrl'] = $workflowJson->callback;
141
$params['taskReservationTimeout'] = $workflowJson->timeout;
142
$params['configuration'] = $this->createWorkFlowJsonConfig(
143
$workspace,
144
$workflowJson
145
);
146
return $workspace->addWorkflow($params);
147
}
148
149
/**
150
* Create the workflow configuration in json format
151
*
152
* @param $workspace
153
* @param $workspaceConfig
154
*
155
* @return string configuration of workflow in json format
156
*/
157
function createWorkFlowJsonConfig($workspace, $workspaceConfig)
158
{
159
$params = array();
160
$defaultTaskQueue = $workspace->findTaskQueueByName("Default") or die(
161
"The 'Default' task queue was not found. The Workflow cannot be created."
162
);
163
$smsTaskQueue = $workspace->findTaskQueueByName("SMS") or die(
164
"The 'SMS' task queue was not found. The Workflow cannot be created."
165
);
166
$voiceTaskQueue = $workspace->findTaskQueueByName("Voice") or die(
167
"The 'Voice' task queue was not found. The Workflow cannot be created."
168
);
169
170
$params["default_task_queue_sid"] = $defaultTaskQueue->sid;
171
$params["sms_task_queue_sid"] = $smsTaskQueue->sid;
172
$params["voice_task_queue_sid"] = $voiceTaskQueue->sid;
173
174
$fileContent = File::get("resources/workflow.json");
175
$interpolatedContent = sprintfn($fileContent, $params);
176
return $interpolatedContent;
177
}
178
179
/**
180
* Prints the message indicating the workspace was successfully created and
181
* shows the commands to export the workspace variables into the environment.
182
*
183
* @param $workspace
184
* @param $workflow
185
*/
186
function printSuccessAndInstructions($workspace, $workflow)
187
{
188
$idleActivity = $workspace->findActivityByName("Idle")
189
or die("Somehow the activity 'Idle' was not found.");
190
$successMsg = "Workspace \"{$workspace->friendlyName}\"" .
191
" was created successfully.";
192
$this->printTitle($successMsg);
193
$this->line(
194
"The following variables will be set automatically."
195
);
196
$encondedWorkersPhone = http_build_query($workspace->getWorkerPhones());
197
$envVars = [
198
"WORKFLOW_SID" => $workflow->sid,
199
"POST_WORK_ACTIVITY_SID" => $idleActivity->sid,
200
"WORKSPACE_SID" => $workspace->sid,
201
"PHONE_TO_WORKER" => $encondedWorkersPhone
202
];
203
updateEnv($envVars);
204
foreach ($envVars as $key => $value) {
205
$this->warn("export $key=$value");
206
}
207
}
208
209
/**
210
* Prints a text separated up and doNwn by a token based line, usually "*"
211
*/
212
function printTitle($text)
213
{
214
$lineLength = strlen($text) + 2;
215
$this->line(str_repeat("*", $lineLength));
216
$this->line(" $text ");
217
$this->line(str_repeat("*", $lineLength));
218
}
219
}

We have a Workspace, Workers and Task Queues... what's left? A Workflow. Let's see how to create one next!


Finally, we set up the Workflow using the following parameters:

  1. friendlyName as the name of a Workflow.
  2. assignmentCallbackUrl as the public URL where a request will be made when this Workflow assigns a Task to a Worker. We will learn how to implement it on the next steps.
  3. taskReservationTimeout as the maximum time we want to wait until a Worker handles a Task.
  4. configuration which is a set of rules for placing Task into Task Queues. The routing configuration will take a Task's attribute and match this with Task Queues. This application's Workflow rules are defined as:

    • selected_product=="ProgrammableSMS" expression for SMS Task Queue. This expression will match any Task with ProgrammableSMS as the selected_product attribute.
    • selected_product=="ProgrammableVoice expression for Voice Task Queue.

app/Console/Commands/CreateWorkspace.php

1
<?php
2
3
namespace App\Console\Commands;
4
5
use App\TaskRouter\WorkspaceFacade;
6
use Illuminate\Console\Command;
7
use Illuminate\Support\Facades\File;
8
use TaskRouter_Services_Twilio;
9
use Twilio\Rest\Client;
10
use Twilio\Rest\Taskrouter;
11
use WorkflowRuleTarget;
12
13
class CreateWorkspace extends Command
14
{
15
/**
16
* The name and signature of the console command.
17
*
18
* @var string
19
*/
20
protected $signature = 'workspace:create
21
{host : Server hostname in Internet}
22
{bob_phone : Phone of the first agent (Bob)}
23
{alice_phone : Phone of the secondary agent (Alice)}';
24
25
/**
26
* The console command description.
27
*
28
* @var string
29
*/
30
protected $description = 'Creates a Twilio workspace for 2 call agents';
31
32
private $_twilioClient;
33
34
/**
35
* Create a new command instance.
36
*/
37
public function __construct(Client $twilioClient)
38
{
39
parent::__construct();
40
$this->_twilioClient = $twilioClient;
41
}
42
43
/**
44
* Execute the console command.
45
*
46
* @return mixed
47
*/
48
public function handle()
49
{
50
$this->info("Create workspace.");
51
$this->line("- Server: \t{$this->argument('host')}");
52
$this->line("- Bob phone: \t{$this->argument('bob_phone')}");
53
$this->line("- Alice phone: \t{$this->argument('alice_phone')}");
54
55
//Get the configuration
56
$workspaceConfig = $this->createWorkspaceConfig();
57
58
//Create the workspace
59
$params = array();
60
$params['friendlyName'] = $workspaceConfig->name;
61
$params['eventCallbackUrl'] = $workspaceConfig->event_callback;
62
$workspace = WorkspaceFacade::createNewWorkspace(
63
$this->_twilioClient->taskrouter,
64
$params
65
);
66
$this->addWorkersToWorkspace($workspace, $workspaceConfig);
67
$this->addTaskQueuesToWorkspace($workspace, $workspaceConfig);
68
$workflow = $this->addWorkflowToWorkspace($workspace, $workspaceConfig);
69
70
$this->printSuccessAndInstructions($workspace, $workflow);
71
}
72
73
/**
74
* Get the json configuration of the Workspace
75
*
76
* @return mixed
77
*/
78
function createWorkspaceConfig()
79
{
80
$fileContent = File::get("resources/workspace.json");
81
$interpolatedContent = sprintfn($fileContent, $this->argument());
82
return json_decode($interpolatedContent);
83
}
84
85
/**
86
* Add workers to workspace
87
*
88
* @param $workspace WorkspaceFacade
89
* @param $workspaceConfig string with Json
90
*/
91
function addWorkersToWorkspace($workspace, $workspaceConfig)
92
{
93
$this->line("Add Workers.");
94
$idleActivity = $workspace->findActivityByName("Idle")
95
or die("The activity 'Idle' was not found. Workers cannot be added.");
96
foreach ($workspaceConfig->workers as $workerJson) {
97
$params = array();
98
$params['friendlyName'] = $workerJson->name;
99
$params['activitySid'] = $idleActivity->sid;
100
$params['attributes'] = json_encode($workerJson->attributes);
101
$workspace->addWorker($params);
102
}
103
}
104
105
/**
106
* Add the Task Queues to the workspace
107
*
108
* @param $workspace WorkspaceFacade
109
* @param $workspaceConfig string with Json
110
*/
111
function addTaskQueuesToWorkspace($workspace, $workspaceConfig)
112
{
113
$this->line("Add Task Queues.");
114
$reservedActivity = $workspace->findActivityByName("Reserved");
115
$assignmentActivity = $workspace->findActivityByName("Busy");
116
foreach ($workspaceConfig->task_queues as $taskQueueJson) {
117
$params = array();
118
$params['friendlyName'] = $taskQueueJson->name;
119
$params['targetWorkers'] = $taskQueueJson->targetWorkers;
120
$params['reservationActivitySid'] = $reservedActivity->sid;
121
$params['assignmentActivitySid'] = $assignmentActivity->sid;
122
$workspace->addTaskQueue($params);
123
}
124
}
125
126
/**
127
* Create and configure the workflow to use in the workspace
128
*
129
* @param $workspace WorkspaceFacade
130
* @param $workspaceConfig string with Json
131
*
132
* @return object with added workflow
133
*/
134
function addWorkflowToWorkspace($workspace, $workspaceConfig)
135
{
136
$this->line("Add Worflow.");
137
$workflowJson = $workspaceConfig->workflow;
138
$params = array();
139
$params['friendlyName'] = $workflowJson->name;
140
$params['assignmentCallbackUrl'] = $workflowJson->callback;
141
$params['taskReservationTimeout'] = $workflowJson->timeout;
142
$params['configuration'] = $this->createWorkFlowJsonConfig(
143
$workspace,
144
$workflowJson
145
);
146
return $workspace->addWorkflow($params);
147
}
148
149
/**
150
* Create the workflow configuration in json format
151
*
152
* @param $workspace
153
* @param $workspaceConfig
154
*
155
* @return string configuration of workflow in json format
156
*/
157
function createWorkFlowJsonConfig($workspace, $workspaceConfig)
158
{
159
$params = array();
160
$defaultTaskQueue = $workspace->findTaskQueueByName("Default") or die(
161
"The 'Default' task queue was not found. The Workflow cannot be created."
162
);
163
$smsTaskQueue = $workspace->findTaskQueueByName("SMS") or die(
164
"The 'SMS' task queue was not found. The Workflow cannot be created."
165
);
166
$voiceTaskQueue = $workspace->findTaskQueueByName("Voice") or die(
167
"The 'Voice' task queue was not found. The Workflow cannot be created."
168
);
169
170
$params["default_task_queue_sid"] = $defaultTaskQueue->sid;
171
$params["sms_task_queue_sid"] = $smsTaskQueue->sid;
172
$params["voice_task_queue_sid"] = $voiceTaskQueue->sid;
173
174
$fileContent = File::get("resources/workflow.json");
175
$interpolatedContent = sprintfn($fileContent, $params);
176
return $interpolatedContent;
177
}
178
179
/**
180
* Prints the message indicating the workspace was successfully created and
181
* shows the commands to export the workspace variables into the environment.
182
*
183
* @param $workspace
184
* @param $workflow
185
*/
186
function printSuccessAndInstructions($workspace, $workflow)
187
{
188
$idleActivity = $workspace->findActivityByName("Idle")
189
or die("Somehow the activity 'Idle' was not found.");
190
$successMsg = "Workspace \"{$workspace->friendlyName}\"" .
191
" was created successfully.";
192
$this->printTitle($successMsg);
193
$this->line(
194
"The following variables will be set automatically."
195
);
196
$encondedWorkersPhone = http_build_query($workspace->getWorkerPhones());
197
$envVars = [
198
"WORKFLOW_SID" => $workflow->sid,
199
"POST_WORK_ACTIVITY_SID" => $idleActivity->sid,
200
"WORKSPACE_SID" => $workspace->sid,
201
"PHONE_TO_WORKER" => $encondedWorkersPhone
202
];
203
updateEnv($envVars);
204
foreach ($envVars as $key => $value) {
205
$this->warn("export $key=$value");
206
}
207
}
208
209
/**
210
* Prints a text separated up and doNwn by a token based line, usually "*"
211
*/
212
function printTitle($text)
213
{
214
$lineLength = strlen($text) + 2;
215
$this->line(str_repeat("*", $lineLength));
216
$this->line(" $text ");
217
$this->line(str_repeat("*", $lineLength));
218
}
219
}

Our workspace is completely setup. Now it's time to see how we use it to route calls.


Handle Twilio's Request

handle-twilios-request page anchor

Right after receiving a call, Twilio will send a request to the URL specified on the number's configuration.

The endpoint will then process the request and generate a TwiML response. We'll use the Say verb to give the user product alternatives, and a key they can press in order to select one. The Gather verb allows us to capture the user's key press.

app/Http/Controllers/IncomingCallController.php

1
<?php
2
3
namespace App\Http\Controllers;
4
5
use App\Http\Requests;
6
use Twilio\Twiml;
7
8
/**
9
* Class IncomingCallController
10
*
11
* @package App\Http\Controllers
12
*/
13
class IncomingCallController extends Controller
14
{
15
16
public function respondToUser()
17
{
18
$response = new Twiml();
19
20
$params = array();
21
$params['action'] = '/call/enqueue';
22
$params['numDigits'] = 1;
23
$params['timeout'] = 10;
24
$params['method'] = "POST";
25
26
$params = $response->gather($params);
27
$params->say(
28
'For Programmable SMS, press one. For Voice, press any other key.'
29
);
30
31
return response($response)->header('Content-Type', 'text/xml');
32
}
33
}

We just asked the caller to choose a product, next we will use their choice to create the appropriate Task.


This is the endpoint set as the action URL on the Gather verb on the previous step. A request is made to this endpoint when the user presses a key during the call. This request has a Digits parameter that holds the pressed keys. A Task will be created based on the pressed digit with the selected_product as an attribute. The Workflow will take this Task's attributes and match them with the configured expressions in order to find a corresponding Task Queue, so an appropriate available Worker can be assigned to handle it.

We use the Enqueue verb with a workflowSid attribute to integrate with TaskRouter. Then the voice call will be put on hold while TaskRouter tries to find an available Worker to handle this Task.

app/Http/Controllers/EnqueueCallController.php

1
<?php
2
3
namespace App\Http\Controllers;
4
5
use Illuminate\Http\Request;
6
use Twilio\Twiml;
7
8
9
/**
10
* Class EnqueueCallController
11
*
12
* @package App\Http\Controllers
13
*/
14
class EnqueueCallController extends Controller
15
{
16
17
public function enqueueCall(Request $request)
18
{
19
$workflowSid = config('services.twilio')['workflowSid']
20
or die("WORKFLOW_SID is not set in the system environment");
21
22
$selectProductInstruction = new \StdClass();
23
$selectProductInstruction->selected_product
24
= $this->_getSelectedProduct($request);
25
26
$response = new Twiml();
27
$enqueue = $response->enqueue(['workflowSid' => $workflowSid]);
28
$enqueue->task(json_encode($selectProductInstruction));
29
30
return response($response)->header('Content-Type', 'text/xml');
31
}
32
33
/**
34
* Gets the wanted product upon the user's input
35
*
36
* @param $request Request of the user
37
*
38
* @return string selected product: "ProgrammableSMS" or "ProgrammableVoice"
39
*/
40
private function _getSelectedProduct($request)
41
{
42
return $request->input("Digits") == 1
43
? "ProgrammableSMS"
44
: "ProgrammableVoice";
45
}
46
}

After sending a Task to Twilio, let's see how we tell TaskRouter which Worker to use to execute that task.


When TaskRouter selects a Worker, it does the following:

  1. The Task's Assignment Status is set to reserved .
  2. A Reservation instance is generated, linking the Task to the selected Worker.
  3. At the same time the Reservation is created, a POST request is made to the Workflow's AssignmentCallbackURL, which was configured using the Artisan command workspace:create(link takes you to an external page) . This request includes the full details of the Task, the selected Worker, and the Reservation.

Handling this Assignment Callback is a key component of building a TaskRouter application as we can instruct how the Worker will handle a Task. We could send a text, email, push notifications or make a call.

Since we created this Task during a voice call with an Enqueue verb, let's instruct TaskRouter to dequeue the call and dial a Worker. If we do not specify a to parameter with a phone number, TaskRouter will pick the Worker's contact_uri attribute.

We also send a post_work_activity_sid which will tell TaskRouter which Activity to assign this worker after the call ends.

app/Http/Controllers/CallbackController.php

1
<?php
2
3
namespace App\Http\Controllers;
4
5
use App\Exceptions\TaskRouterException;
6
use App\MissedCall;
7
use Illuminate\Http\Request;
8
use Illuminate\Support\Facades\Log;
9
use Twilio\Rest\Client;
10
11
/**
12
* Class CallbackController Handles callbacks
13
*
14
* @package App\Http\Controllers
15
*/
16
class CallbackController extends Controller
17
{
18
/**
19
* Callback endpoint for Task assignments
20
*/
21
public function assignTask()
22
{
23
$dequeueInstructionModel = new \stdClass;
24
$dequeueInstructionModel->instruction = "dequeue";
25
$dequeueInstructionModel->post_work_activity_sid
26
= config('services.twilio')['postWorkActivitySid'];
27
28
$dequeueInstructionJson = json_encode($dequeueInstructionModel);
29
30
return response($dequeueInstructionJson)
31
->header('Content-Type', 'application/json');
32
}
33
34
/**
35
* Events callback for missed calls
36
*
37
* @param $request Request with the input data
38
* @param $twilioClient Client of the Twilio Rest Api
39
*/
40
public function handleEvent(Request $request, Client $twilioClient)
41
{
42
$missedCallEvents = config('services.twilio')['missedCallEvents'];
43
44
$eventTypeName = $request->input("EventType");
45
46
if (in_array($eventTypeName, $missedCallEvents)) {
47
$taskAttr = $this->parseAttributes("TaskAttributes", $request);
48
if (!empty($taskAttr)) {
49
$this->addMissingCall($taskAttr);
50
51
$message = config('services.twilio')["leaveMessage"];
52
return $this->redirectToVoiceMail(
53
$twilioClient, $taskAttr->call_sid, $message
54
);
55
}
56
} else if ('worker.activity.update' === $eventTypeName) {
57
$workerActivityName = $request->input("WorkerActivityName");
58
if ($workerActivityName === "Offline") {
59
$workerAttr = $this->parseAttributes("WorkerAttributes", $request);
60
$this->notifyOfflineStatusToWorker(
61
$workerAttr->contact_uri, $twilioClient
62
);
63
}
64
}
65
}
66
67
protected function parseAttributes($name, $request)
68
{
69
$attrJson = $request->input($name);
70
return json_decode($attrJson);
71
}
72
73
protected function addMissingCall($task)
74
{
75
$missedCall = new MissedCall(
76
[
77
"selected_product" => $task->selected_product,
78
"phone_number" => $task->from
79
]
80
);
81
$missedCall->save();
82
Log::info("New missed call added: $missedCall");
83
}
84
85
protected function redirectToVoiceMail($twilioClient, $callSid, $message)
86
{
87
$missedCallsEmail = config('services.twilio')['missedCallsEmail']
88
or die("MISSED_CALLS_EMAIL_ADDRESS is not set in the environment");
89
90
$call = $twilioClient->calls->getContext($callSid);
91
if (!$call) {
92
throw new TaskRouterException("The specified call does not exist");
93
}
94
95
$encodedMsg = urlencode($message);
96
$twimletUrl = "http://twimlets.com/voicemail?Email=$missedCallsEmail" .
97
"&Message=$encodedMsg";
98
$call->update(["url" => $twimletUrl, "method" => "POST"]);
99
}
100
101
protected function notifyOfflineStatusToWorker($workerPhone, $twilioClient)
102
{
103
$twilioNumber = config('services.twilio')['number']
104
or die("TWILIO_NUMBER is not set in the system environment");
105
106
$params = [
107
"from" => $twilioNumber,
108
"body" => config('services.twilio')["offlineMessage"]
109
];
110
111
$twilioClient->account->messages->create(
112
$workerPhone,
113
$params
114
);
115
}
116
117
}

Now that our Tasks are routed properly, let's deal with missed calls in the next step.


This endpoint will be called after each TaskRouter Event is triggered. In our application, we are trying to collect missed calls, so we would like to handle the workflow.timeout event. This event is triggered when the Task waits more than the limit set on Workflow Configuration-- or rather when no worker is available.

Here we use TwilioRestClient to route this call to a Voicemail Twimlet(link takes you to an external page). Twimlets are tiny web applications for voice. This one will generate a TwiML response using Say verb and record a message using Record verb. The recorded message will then be transcribed and sent to the email address configured.

We are also listening for task.canceled. This is triggered when the customer hangs up before being assigned to an agent, therefore canceling the task. Capturing this event allows us to collect the information from the customers that hang up before the Workflow times out.

app/Http/Controllers/CallbackController.php

1
<?php
2
3
namespace App\Http\Controllers;
4
5
use App\Exceptions\TaskRouterException;
6
use App\MissedCall;
7
use Illuminate\Http\Request;
8
use Illuminate\Support\Facades\Log;
9
use Twilio\Rest\Client;
10
11
/**
12
* Class CallbackController Handles callbacks
13
*
14
* @package App\Http\Controllers
15
*/
16
class CallbackController extends Controller
17
{
18
/**
19
* Callback endpoint for Task assignments
20
*/
21
public function assignTask()
22
{
23
$dequeueInstructionModel = new \stdClass;
24
$dequeueInstructionModel->instruction = "dequeue";
25
$dequeueInstructionModel->post_work_activity_sid
26
= config('services.twilio')['postWorkActivitySid'];
27
28
$dequeueInstructionJson = json_encode($dequeueInstructionModel);
29
30
return response($dequeueInstructionJson)
31
->header('Content-Type', 'application/json');
32
}
33
34
/**
35
* Events callback for missed calls
36
*
37
* @param $request Request with the input data
38
* @param $twilioClient Client of the Twilio Rest Api
39
*/
40
public function handleEvent(Request $request, Client $twilioClient)
41
{
42
$missedCallEvents = config('services.twilio')['missedCallEvents'];
43
44
$eventTypeName = $request->input("EventType");
45
46
if (in_array($eventTypeName, $missedCallEvents)) {
47
$taskAttr = $this->parseAttributes("TaskAttributes", $request);
48
if (!empty($taskAttr)) {
49
$this->addMissingCall($taskAttr);
50
51
$message = config('services.twilio')["leaveMessage"];
52
return $this->redirectToVoiceMail(
53
$twilioClient, $taskAttr->call_sid, $message
54
);
55
}
56
} else if ('worker.activity.update' === $eventTypeName) {
57
$workerActivityName = $request->input("WorkerActivityName");
58
if ($workerActivityName === "Offline") {
59
$workerAttr = $this->parseAttributes("WorkerAttributes", $request);
60
$this->notifyOfflineStatusToWorker(
61
$workerAttr->contact_uri, $twilioClient
62
);
63
}
64
}
65
}
66
67
protected function parseAttributes($name, $request)
68
{
69
$attrJson = $request->input($name);
70
return json_decode($attrJson);
71
}
72
73
protected function addMissingCall($task)
74
{
75
$missedCall = new MissedCall(
76
[
77
"selected_product" => $task->selected_product,
78
"phone_number" => $task->from
79
]
80
);
81
$missedCall->save();
82
Log::info("New missed call added: $missedCall");
83
}
84
85
protected function redirectToVoiceMail($twilioClient, $callSid, $message)
86
{
87
$missedCallsEmail = config('services.twilio')['missedCallsEmail']
88
or die("MISSED_CALLS_EMAIL_ADDRESS is not set in the environment");
89
90
$call = $twilioClient->calls->getContext($callSid);
91
if (!$call) {
92
throw new TaskRouterException("The specified call does not exist");
93
}
94
95
$encodedMsg = urlencode($message);
96
$twimletUrl = "http://twimlets.com/voicemail?Email=$missedCallsEmail" .
97
"&Message=$encodedMsg";
98
$call->update(["url" => $twimletUrl, "method" => "POST"]);
99
}
100
101
protected function notifyOfflineStatusToWorker($workerPhone, $twilioClient)
102
{
103
$twilioNumber = config('services.twilio')['number']
104
or die("TWILIO_NUMBER is not set in the system environment");
105
106
$params = [
107
"from" => $twilioNumber,
108
"body" => config('services.twilio')["offlineMessage"]
109
];
110
111
$twilioClient->account->messages->create(
112
$workerPhone,
113
$params
114
);
115
}
116
117
}

Most of the features of our application are implemented. The last piece is allowing the Workers to change their availability status. Let's see how to do that next.


Change a Worker's Activity

change-a-workers-activity page anchor

We have created this endpoint, so a worker can send an SMS message to the support line with the command "On" or "Off" to change their availability status.

This is important as a worker's activity will change to Offline when they miss a call. When this happens, they receive an SMS letting them know that their activity has changed, and that they can reply with the On command to make themselves available for incoming calls again.

app/Http/Controllers/MessageController.php

1
<?php
2
3
namespace App\Http\Controllers;
4
5
use App\Exceptions\TaskRouterException;
6
use Illuminate\Http\Request;
7
use App\TaskRouter\WorkspaceFacade;
8
use Twilio\Twiml;
9
10
class MessageController extends Controller
11
{
12
13
public function handleIncomingMessage(
14
Request $request, WorkspaceFacade $workspace
15
) {
16
$cmd = strtolower($request->input("Body"));
17
$fromNumber = $request->input("From");
18
$newWorkerStatus = ($cmd === "off") ? "Offline" : "Idle";
19
20
$response = new Twiml();
21
22
try {
23
$worker = $this->getWorkerByPhone($fromNumber, $workspace);
24
$this->updateWorkerStatus($worker, $newWorkerStatus, $workspace);
25
26
$response->sms("Your status has changed to {$newWorkerStatus}");
27
28
} catch (TaskRouterException $e) {
29
$response->sms($e->getMessage());
30
}
31
32
return response($response)->header('Content-Type', 'text/xml');
33
}
34
35
function updateWorkerStatus($worker, $status, $workspace)
36
{
37
$wantedActivity = $workspace->findActivityByName($status);
38
$workspace->updateWorkerActivity($worker, $wantedActivity->sid);
39
}
40
41
protected function getWorkerByPhone($phone, $workspace)
42
{
43
$phoneToWorkerStr = config('services.twilio')['phoneToWorker'];
44
parse_str($phoneToWorkerStr, $phoneToWorkerArray);
45
if (empty($phoneToWorkerArray[$phone])) {
46
throw new TaskRouterException("You are not a valid worker");
47
}
48
return $workspace->findWorkerBySid($phoneToWorkerArray[$phone]);
49
}
50
}

Congratulations! You finished this tutorial. As you can see, using Twilio's TaskRouter is quite simple.


If you're a PHP developer working with Twilio, you might also enjoy these tutorials:

Automated-Survey(link takes you to an external page)

Instantly collect structured data from your users with a survey conducted over a call or SMS text messages. Let's get started!

ETA-Notifications(link takes you to an external page)

Learn how to implement ETA Notifications using Laravel and Twilio.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.