Get status of SMS send though Twilio notify - twilio

I have send notification messages using Twilio api. Messages are sending properly.
$notification = $client
->notify->services($serviceSid)
->notifications->create([
"toBinding" => [
'{"binding_type":"sms", "address":"+971444444444"}',
'{"binding_type":"sms", "address":"+971444444445"}'
],
'body' => 'Test message 8'
]);
Response of the request is 201 and returning a sid starting with 'NT'. How to track status of this messages?

Should be like this:
PHP:
$notification = $client
->notify->services($serviceSid)
->notifications->create([
"toBinding" => [
'{"binding_type":"sms", "address":"+971444444444"}',
'{"binding_type":"sms", "address":"+971444444445"}'
],
'body' => 'Test message 8'
'sms' => ['status_callback' => 'https://youcallbackurl.com']
]);
Or Javascript
const service = twilio.notify.services(notifyId);
const bindings = numbers.map(number => {
return JSON.stringify({
binding_type: 'sms',
address: number,
});
});
service.notifications.create({
        toBinding: bindings,
        body: message,
sms: {
status_callback: 'https://youcallbackurl.com'
}
  })

twilio has a callback status webhook , you need to configure it inorder to track the delivery status of an sms message
$notification = $client
->notify->services($serviceSid)
->notifications->create([
"toBinding" => [
'{"binding_type":"sms", "address":"+971444444444"}',
'{"binding_type":"sms", "address":"+971444444445"}'
],
'body' => 'Test message 8'
'statusCallback' => "your public end point to track sms delivery status"
]);
see more here

Step to send Multiple SMS via Twilio using PHP
Create Account on Twilio
Get a Twilio Number
Add Phone numbers here: https://www.twilio.com/console/phone-numbers/verified
Create a notification Service here: https://www.twilio.com/console/notify/services and copy "SERVICE SID" (This will be used in code)
Create a Message Service here: https://www.twilio.com/console/sms/services
Select MESSAGING SERVICE SID under Notify - Configuration's page, what you have created on 5th step:
$sid = 'ACb2f967a907520b85b4eba3e8151d0040'; //twilio service SID
$token = '03e066de1020f3a87cec37bb89f56dea'; //twilio Account SID
$serviceSid = 'IS4220abf29ae4169992b8db5fc2668b10'; //Notify service SID
$client = new Client($sid, $token);
$rs = $client->notify->services($serviceSid)->notifications->create([
"toBinding" => [
'{"binding_type":"sms", "address":"+919999999999"}',
'{"binding_type":"sms", "address":"+919999999999"}'
],
'body' => 'Test message 8',
'statusCallback' => "your public end point to track sms delivery status"
]);

Related

Twilio Functions - Pass in parameters and format SMS body to include parameters

I am using Twilio to create an 'attendance line' where employees can provide information about why they will be absent and then Twilio will send separate, curated messages to supervisors and human resources.
To do this, I've created a Flow in Twilio Studio and I would like to use a Twilio Function to handle sending the mass SMS messages notifying users of a new absence.
I am passing parameters to the function like name, dept, shift, reason, etc with the intent to then share these values via SMS.
I am having the hardest time getting all of these different values properly into the body of the message.
exports.handler = function(context, event, callback) {
// Create a reference to the user notification service
const client = context.getTwilioClient();
const service = client.notify.services(
context.TWILIO_NOTIFICATION_SERVICE_SID
);
const notification = {
toBinding: JSON.stringify({
binding_type: 'sms', address: '+1XXXXXXXXXX',
binding_type: 'sms', address: '+1XXXXXXXXXX',
}),
body: 'New Attendance Notification',
event.question_name,
event.question_dept,
event.question_reason,
event.contactChannelAddress,
};
console.log(notification);
// Send a notification
return service.notifications.create(notification).then((message) => {
console.log('Notification Message',message);
callback(null, "Message sent.");
}).catch((error) => {
console.log(error);
callback(error,null);
});
};
Now I know the 'body' of the message above will not work but I'm a bit lost...
The text below is how I would like my SMS message to read out when sent.
New Attendance Notification
Name: event.Name
Dept: event.Dept
Reason: event.Reason
Contact: event.ContactChannelAddress
Is what I am trying to accomplish even possible?
Something like this...
exports.handler = function(context, event, callback) {
// Create a reference to the user notification service
const client = context.getTwilioClient();
const service = client.notify.services(
context.TWILIO_NOTIFICATION_SERVICE_SID
);
const bindings = [
'{ "binding_type": "sms", "address": "+14071234567" }',
'{ "binding_type": "sms", "address": "+18021234567" }'
];
const notice = `New Attendance Notification\nName: ${event.question_name}\nDept: ${event.question_dept} \nReason: ${event.question_reason}\nContact: ${event.contactChannelAddress} \n`;
// Send a notification
service.notifications.create({ toBinding: bindings, body: notice }).then((message) => {
console.log('Notification Message',message);
callback(null, "Message sent.");
})
.catch((error) => {
console.log(error);
callback(error,null);
});
};

