How to get Twilio call status in Laravel? - twilio

I have a Laravel app where I have some logic and I'm using Twilio to make the phone call but I want to make when the user missed the phone call after the user will get the SMS and for that, I need to know the call status but how do I get the call status in Laravel. If anybody can help me please feel free to respond.
public function initiateCall(Request $request)
{
// Validate form input
$this->validate($request, [
'phone_number' => 'required|string',
]);
try {
//Lookup phone number to make sure it is valid before initiating call
$phone_number = $this->client->lookups->v1->phoneNumbers($request->phone_number)->fetch();
// If phone number is valid and exists
if ($phone_number) {
// Initiate call and record call
$call = $this->client->account->calls->create(
$request->phone_number, // Destination phone number
$this->from, // Valid Twilio phone number
array(
"record" => True,
"url" => "http://demo.twilio.com/docs/voice.xml"
)
);
if ($call) {
echo 'Call initiated successfully';
} else {
echo 'Call failed!';
}
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
} catch (RestException $rest) {
echo 'Error: ' . $rest->getMessage();
}
}

In the else section of the code when the code echo 'Call failed!'
else {
echo 'Call failed!';
}
you can create or call a function here to send a SMS to user after failed call & also you can set a counter variable here that changes the variable's value to indicate that call is failed.

Related

Trying to read "bounce list" from AWS SNS in PHP

I'm programming an application to send emails through Amazon SES.
I would like to read the bounces (hard/soft bounces) from Amazon SNS (SES and SNS are already linked).
I tried the code shared on StackOverflow, but i constantly get an error message
//Create a SESClient
$SnsClient = new Aws\Sns\SnsClient([
//'profile' => 'default',
'version' => '2010-03-31',
'region' => 'eu-west-1',
'credentials' => [
'key' => $DatabaseLink->aws_access_key_id,
'secret' => $DatabaseLink->aws_secret_access_key],
]);
try {
$_SERVER['HTTP_X_AMZ_SNS_MESSAGE_TYPE'] = 'Notification';
// Retrieve the message
$message = Message::fromRawPostData();
// make validator instance
$validator = new MessageValidator();
// Validate the message
if ($validator->isValid($message)) {
if ($message['Type'] == 'SubscriptionConfirmation') {
// if it's subscription or unsubscribe event then call SubscribeURL
file_get_contents($message['SubscribeURL']);
} elseif ($message['Type'] === 'Notification') {
$subject = $message['Subject'];
$messageData = json_decode($message['Message']);
// use $subject and $messageData and take relevant action
}
}
} catch (Exception $e) {
// Handle exception
echo $e;
}
"Invalid POST data". I don't want to send a message for validation, i would like to get the list of email adresses that bounced. So, my backend can process them and remove them from my database.
Could you please help me to figure it out?
I'm going in circles with the aws documentation.

Twilio Classic Functions, How do you work with Tags and SMS?

Twilio function Problem: Tags are not working as expected.
I'm trying to create unique SMS subscription lists for users who SMS 'keyword1','keyword2','keyword3',etc to my number.
I'm doing this by intercepting the 'incoming message' events via a classic function.
I want to poll the keywords then assign tags to the users as I subscribe them to a list.
Then when I broadcast SMS I want to be able to send to only those users who are tagged with my keyword.
For example to capture the keyword 'test' and assign the tag 'test' to a user, I'm using the code below.
And then to send messages to all users with the tag 'test' I'm using a "sendtest" command.
I can broadcast to 'all' tags and it will work fine, but if I want to only send to users with tags ['test'], then there are no errors reported and the system tells me it was successful, but no subscribers will receive any messages.
I'm wondering if I have some problem in the way I am trying to define the tags? It looks like the data format is supposed to be a STRING[] array of some kind, I'm guessing ['test','two','three']. (If I can confirm this is right). But I notice as per the working examples provided by twilio if I set the notification arguments to a string IE: tags: 'all', then this syntax works to broadcast to all tags. Anything else though, will not work at all.
is there some trick to getting tags to work, or do they not work at all when trying to filter notifications via the classic function interface?
class TestCommand extends Command {
run(callback) {
// Create a new SMS Notify binding for this user's phone number
//and try to tag the user with keyword 'test'
notify.bindings.create({
identity: this.fromNumber,
bindingType: 'sms',
address: this.fromNumber,
tags: ['test']
}).then((response) => {
callback(null, 'test Message success')
}).catch(err => {
callback(err, 'test message fail')
})
}
}
class BroadcastTestCommand extends Command {
run(callback) {
// Check if sender is in list of admins, stored in the system environment
// as a comma-separated string
if (adminNumbers.indexOf(this.fromNumber) < 0) {
return callback(null, 'broadcast Not Authorized')
}
// Create a new SMS Notify binding for this user's phone number
//only notify users who are tagged with 'test'
notify.notifications.create({
tag: ['test'],
body: this.commandText
}).then((response) => {
callback(null, 'broadcast test Success')
}).catch(err => {
console.log(err)
callback(err, 'broadcast test Fail')
})
}
}
// Handle incoming SMS commands ####################
exports.handler = (context, event, callback) => {
// Get command text from incoming SMS body
let cmd = event.Body || ''
cmd = cmd.trim().split(' ')[0].toLowerCase()
// Default to help command
let cmdInstance = new HelpCommand(event, context)
// Choose other commands as appropriate
switch(cmd) {
case 'test': cmdInstance = new TestCommand(event, context); break;
case 'sendtest': cmdInstance = new BroadcastTestCommand(event, context); break;
}
// Execute command
cmdInstance.run((err, message) => {
let twiml = new twilio.twiml.MessagingResponse()
if (err) {
console.log(err)
message = 'There was a problem with your request. Try again!'
}
twiml.message(message)
callback(null, twiml)
})
}
Okay for anyone else pulling their hair out on this one..
The Twilio docs here on bindings will throw you off
https://www.twilio.com/docs/notify/api/binding-resource
Because the argument is NOT 'tags' it's 'tag'
This works ...
class TestCommand extends Command {
run(callback) {
// Create a new SMS Notify binding for this user's phone number
//and try to tag the user with keyword 'test'
notify.bindings.create({
identity: this.fromNumber,
bindingType: 'sms',
address: this.fromNumber,
tag: ['test']
}).then((response) => {
callback(null, 'test Message success')
}).catch(err => {
callback(err, 'test message fail')
})
}
}

Unable to print error message in foreach in magento admin

Hi i have added a new mas action in the sales order grid which allow create batch invoices.
For this my controler file is
<?php
class Iclp_Batchupdate_IndexController extends Mage_Adminhtml_Controller_Action
public function batchinvoiceAction ()
{
$already = " already ";
$refererUrl = $this->getRequest()->getServer('HTTP_REFERER');
$this->loadLayout();
$this->renderLayout();
$orderIds = explode(",",$this->getRequest()->getParam('order_ids'));
foreach ($orderIds as $orderIdss) {
$order = Mage::getModel('sales/order')->load($orderIdss);
//echo $orderIdss ."<br/>";
//echo "already ".$order->getStatusLabel();
try
{
if(!$order->canInvoice())
{
echo Mage::getSingleton('core/session')->addError($orderIdss.$already.$order->getStatusLabel());
}
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
$invoice->register();
$transactionSave = Mage::getModel('core/resource_transaction')->addObject($invoice)->addObject($invoice->getOrder());
$transactionSave->save();
$order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true)->save();
//echo "Invoice are created";
}
catch (Mage_Core_Exception $e) {
}
}
//A Success Message
Mage::getSingleton('core/session')->addSuccess("Some success message");
//A Error Message
Mage::getSingleton('core/session')->addError("Some error message");
//A Info Message (See link below)
Mage::getSingleton('core/session')->addNotice("This is just a FYI message...");
//These lines are required to get it to work
session_write_close();
$this->getResponse()->setRedirect($refererUrl);
}
}
every thing is working fine but the problem is it is not printing the error message in foreach in above code
if(!$order->canInvoice())
{
echo Mage::getSingleton('core/session')->addError($orderIdss.$already.$order->getStatusLabel());
}
but the bottom error message are displayed properly. MOreover if i extend the class with front-action than it also prints the foreach messages. Please suggest where i am doing the mistake
You should add your errors and messages to admintml/session and not to core/session when you are in adminhtml. That should display the message correctly. You shouldn't need session_write_close();. There is also no need to echo the message, that should be handled automatically by Magento after the redirect.
There is also no need to call $this->loadLayout(); and $this->renderLayout(); because you are redirecting at the end.
Finally, regarding the redirect, you should not read the referrer yourself, Magento can to that for you more reliably. Just use the $this->_redirectReferer(); method instead of $this->getResponse()->setRedirect($refererUrl);.

