When Customer replies to proxy service reserved number then proxy hit an OutOfSessionCallbackUrl(if a session is not active).
That URL will come to my code below.
public function response()
{
$to = $_POST['To'];
$from = $_POST['From'];
$from = substr($from, 2);
$body = $_POST['Body'];
$twilio = new Client($this->sid, $this->token);
$response=$this->db->get_where('contact_management as cm
,proxy_service as ps',
array('mobile'=>$from,'company_mobile'=>$to,'sc.sms_template_id<>'=>0))
->row_array();
$number = trim($response['country_code'].$response['mobile_number']);
//Here I'm sending a response
header("content-type:application/json");
?>
{
"uniqueName": "<?php echo rand();?>",
"ttl":"64800",
"mode": "voice-and-message",
"participantIdentifier":"<?php echo $number;?>"
}
<?php
}
This will create a session between SMS sender and returned number(company) and send the message of the sender to the company. I want to send a custom message before Twilio proxy send actual message to the company.
Thanks.
Twilio developer evangelist here.
Currently you are using the out of session callback in order to create a session, but you want to send a message before you forward on the incoming message.
To do this, you won't be able to respond with the JSON to create a session. Instead, you should create the session manually using the session API. Once you have created a session you can then send your initial message by creating an interaction on the participant you want to send the message to. You can then follow up by using the same API to forward the original message. And finally you still need to respond to the webhook. Since you handled all the message sending manually, you can return an empty TwiML <Response/> to signify that you need Twilio to take no further part.
Let me know if that helps at all.
Here Are the complete Description.
I have add Twilio number as reserved in proxy service and set the proxy service OutOfSessionCallbackUrl.When this URL reach my code then the magic happens,
public function response()
{
$to = $_POST['To'];
$from = $_POST['From'];
$twilio = new Client($this->sid, $this->token);
$response=$this->db->get_where('contact_management ,proxy_service,
array('mobile'=>$from,'company_mobile'=>$to))->row_array();
$service_sid=$response['service_sid'];
$session = $twilio->proxy->v1->services($service_sid)->sessions
->create(array("uniqueName" => rand(),"ttl"=>"64800"));
$session_sid = $session->sid;
$participant1 = $twilio->proxy->v1->services($service_sid)
->sessions($session_sid)->participants->create($_POST['From'], // identifier
array("friendlyName" => $response['f_name'],"proxyIdentifier"=>$to));
$from_id = $participant1->proxyIdentifier;
$participant2 = $twilio->proxy->v1->services($service_sid)
->sessions($session_sid)->participants
->create($response['country_code'].$response['mobile_number'], // identifier
array("friendlyName" => $response['first_name']));
$to_id = $participant2->proxyIdentifier;
$to_sid = $participant2->sid;
$body = $response['campaign_name']."\n";
$body .= $_POST['Body'];
$message_interaction = $twilio->proxy->v1->services($service_sid)
->sessions($session_sid)
->participants($to_sid)
->messageInteractions
->create(array("body" => $body));
header("content-type:text/xml");
?>
<Response />
<?php
}
Related
I'm trying to implement fax sending and receiving using laravel. But unfortunately, I'm getting this error. Please see the error and my code below.
Error
Twilio\Exceptions\RestException
[HTTP 403] Unable to create record: '+15005550006' is not a valid destination for trial accounts
Code
public function send()
{
$sid = env('TWILIO_ACCOUNT_SID');
$token = env('TWILIO_AUTH_TOKEN');
$to = env('TO_EXAMPLE');
$twilio = new Client($sid, $token);
$mediaURL = asset('pdfs/dummy.pdf');
$from = ["from" => '+' . env('TWILIO_NUMBER')];
$fax = $twilio->fax->v1->faxes
->create('+' . $to, $mediaURL, $from);
print($fax->sid);
}
Reference
https://www.twilio.com/docs/fax/quickstart
Do not use your TEST credentials. Use your LIVE credentials. +15005550006 is reserved for use with TEST credentials.
How To Use Twilio Test Credentials with Magic Phone Numbers
I'm trying to send bulk sms through twilio Api. Is there any method to pass the array of all phone numbers in a single API request.
Twilio developer evangelist here.
Yes there is now! It's known as the passthrough API (as it allows you to pass through many different messaging systems and send bulk messages. It's part of the Notify API and you can use it to send bulk SMS messages. You need to set up a messaging service and a notify service in your console, then you can use the following code:
<?php
// NOTE: This example uses the next generation Twilio helper library - for more
// information on how to download and install this version, visit
// https://www.twilio.com/docs/libraries/php
require_once '/path/to/vendor/autoload.php';
use Twilio\Rest\Client;
// Your Account SID and Auth Token from https://www.twilio.com/console
$accountSid = "your_account_sid";
$authToken = "your_auth_token";
// your notify service sid
$serviceSid = "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
// Initialize the client
$client = new Client($accountSid, $authToken);
// Create a notification
$notification = $client
->notify->services($serviceSid)
->notifications->create([
"toBinding" => [
'{"binding_type":"sms", "address":"+15555555555"}',
'{"binding_type":"sms", "address":"+12345678912"}'
],
"body" => "Hello Bob"
]);
Checkout the documentation on sending multiple messages with the Notify passthrough API for all the details.
In case someone else had troubles with preparing the toBinding parameter from a PHP array() as I had, here is an example for that:
<?php
require_once '/path/to/vendor/autoload.php';
use Twilio\Rest\Client;
$accountSid = "your_account_sid";
$authToken = "your_auth_token";
$serviceSid = "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$client = new Client($accountSid, $authToken);
$recipients = array($num1, $num2, ...); // Your array of phone numbers
$binding = array();
foreach ($recipients as $recipient) {
$binding[] = '{"binding_type":"sms", "address":"+1'.$recipient.'"}'; // +1 is used for US country code. You should use your own country code.
}
$notification = $client
->notify->services($service_sid)
->notifications->create([
"toBinding" => $binding,
"body" => $text
]);
?>
First of all, you need to configure your twilio number properly for notification. Then your to use below code to send bulk SMS.
$message = 'Any text message';
$to = array();
foreach ($users as $user) {
$to[] = '{"binding_type":"sms", "address":"'.$user->phone_number.'"}';
}
$sid = 'TWILIO_ACCOUNT_SID';
$token = 'TWILIO_AUTH_TOKEN';
$services_id = 'TWILIO_SERVICE_ID';
$twilio = new Client($sid, $token);
$notification = $twilio
->notify->services($services_id)
->notifications->create([
"toBinding" => $to,
"body" => $message
]);
I am using PHPmailer with Gmail API to send out mail. This process has worked very well for me for sending just standard emails, however, I want to also have the ability to send out an email with attachments using the Gmail API. When I tried using $mail->addAttachment($urlString, $name); Gmail would come back with the error Request Entity Too Large Error 413 (The size of the attachments never goes above 20MB so it should be well within the 35MB limits of Gmail API).
After some searching, I found out it was because I wasn't using "/Upload URI" for sending large Gmail Attachments (Anything above 5mb and below 35mb). Problem is, I am not very knowledgeable on how to work the Gmail API and only got what I have now from basically copying code from somewhere else and slightly modifying it for my uses and as such, I have no idea how to change the URI like that.
Here is what I have so far, that works with standard emails:
function($agent, $assistantName='', $assistantEmail='', $subject, $body, $attachments=''){
$key = realpath(dirname(__FILE__).'/Services/Google/Gmail.json');
$useremail = 'myuseremail#example.com';
$toAddress = $agent->email;
$agentFirst = $agent->first_name;
$client = new Google_Client();
putenv('GOOGLE_APPLICATION_CREDENTIALS='.$key);
$client->useApplicationDefaultCredentials();
$user_to_impersonate = $useremail;
$client->setSubject($user_to_impersonate);
$client->addScope('https://www.googleapis.com/auth/gmail.compose');
if ($client->isAccessTokenExpired()) {
$client->refreshTokenWithAssertion();
}
//prepare the mail with PHPMailer
$mail = new PHPMailer();
$mail->CharSet = "UTF-8";
$mail->Encoding = "base64";
$subject = $subject;
$msg = $body;
$from = $useremail;
$fname = "My Name";
$mail->From = $from;
$mail->FromName = $fname;
$mail->AddAddress($toAddress, $agentFirst);
$mail->AddCC($assistantEmail, $assistantName);
$mail->AddReplyTo($from,$fname);
if ($attachments != '') {
foreach ($attachments as $name => $urlString) {
$mail->addAttachment($urlString, $name);
}
}
$mail->Subject = $subject;
$mail->Body = $msg;
$mail->IsHTML(true);
$mail->preSend();
$mime = $mail->getSentMIMEMessage();
$m = new Google_Service_Gmail_Message();
$data = base64_encode($mime);
$data = str_replace(array('+','/','='),array('-','_',''),$data); // url safe
$m->setRaw($data);
$service = new Google_Service_Gmail($client);
$email = $service->users_messages->send($useremail, $m);
return json_encode($email);
}
I don't really know where to go from here, so any help would be appreciated.
use EZCMail and build the email structure yourself... it is very pickey! I can post some details after.
you may also have to send the email in chunks.
If the email is over 4MB then you are going to have to send in chunks using Google_Http_MediaFileUpload
Your code using this should be something similar to this, there is examples for using Google_Http_MediaFileUpload elsewhere on the web which might be more complete:
$client->setDefer(true);
// Call the API with the media upload, defer so it doesn't immediately return.
$arrRequestParams = $arrRequestParams+['uploadType' => 'multipart'];
$result = $this->TransportPrepSwitch($strAction, $objGMessage, $arrRequestParams); // Make draft or message $service->users_messages->send('me', $objGMessage, $arrRequestParams);
$mailMessage = base64url_decode($strRaw);
// create mediafile upload
$chunkSizeBytes = 1*1024*1024; // send to google in 1MB chunks
$media = new Google_Http_MediaFileUpload($client,$result,'message/rfc822',$mailMessage,true,$chunkSizeBytes);
$media->setFileSize(strlen($mailMessage));
// Upload chunks. Status will contain the completed $result.
$status = false;
set_time_limit(300);
while(!$status)
$status = $media->nextChunk();
// Reset to the client to execute requests immediately in the future.
$client->setDefer(false);
$objResponce = $status;
Also the structure of the email parts MUST be as follows:
multipart/mixed => [
multipart/related => [
multipart/alternative => [
plain,
html
],
inline images,
],
attachments,
]
The only way I could achieve this was using EZCMail to build the email part by part.
I am sending an SMS message to an Android phone using Twilio.
The domain has a hypen in it. e.g. http://my-domain.com
When the SMS message arrives on Android, only the initial portion of the text is included in the hyperlink.
So in the above example the hyperlink is "http://my"
How is it possible to escape a hyperlink being send to android? I am using the PHP Twilio client.
It might be you done any small mistake. And, it not depend on android or iOS.
I also tried and it worked as its not specific to Android or iOS.
<?php
require '../Services/Twilio.php'; // Include the Twilio PHP library
$version = "2010-04-01"; // Twilio REST API version
// Set our Account SID and AuthToken
$sid = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy';
$token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$client = new Services_Twilio($sid, $token, $version); //initialise the Twilio client
$message = 'http://my-domain.com';
try {
// Initiate a new outbound call
$call = $client->account->messages->create(array(
'To' => "+YYYYYYYYYY",
'From' => "+1XXXXXXXXXX",
'Body' => $message,
));
echo 'TWILIO SMS';
echo 'Sending.... ';
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
?>
Here, my code. From this am getting this url as same in SMS from Twilio.
You please check your code once. And, I hope my code will help you.
I'm using the Twilio API to send broadcast SMS messages based on an approved number. The problem in which I have encountered is not being able to successfully run a query pulling the phone information from a database and enter it into the API for each results that meet the query criteria to send an SMS to. The below is what I have so far.
//Include the PHP TwilioRest library
require "Services/Twilio.php";
//Set our AccountSid and AuthToken
$AccountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXX";
$AuthToken = "YYYYYYYYYYYYYYYYYYYYYYYYYYYYY";
//Instantiate a new Twilio Rest Client
$client = new Services_Twilio($AccountSid, $AuthToken);
//Trusted numbers that we want to be able to send a broadcast
$trusted = array("+33333333333" => "ApprovedAdmin1");
//An unauthorized user tried to send a broadcast.
if(!$name = $trusted[$_REQUEST['From']])
{header("content-type: text/xml");echo "\n";echo "Unauthorized broadcaster, contact an admin for access.";exit(0);}
//These are the recipients that are going to receive the broadcasts
//database user credentials
`$user = "user";`
`$password = "password";`
`$database = "database";`
`$host = "localhost";`
//connect to the database
`$DB = mysql_connect($host, $user, $password) or die("Can't connect to database.");`
`#mysql_select_db($database) or die("Unable to select database");`
//Used to query database for only user phone numbers who accept texts
$recipients = array (mysql_query("SELECT phone FROM sms WHERE (accept_text = 'Y')"));
//I have commented this out to try to get the query to work. The below recipients array does work and even lists the names of the user in the SMS.
//$recipients = array("+22222222222" => "testuser1");
//Grab the message from the incoming SMS
$msg = $_REQUEST['Body'];
// Iterate over all our recipients and send them the broadcast
//foreach ($recipients as $number => $name) {
//Send a new outgoinging SMS by POSTing to the SMS resource
$sms = $client->account->sms_messages->create("3333333333",$number,"$name, " . $msg);echo $name . " ";}
Ok so first of all you are not executing valid XML on the error condition e.g. if the user is not a trusted number. If you want to reply to the texter that the number is unauthorised you would need to do:
header("content-type:text/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<Response>\n<Sms>Unauthorized broadcaster, contact an admin for access.</Sms>\n</Response";
I'm not sure what you are trying to do with the query - why is it in an array? And I don't know why you then have a recipients array - surely this is what you are pulling in from the database? You need to do:
$result = mysql_query("SELECT phone FROM sms WHERE accept_text = 'Y'");
while($row = mysql_fetch_assoc($result)) {
$client->account->sms_message->create("3333333333", $row['phone'], $_REQUEST['Body']);
}