how to get callback status in twilio

How to callback status in twilio for example in php.
require __DIR__ . '/vendor/autoload.php';
use Twilio\Rest\Client;
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "---------------";
$token = "-----------------;
$client = new Client($sid, $token);
$call = $client->calls->create(
$to, $from,
array(
"url" => "http://demo.twilio.com/docs/voice.xml",//this line complete
"method" => "GET",
"statusCallbackMethod" => "POST",
"statusCallback" => "https://www.myapp.com/events", //in this line no idea
"statusCallbackEvent" => array(
"initiated", "ringing", "answered", "completed"
)
)
);
echo $call->sid;
In this example how to get event after call
Your code is correct for registering call status notifications from Twilio. For every event you specified in your statusCallbackEvent array, Twilio will make an asynchronous HTTP request to the URL specified in the statusCallback parameter. See this article for more details.
So now you will need a service at this URL: https://www.myapp.com/events, listening for notification sent by Twilio. In your case these will be POST requests, given the method you specified in statusCallbackMethod parameter. The parameter you need to tell which event is being notified is CallStatus. See this documentation for more info.
We're not using PHP, but if you want to do a quick test, just create a Twilio Function and paste the following code in there to see your event notifications:
exports.handler = function(context, event, callback) {
let response = { get_started: true };
console.log(`Call status notified was '${event.CallStatus}'.`);
callback(null, response);
};

Creating Group via Microsoft Graph returns Error "An unexpected PrimitiveValue node was found when reading from the JSON reader"

Am trying to create group using my admin account via Microsoft Graph. I have implemented all the required parameters/variables but when I tried making calls to the API, it displays error below:
{
"error": {
"code": "Request_BadRequest",
"message": "An unexpected 'PrimitiveValue' node was found when reading from the JSON reader. A 'StartArray' node was expected.",
"innerError": {
"request-id": "02bfcc43-5982-4c49-8484-da9d6cc61bab",
"date": "2017-12-05T17:53:57"
}
}
}
My code:
<?php
session_start();
echo $acc= $_SESSION['access_token'];
$data_string = array("description" => "An Awesome New Group", "displayName" => "Awesome Group", "groupTypes" => "Unified", "mailEnabled" => "true", "mailNickname" => "awesomeGroup", "securityEnabled" => "fasle");
$data = json_encode($data_string);
//$data = $data_string;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://graph.microsoft.com/v1.0/groups",
CURLOPT_HEADER => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "$data",
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"authorization: Bearer $acc",
"content-type: application/json; charset=utf-8"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
print_r($response);
if ($err) {
echo "cURL Error #:" . $err;
} else {
//echo $response;
}
?>
Note that my real tenant id was replaced with admin#secx34fake.onmicrosoft.com so that its not displayed to public.
The error is telling you that the URL you're using is invalid.
This is accurate as /v1.0/admin#secx34fake.onmicrosoft.com/groups isn't a valid endpoint. Specifically it rejecting the userPrincipalName of admin#secx34fake.onmicrosoft.com. I'm not exactly sure where you were going with this but a Group is not a child of a User object. A User can be a member of a Group but they are both top-level elements within your Active Directory.
As an aside, a "segment" in the context of a URL is the elements separated by a /. You can think of a URL as a / delimited string with each column being a "segment". For example, /v1.0/me/events contains 3 segments: v1.0, me and events. The error you got is telling you one of these "segments" is either invalid or not in the proper order (i.e. /v1.0/events/me has the right segments in the wrong order).
For creating a Group, the proper URI looks like this:
POST https://graph.microsoft.com/v1.0/groups
Within the body of your POST you define the properties of the group. For example:
{
"description": "An Awesome New Group",
"displayName": "Awesome Group",
"groupTypes": ["Unified"],
"mailEnabled": true,
"mailNickname": "awesomeGroup",
"securityEnabled": false
}

