Twilio attach statusCallbackEvent and url on an incoming call - twilio

I am trying to forward a call to user phone if his twilio phone is called.
$usr_ph = 'xxxxxxxxxx'; // get user personal phone from database
$twiml = new Twiml();
$twiml->dial($usr_ph);
return $twiml;
The above code works fine , I need to get the call minutes. So I added status callback url to dial . But its not sending me the any status event
Below is the code I have
$data = array ('statusCallbackEvent' => array('completed'),
statusCallback' => "https://mywebsite.com/get_Call_outcome",
'statusCallbackMethod' => 'POST'
);
$twiml = new Twiml();
$twiml->dial($usr_ph, json_encode($data));
return $twiml;
I did tried :
$twiml = new Twiml();
$twiml->dial($usr_ph, [
'statusCallbackEvent' => array('completed'),
'statusCallback' => "https://mywebsite.com/get_Call_outcome",
'statusCallbackMethod' => 'POST'
]);
return $twiml;
But then I get the error message as
SimpleXMLElement::addAttribute() expects parameter 2 to be string, array given
Not sure , but I think I need to add statusCallbackEvent on the original call which was made on the twilio phone.
Edit:
Now I tried updating the incoming call by adding statusCallbackEvent, but its still not sending any Event.
$twi = new Client($twilio->sid, $twilio->token);
$call = $twi->calls($request->input('CallSid'))
->update(array ('statusCallbackEvent' => array('completed'),
'statusCallback' =>"www.mywebsite.com/get_Call_outcome",
'statusCallbackMethod' => 'POST'
));

The statusCallback is part of the Number noun, not Dial verb. You can find more details below. See if that addresses the issue.
Twilio Voice:
https://www.twilio.com/docs/voice/twiml/number

Try this Set Status Codes on Number Noune
$dial->number('+14158675310', [
'statusCallbackEvent' => 'initiated ringing answered completed',
'statusCallback' => 'https://myapp.com/calls/events',
'statusCallbackMethod' => 'POST'
]);

Related

Twilio Redirecting the wrong call when using CallSid and trying to update live call