Using Dispatch Event to check authorization

I am trying to setup a simple API. I have a Controller all other API controllers are extending, and I have attached a dispatch listener like so. I created a test that will always fail. Set the status code to 401, and return a message. However, it's still calling the main Controller method and not abandoning the request from the preDispatch method. Can I build a proper response here and force ZF2 not to continue executing the requested route? I tried just adding an exit() statement, but the client side receives an incomplete response.
protected function attachDefaultListeners()
{
parent::attachDefaultListeners();
$events = $this->getEventManager();
$this->events->attach('dispatch', array($this, 'preDispatch'), 100);
$this->events->attach('dispatch', array($this, 'postDispatch'), -100);
}
public function preDispatch (MvcEvent $e)
{
$this->dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
// TODO: Check user and token from DB
if (Cookie::isCookieSet())
{
$cookie = Cookie::readCookie();
if (empty($cookie->user))
{
$this->getResponse()->setStatusCode(401);
return new JsonModel(array('auth' => false, 'msg' => 'Try again'));
}
// Cookie not set, if we are authenticating, continue; otherwise return a failure
} else {
}
}
You need to return a response object to short circuit the process, not a ViewModel:
Try something like this:
$response = $this->getResponse();
$response->setStatusCode(401);
$response->setContent(array('auth' => false, 'msg' => 'Try again'));
return $response;

