How to answer incoming call in browser using javascript and php - twilio

connection.on('incoming', function(conn) {}) function not called.
I am trying to implement the incoming call in the browser. What I tried is a javascript code
var number = $("#number").val();
params = {
"PhoneNumber": number,
"CallerId": "+13604924000",
"AgentName": "Noman Javed",
};
Twilio.Device.setup(token);
Twilio.Device.ready(function(device) {
console.log('Ready');
// ---------------------------------------------------
// Explicitly create a new outgoing connection
var connection = Twilio.Device.connect(params);
console.log('PhoneNumber: ' + params.PhoneNumber);
$('#hangup_btn_span').show();
$("#hangup_btn").show();
connection.on('error', function(error) {
console.log(error);
});
connection.on('accept', function(conn) {
});
connection.on('incoming', function(conn) {
console.log("incoming call connection object log");
console.log(conn);
console.log('Incoming connection from ' + conn.parameters.From);
// accept the incoming connection and start two-way audio
// conn.accept();
});
}
For outgoing calls, I had to add the URL of the Twiml App outgoing call URL and dial the call using rest API to hit twiml page.
For incoming calls, I had add incoming call URL in the phone number incoming call URL that is
mydomain.com/Welcome/incoming_call
The incoming call urls code is:
header('Content-Type: application/xml');
// Load the required files
require APPPATH . 'libraries/vendor/autoload.php';
use Twilio\Jwt\ClientToken;
use Twilio\Rest\Client;
use Twilio\TwiMl;
use Twilio\TwiML\VoiceResponse;
file_put_contents('request.log', "\n" . "incoming call - : " . json_encode($_REQUEST) . "\n", FILE_APPEND);
?>
<Response>
<Pause length="2"/>
<Say voice="woman">Dialing number</Say>
<Dial callerId="<?php echo $_REQUEST['From']; ?>" >
<?php echo $_REQUEST['To']; ?>
</Dial>
</Response>
How I will receive the call in the browser in this function with parameters
connection.on('incoming', function(conn) {
console.log("incoming call connection object log");
console.log(conn);
console.log('Incoming connection from ' + conn.parameters.From);
// accept the incoming connection and start two-way audio
// conn.accept();
});
Do I need to add an incoming call URL in Twiml App too or just add in the phone number incoming URL?
Thanks in advance for helping and guiding.

First, in the twiml app you have to add the url for your backend api where you have your php code and add that twiml app to your incoming number.
Now, while generating the token for your user you must have used an 'identity'. We need to use that identity value to connect the incoming call to the user. Something like below:
$response = new VoiceResponse();
$dial = $response->dial('');
$dial->client(IDENTITY_VALUE);
this dial->client will connect the incoming call to the browser.
If you have not used identity attribute in your token generation, check this url:
https://www.twilio.com/docs/iam/access-tokens?code-sample=code-creating-an-access-token-voice-2&code-language=PHP&code-sdk-version=5.x

Related

How can I capture a dtmf code on for a call sent out of twilio?

I send calls out by building an html file that contains twiml markup, and use the php lib to place the call to the outgoing number (see e.g.)
$tw_call = $twilio_client->calls->create(
"+1".$recipient['address'], "+1".$org['twilio_number'],
array(
'Url' => VOICE_CALL_LINK.'/'.$file, (this contains the SAY verbs and text)
'Timeout' => '30',
'StatusCallback' => CALLBACK_LINK.'/voice_call_handler.php',
'StatusCallbackEvent' => array('initiated', 'ringing', 'answered', 'completed')
)
I want to know if it is possible to record a dtmf code from the call recipient via the method I am using for placing the call?
Can an additional callback url be placed in the text file? If so how would I capture which call the was coming back? Would the call sid be available to the possible callback url within the text file?
Ok I must be missing something. I tried the following:
<Response>
<Pause length='1'/>
<Say voice='alice'>$intro</Say>
<Pause length='1'/>
<Say voice='alice'>$msg_body</Say>
<Pause length='1'/>
<Gather action='absolute html path' numDigits='1'>
<Say Please respond by selecting 1 for I can come. Select 2 for I cannot come.</Say>
</Gather>
</Response>";
I get back from Twilio "an application error has occurred". If I remove the Gather tags and the Say tag within the Gather tags, I receive a perfect call.
Same error occurs if I leave the tags and remove the action and path.
Can you gather responses on outbound calls? I ask because all twilio docs refer to inbound call.
Twilio developer evangelist here.
In order to capture DTMF tones from a call you can use the <Gather> TwiML verb. This would probably go in the file which contains your <Say> that you point to in the code above. <Say> can be nested within <Gather> in order to allow you to ask the user for input and start taking it as soon as they start typing.
The TwiML might look like this:
<Response>
<Gather action="/gather_result.php" numDigits="1">
<Say>Welcome to the free beer hotline, dial 1 for free beer, dial 2 for other beverages.</Say>
</Gather>
</Response>
Then, when the user dials the number (you can control how many numbers with the numDigits attribute) Twilio will make a request to the URL in the action attribute. Within that request will be a Digits parameter which will contain the numbers the user pressed. The call SID would also be among the parameters.
Let me know if that helps at all.
I had similar issue where Gather TwiML was not capturing the user dtmf input from a call sent out of twilio. For some reasons, it failed to capture my input digit. I did press 1#, but the voice message keep playing and repeating the same message. Sometimes it works and twilio able to get the digit that I inputted, but more than 80% of the times I tried, it failed to capture the inputted digit. Below is the TwiML in node js looks like:
var promise = new Parse.Promise();
twilioClient.calls.create({
to: phoneNumber,
from:'+6598124124',
url: hosturl + '/gather_user_dial',
body: callParam,
statusCallback: hosturl + '/callback_user',
statusCallbackMethod: 'POST',
statusCallbackEvent: ["completed", "busy", "no-answer", "canceled", "failed"]
}).then(function(call) {
if (res) res.success(call);
promise.resolve(call);
}, function(error) {
console.error('Call failed! Reason: ' + error.message);
if (res) res.error(error);
promise.reject(error);
});
app.post('/gather_user_dial', (request, response) => {
const twiml = new VoiceResponse();
const gather = twiml.gather({
numDigits: 1,
timeout: 5,
actionOnEmptyResult: true,
action: '/gather',
});
gather.say('You are receiving a call from company A because you press the emergency button. Press 1 if you are okay or Press 9 if you need help, followed by the pound sign.');
twiml.redirect('/gather_user_dial');
response.type('text/xml');
response.send(twiml.toString());
});
app.post('/gather', (request, response) => {
const twiml = new VoiceResponse();
if (request.body.Digits) {
switch (request.body.Digits) {
case '1':
twiml.say('User has been notified!');
userPressOne(request.body.Called);
break;
case '9':
twiml.say('User has been notified!');
userPressNine(request.body.Called);
break;
default:
twiml.say("Sorry, I don't understand that choice.").pause();
twiml.redirect('/gather_user_dial');
break;
}
} else {
twiml.redirect('/gather_user_dial');
}
response.type('text/xml');
response.send(twiml.toString());
});

when we make call using rest api then what twiml we use on that url parameter

I am Creating the call using the rest api-
try{
// Initiate a new outbound call
$call = $this->client->calls->create(
// to call.
"num2",
// Step 5: Change the 'From' number below to be a valid Twilio number
// that you've purchased or verified with Twilio.
"num1",
array("url" => "url-tw",
'IfMachine'=>'Continue')
);
echo "Started call: " . $call->sid;
} catch(Exception $e){
echo "Error: " . $e->getMessage();
}
and on the url-tw what twiml should I use which can't disconnect the call.
Before I was handling the call using the TwiML but now I have to detect the AnsweredBy option which is only available if I make the call using the REST API so.
for now I m using the same twiml I have used before when I was making calls using the twiML like use the <Dial> which let to dial again but if I dont use any twiml it disconnect the call.So any advice where I m going wrong.
Twilio evangelist here.
The value of the url parameter should be a publicly accessible URL that returns TwiML containing the instructions that you want Twilio to execute to the caller.
Your PHP to start the call would look like:
// Initiate a new outbound call
$call = $this->client->calls->create(
"num2",
"num1",
array("url" => "http://example.com/answer.php", 'IfMachine'=>'Continue')
);
Then in answer.php, you can do two things:
Check the AnsweredBy parameter to see if Twilio detected a machine or a human.
Generate the Twiml you want to return based on that value
For example to say something different to a machine v a human, you could do something like this in your PHP:
<?php
header("content-type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<?php if ($_REQUEST['AnsweredBy']=='machine'): ?>
<Response>
<Say>Hello machine</Say>
</Response>
<?php else: ?>
<Response>
<Dial>+15555555555</Dial>
</Response>
<?php endif ?>
Hope that helps.

Make a call between two numbers not registered in twilio

There's some way of make a call between two of my users? I mean... I have a twilio acount with a registered number and I have to make a call to my client "Bill" so when he answer that, the call should be redirected to another client, that Bill choosed, let's say "Joe". So, Bill click's a button and he's phone rings, he answer that and start to call Joe. When some of them hangup, the all call should be over. Have someone ever made that? Help me! And I'm sorry about my bad english
(oh yeah, I'm using php for that)
This is just something simple to get you going, you can also look at connecting to a conference room https://www.twilio.com/docs/api/twiml/conference
You will need to use the Twilio PHP Helper Library (the "Services" folder from there) download from https://www.twilio.com/docs/libraries/php#install-via-zip-file
Project structure
/
/Services
/callBill.php
/callJoe.php
callBill.php
<?php
header("content-type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<Response>
<!-- // calling Bill -->
</Response>
<?php
// Include the Twilio PHP library
require 'Services/Twilio.php';
// Twilio REST API version
$version = "2010-04-01";
// Set our Account SID and AuthToken
$sid = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// A phone number you have at Twilio
$phonenumber = '5557779999';
// The URL Twilio will request when the call is answered
$twilioRequestUrl = "http://somewebsite.xyz/callJoe.php";
// Instantiate a new Twilio Rest Client
$client = new Services_Twilio($sid, $token, $version);
try {
// Initiate a new outbound call
$call = $client->account->calls->create(
$phonenumber, // The number of the phone initiating the call
'7779995555', // call Bill at 7779995555
$twilioRequestUrl
);
//echo 'Started call: ' . $call->sid;
} catch (Exception $e) {
//echo 'Error: ' . $e->getMessage();
}
?>
callJoe.php
<?php
header("content-type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<!-- call and connect Joe at 9995557777 with Bill's caller ID-->
<Response>
<Pause length="2"/>
<Say>Please wait, I'm calling Joe.</Say>
<Dial callerId="7779995555">9995557777</Dial>
</Response>
Request http://somewebsite.xyz/callBill.php with your browser or with a click on a button.

Forwarding live Calls to a new Twiml from the browser

I am following the tutorial on https://www.twilio.com/docs/api/rest/change-call-state#post I am coding in php the portion that allows you to forward a current inbound call to a new Twiml URL. How do I get the inbound call Sid? Currently, the call Sid that I am retrieving forwards my browser to the new Twiml URL and hangs up the inbound caller. I think that I may have the wrong call Sid since I want to forward the current inbound caller to the new Twiml URL. Not The Browser. Can someone please give me some advice on retrieving the inbound call Sid to use in this php script? Thanks
Twilio.Device.incoming(function (conn) {
callSid = conn.parameters.CallSid;
$("#log").text("Incoming connection from " + conn.parameters.From);
// accept the incoming connection and start two-way audio
conn.accept();
});
This is how I am getting the Call Sid. If I input this Call Sid into
<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once('TwilioAPI/twilio-php-master/Services/Twilio.php'); // Loads the library
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = '';
$token = '';
$client = new Services_Twilio($sid, $token);
// Get an object from its sid. If you do not have a sid,
// check out the list resource examples on this page
$call = $client->account->calls->get("THE CALL SID I GOT FROM THE JS GOES HERE");
$call->update(array(
"Url" => "http://twimlets.com/message?Message%5B0%5D=I%20finally%20did%20it&",
"Method" => "POST"
));
echo $call->to;
?>
This code forwards the browser which receives the call to the new Twiml URL. Not the inbound caller.

twilio javascript client set from number , also how I can get the call sid after connect?

twilio javascript client set from number , Also how I can get the call sid after connect?
I tried to set the from Number in the call options like the next lines before connect and still the same issue in the javascript
$(document).ready(function () {
Twilio.Device.setup(token);
var connection = null;
$("#call").click(function () {
var params = { "Phone": $('#Phone').val(), "from":$('#Phone').val() };
connection = Twilio.Device.connect(params);
return false;
});
});
-- and inside the server side code vbnet when I am generating the token I added the next code but this doesn't solve the from number issue
Dim options As New CallOptions()
options.Record = True
options.From = model.FromNumber
Dim cap = New TwilioCapability(_settings.AccountSID, _settings.AuthToken)
cap.AllowClientOutgoing(_settings.ClientCallApplicationSID, options)
dim token = cap.GenerateToken()
Twilio evangelist here.
The params collection that you pass into the connect function is just a dictionary of key/value pairs. Those key/values simply get passed as parameters to the Voice URL that Twilio requests when Client makes its connection to Twilio, and you can use those parameters to dynamically generate some TwiML markup. Twilio does not do anything with them.
For example, if this is a PHP application, in the Voice URL you could do something like:
<Response>
<Dial>$_REQUEST['From']</Dial>
</Response>
One note of caution, Twilio already adds a parameter called from (which in the case of Client will be the client identifier set when you made your capability token) to the parameters sent to the Voice URL, so you might want to choose a different key name for your dictionary entry. I normally use a name like target for the key that holds the number that I want to dial.
Hope that helps.
To get the call sid, you can get it in connect event.
Please note that I am using Twilio JS v1.9.7
device.on('connect', function (conn) {
log('Successfully established call!');
//Get the CallSid for this call
callUUID = conn.outboundConnectionId;
console.log('CallSid: ' + callUUID);
});

Resources