So here's the logic of what I am working on:
Someone calls my Twilio Number I use the dial twiml to forward to a cell phone
I use gather and play a whisper to the operator answering the phone (so his cell phone).
The operator has a choice - press 1 to accept, press 2 (transfers to
a different agent).
step 3 is where I am having trouble I am using the code below:
$call = $twilio->calls($CallSid)
->update([
"method" => "POST",
"url" => "http:www.example.com/directcall.php"
]
);
Here's the problem it is modifying the call but it's redirecting the operators phone number instead of the person who is calling in. So the operator is getting redirected to the other operator and the customer is being hung up on. I tried using the parentcallsid too but that doesn't seem to work either.
Any ideas what I am doing wrong?
so just to be clear I want the flow to work like this:
Customer calls phone number -> redirects to designated operator -> if designated operator presses 2 it redirects the customer to operator 2 and disconnects operator 1 from the call. Is this possible?
Thanks for the help, I greatly appreciate it.
UPDATE PLEASE FIND THE CODE SAMPLES BELOW
Index.php
<?php
include ("config.php");
require_once './vendor/autoload.php';
use Twilio\TwiML\VoiceResponse;
$response = new VoiceResponse();
$twilionumber = ltrim($_POST['To'], '+');
$callernumber=ltrim($_POST['From'], '+');
createCall($phonenumbertouse,$response,$twilionumber);
echo $response;
function createCall($phonenumbertouse,$response,$twilionumber) {
$dial = $response->dial('',['timeout' => '30']);
$dial->number($phonenumbertouse, ['action' => "http://example.com/whisper.php",'method' => 'GET']);
}
WHISPER.PHP
<?php
include ("config.php");
require_once './vendor/autoload.php';
use Twilio\TwiML\VoiceResponse;
$response = new VoiceResponse();
$gather = $response->gather(['action' => "http://example.com/route.php",
'method' => 'GET']);
$gather->say($whisper, ['voice' => 'woman', 'language' => 'en-US']);
echo $response;
?>
route.php
<?php
include ("config.php");
require_once './vendor/autoload.php';
use Twilio\TwiML\VoiceResponse;
use Twilio\Rest\Client;
$response = new VoiceResponse();
$keyedInput=$_REQUEST['Digits'];
$mycallsid=$_REQUEST['ParentCallSid'];
if ($keyedInput == 1){
$response->say('connecting the call');
}
elseif ($keyedInput == 2){
$twilio = new Client($sid, $token);
$call = $twilio->calls($mycallsid)
->update([
"method" => "POST",
"url" => "http://example.com/redirect.php"
]
);
}
elseif ($keyedInput == 3){
$response->say('you selected 3');
}
else {
$response->say('Sorry, I don\'t understand that choice.');
}
echo $response;
?>
**Redirect.php **
<?php
include ("config.php");
require_once './vendor/autoload.php';
use Twilio\TwiML\VoiceResponse;
$response = new VoiceResponse();
$dial = $response->dial('+14151234567',['timeout' => '30']);
echo $response;
?>
Twilio developer evangelist here.
Your issue here is that you are using the wrong CallSid to update.
In this case there are two CallSids at play. When your user dials in to your Twilio number, that call between the user and Twilio has one CallSid. Then, when Twilio creates an outbound call to the operator, that call has a different CallSid.
In your application, when you get the <Gather> response from the operator, the CallSid being sent to your endpoint is the CallSid of the operator's call leg. Instead, you need to find the CallSid of the original call.
You should find that the ParentCallSid parameter is sent to the webhook endpoint as well. That ParentCallSid is the original inbound call's Sid and is what you should use to redirect the caller to another operator.
Edit
OK, so I had a go at building this. I don't normally work in PHP, so I wrote this in Node.js (as Twilio Functions). I got it to work and the answer still seems to me to be "use the ParentCallSid, so hopefully it gives you some idea where you might have gone wrong.
The incoming call
This makes an outbound call to my cell phone number, with a url set to make the whisper to me when I answer the call.
exports.handler = function (context, event, callback) {
const twiml = new Twilio.twiml.VoiceResponse();
const dial = twiml.dial();
dial.number({ url: "/whisper" }, MY_CELL_PHONE_NUMBER);
callback(null, twiml);
};
<Response>
<Dial><Number url="/whisper">MY_CELL_PHONE_NUMBER</Number></Dial>
</Response>
The whisper
This returns a <Gather> spoken to the person answering the cell phone number. It offers a choice, dial "1" to connect or "2" to hang up, triggering the original caller to dial to another number.
exports.handler = function (context, event, callback) {
const twiml = new Twilio.twiml.VoiceResponse();
const gather = twiml.gather({ digits: 1, action: "/after-whisper" });
gather.say("Dial 1 to connect, dial 2 to hang up.");
callback(null, twiml);
};
<Response>
<Gather action="/after-whisper" digits="1">
<Say>Dial 1 to connect, dial 2 to hang up.</Say>
</Gather>
</Response>
The Gather action "/after-whisper"
This checks the Digits parameter. If it is "1" it immediately calls back with an empty response, signalling the end of the whisper and leading the call to connect with the original caller.
If the Digits parameter is not "1" then we initialise a Twilio client and make a request to the API to update the call with the sid ParentCallSid to a new URL. Once that is complete we return TwiML that says to <Hangup> the whisper call (which wasn't strictly necessary, but I like the intention).
exports.handler = async function (context, event, callback) {
const twiml = new Twilio.twiml.VoiceResponse();
if (event.Digits === "1") {
callback(null, twiml);
} else {
const client = context.getTwilioClient();
try {
// Update the parent call with a new URL.
await client.calls(event.ParentCallSid).update({
url: URL_TO_NEXT_TWIML,
});
} catch (error) {
console.log(error);
}
twiml.hangup();
callback(null, twiml);
}
};
The next TwiML
This is the endpoint that the url above relates to, when it gets the callback it just returns a <Dial> to another number, though it could include another whisper and go round this loop again if desired.
exports.handler = async function (context, event, callback) {
const twiml = new Twilio.twiml.VoiceResponse();
twiml.dial(NEXT_NUMBER_TO_DIAL);
callback(null, twiml);
};
<Response>
<Dial>NEXT_NUMBER_TO_DIAL</Dial>
</Response>

Not recieving sms using twilio notify service, no debug error in console?

I am trying to send bulk SMS using Twilio notify API. I had looked at the documentation, and other StackOverflow resources but did not find the issue yet. What I am doing is:
$sid = "AC1e590cbb8eee064c3c71axxxxxxxxxxx";
$token = "94c2dc3e2e407c4ebd28cxxxxxxxxxxx";
$twilio = new Client($sid, $token);
$serviceSid = "IS32913ae9b083b809b1c06xxxxxxxxxxx";
$recipients = array();
foreach($phone_nos as $phone_no) {
array_push($recipients, $phone_no['phone_no']);
}
//recipients array print value is
//Array
//(
//[0] => +923105653361
//[1] => +923491457062
//)
$binding = array();
foreach ($recipients as $recipient) {
$binding[] = '{"binding_type":"sms", "address":"'.$recipient.'"}';
}
//binding array is print value is
//Array
//(
//[0] => {"binding_type":"sms", "address":"+923105653361"}
//[1] => {"binding_type":"sms", "address":"+923491457062"}
//)
$service = $twilio->notify->v1->services->create();
$notification = $twilio->notify->services($serviceSid)
->notifications->create([
"toBinding" => $binding,
"body" => 'Test message 5 notify'
]);
echo $notification->body;
echo '<pre>';print_r($notification->sid);exit;
The notify console is showing the messages are sent with no error.
Twilio developer evangelist here.
It looks like you haven’t connected a messaging service and a phone number to your Notify service. Follow the instructions in the documentation here to set that up, then try sending the messages again.

Twilio unable to record incoming call conversation (not related to leave a message)

In the incoming call back url
I have the next code:
Twilio Call id
if (isset($_REQUEST['CallSid'])){
$tw_call_id = $_REQUEST['CallSid'];
}
else {
$tw_call_id = '';<br />
}<br />
$sid = "Axxxx";
$token = "Txxxx";
$twilio = new Client($sid, $token);
$recording = $twilio->calls($tw_call_id)
->recordings
->create([
"recordingStatusCallback" => "https://mycode.php",
"recordingStatusCallbackEvent" => ["completed"],
"recordingChannels" => "dual"
]
);
After this I have a say() and a dial() , so I want to record the say and the dial , no only the dial call
I got the error
PHP Fatal error: Uncaught Twilio\Exceptions\RestException: [HTTP 400] Unable to create record: Requested resource is not eligible for recording in /var/www/html/vendor/twilio/sdk/src/Twilio/Version.php
What I am looking for is to record the complete conversation from incoming call

How to handle my sms statuscallback in twilio using php laravel?

I saw an example in twilio: https://www.twilio.com/docs/sms/tutorials/how-to-confirm-delivery-php
<?php
$sid = $_REQUEST['MessageSid'];
$status = $_REQUEST['MessageStatus'];
openlog("myMessageLog", LOG_PID | LOG_PERROR, LOG_USER);
syslog(LOG_INFO, "SID: $sid, Status: $status");
closelog();
I don't know what the code above exactly do, but what I want is to save the data to my local database.
The code in my post method(my statuscallback):
public function smsStatusCallback(Request $request){
$sms = SmsChannel::create([
'number' => $request['MessageSid'],
'body' => $request['MessageStatus'],
]);
}
I've found a solution already. I saw the possible solutions in twilio debugger: "Double check that your TwiML URL does not ...". So I tried making it as a twiml
public function smsStatusCallback(Request $request){
$response = new Twiml();
$sms = SmsChannel::create([
'sid' => $request['MessageSid'],
'status' => $request['MessageStatus'],
]);
return response($response)
->header('Content-Type', 'text/xml');
}
I've added my route to api.php since the URL should be accessible by twilio.
Route::post('sms-status-callback','CommunicationController#smsStatusCallback');

Create webhook for trello in php

I am creating webhook for trello using trello api and mattzuba sdk, webhook is created successfully by using post method but there are two issues
On getting this webhook by using GET function, no results I found.
On changing in model (board id ive used) its not hitting to the callbackURL, i want some example code for callbackurl.
Here is my code of Example.php
$id = '558d029fd94e87c6230df746';
$callback_url = 'http://exampledomain.com/webhook.php';
$description = 'Webhook for board';
$webhook = array(
'idModel' => $id,
'callbackURL' => $callback_url,
'description' => $description,
);
$post = $trello2->post("tokens/$token/webhooks/?key=$key", array_filter($webhook));
print_r($post);
Here is the code of callbackurl page webhook.php
$json = file_get_contents('php://input');
$action = json_decode($json);
$sql = mysql_query("INSERT INTO trellowebhook (data) VALUES ('$action')",$con);
print_r($sql);

Resources