In Twilio how can I access a menu after outgoing call is answered?

I'm trying to enable access to a menu after a call as been dialed and answered. For example, an agent dials a number, which uses the verb to place a call. During that call the person called asks to be transferred to a different agent, extension or queue. I have read about putting a call into a conference and using the hangupOnStar attribute to put the person called on hold and bring up a menu for the agent to further manipulate the call but have been unsuccessful. It seems that pressing the '*' button ends the call and therefore the DialCallSid belongs to a completed call which can't be updated.
I was originally going about this the wrong way. This is for an Outbound call, so I was able to successfully create a "on hold" conference, dial up a caller using the REST API, then add the caller to the conference. I was also able to harness the hangupOnStar attribute to enable leaving the conference and going to a menu.
Here is the code in my first function:
public function makeOutboundConference(Request $request) {
$sid = "ACxxxxxxxxxxxxxxxxxxxxxxxxx";
$token = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
$response = new Twiml();
$dial = $response->dial(
[
'hangupOnStar' => true,
'action' => 'url-to-incall-menu',
'method' => 'POST'
]
);
$dial->conference("On Hold",
[
'beep' => false,
]
);
$client = new Client($sid, $token);
try {
$call = $client->calls->create(
$to,
$callerId,
array('url' => 'fq-url-to-connect-caller')
);
} catch (Exception $e) {
error_log("Error: " . $e->getMessage());
}
return $response;
}
and my second function to add the person called to the conference:
public function showConnectCaller(Request $request) {
$response = new Twiml();
$dial = $response->dial();
$dial->conference(
"On Hold",
[
'record' => 'record-from-start',
'beep' => false,
'endConferenceOnExit' => true,
]
);
return $response;
}
Twilio: Can I make OUTBOUND Conference Calls? was very helpful.

how to use StatusCallback url in twilio

<?php
$options = array(
"StatusCallback" => 'http://173.203.104.63/call/out/log-callback.php? id='.$id
);
$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
$cphonenumber, // The number of the phone receiving call
'60',
'http://173.203.104.63/call/out/three.php?id='.$id, // The URL Twilio will request when the call is answered
$options
);
...
here i have set up url for statuscallback but i dont know weather it is redirecting or not and also how to get my callstatus values in that url
The 3rd argument should be the URL, not '60'. Once the call ends, all the data will be passed to your callback URL as normal POST or GET parameters (depending on what you've setup in your account).
you have forgotten to specify the method for statuscallback url
i have included it here in the code
<?php
//"StatusCallbackMethod" can be "POST" or "GET", depends on the way you recieve it on your StatusCallback,
$options = array(
"StatusCallbackMethod"=>"GET",
"StatusCallback" => 'http://173.203.104.63/call/out/log-callback.php? id='.$id
);
$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
$cphonenumber, // The number of the phone receiving call
'60',
'http://173.203.104.63/call/out/three.php?id='.$id, // The URL Twilio will request when the call is answered
$options
);
<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once('/path/to/twilio-php/Services/Twilio.php'); //
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "AC5ef8732a3c49700934481addd5ce1659";
$token = "{{ auth_token }}";
$client = new Services_Twilio($sid, $token);
$call = $client->account->calls->create("+18668675309", "+14155551212", "http://demo.twilio.com/docs/voice.xml", array(
"Method" => "GET",
"StatusCallback" => "https://www.myapp.com/events",
"StatusCallbackMethod" => "POST",
"StatusCallbackEvent" => array("initiated", "ringing", "answered", "completed"),
));
echo $call->sid;
Please see https://www.twilio.com/docs/api/rest/making-calls

Resources