Why i don't see my #replies in conversation view in twitter?

I need to reply to one particular twitter status. I'm using following functions. And I've used Abraham's twitteroauth library in php.
public function replyToTwitterStatus($user_id,$status_id,$twitt_reply,$account_name)
{
$connection= $this->getTwitterConnection($user_id,$account_name);
try{
$responce = $this->postApiData('statuses/update', array('status' => $twitt_reply,'in_reply_to_status_id '=> $status_id),$connection);
}
catch(Exception $e){
echo $message = $e->getMessage();
exit;
}
}
// this function will handle all post requests
// To post/update twitter data
// To post/update twitter data
public function postApiData($request,$params = array(),$connection)
{
if($params == null)
{
$data = $connection->post($request);
}
else
{
$data = $connection->post($request,$params);
}
// Need to check the error code for post method
if($data->errors['0']->code == '88' || $data->errors['0']->message == 'Rate limit exceeded')
{
throw new Exception( 'Sorry for the inconvenience,Please wait for minimum 15 mins. You exceeded the rate limit');
}
else
{
return $data;
}
}
But the issue is that it is not maintaining the conversation view and it is update like normal status for e.g #abraham hello how are you. but that "View conversation" is not coming. Like expanding menu is not coming.
Please do needful
Thanks
You've got an unwanted space in your in_reply_to_status_id key which causes that parameter to be ignored.
This call:
$responce = $this->postApiData('statuses/update', array(
'status' => $twitt_reply,
'in_reply_to_status_id ' => $status_id
), $connection);
should look like this:
$responce = $this->postApiData('statuses/update', array(
'status' => $twitt_reply,
'in_reply_to_status_id' => $status_id
), $connection);
Also, make sure that the $status_id variable is being handled as a string. Although they look like numbers, most ids will be too big to be represented as integers in php, so they'll end up being converted to floating point which isn't going to work.
Lastly, make sure you have include the username of the person you are replying to in the status text. Quoting from the documentation for the in_reply_to_status_id parameter:
Note:: This parameter will be ignored unless the author of the tweet this parameter references is mentioned within the status text. Therefore, you must include #username, where username is the author of the referenced tweet, within the update.

Resources