Am getting an error message on sending a message to a single number.
{
"response":{
"success":false,
"errors":{
"id":"No device found with that ID"
}
},
"status":422
}
{
"response":{
"success":true,
"result":{
"id":90841,
"name":"New Device",
"make":"General Mobile",
"model":"General Mobile 4G",
"number":"",
"provider":"Airtel",
"country":"tz",
"connect_type":"3G",
"battery":77,
"signal":75,
"wifi":false,
"lat":"0",
"lng":"0",
"last_seen":"1526713626",
"created_at":"1526681354",
"updated_at":"1526713626"
}
},
"status":200
}
The first response is for sending a message to a single number and the second is getting device details using DeviceID.DeviceID for getting device details and sending a message to a number is the SAME Here is My PHP code
<?php
require_once 'smsGateway.php'; $number='07****XXXX'; $message="Hi ";
$smsGateway = new SmsGateway('user#gmai.com', '****');
$deviceID = 90841;
/*$options = [ 'send_at' => strtotime('+1 minutes'), // Send the message in 10 minutes 'expires_at' => strtotime('+1 hour') // Cancel the message in 1 hour if the message is not yet sent ];
*/ //Please note options is no required and can be left out $result = $smsGateway->sendMessageToNumber('0715605476', $message,2/*, $options*/); $devices = $smsGateway->getDevice($deviceID);
echo json_encode($result)."<br><br>".json_encode($devices);
?>
Related
I need help in Twilio getting reply responses and storing them in the database in response to sending SMS after user input in response to the message. I am sending an SMS to the user about his/her order schedule and asking him/her to confirm delivery by inputting Ok and when he/she confirm, I am getting his response successfully.
The question or the issue I am facing is that I want to know that when he/she confirm the delivery, I want to update the database record in response to the delivery SMS we sent to him/her earlier. My issue will be resolved if I am able to get order_id from the first message and send it in replytoSMS function.
My Code to send SMS and webhook (replytoSMS) are given below.
<?php
public function initiateSMS(Request $request) {
try {
foreach ( $request->get('items') as $item ) {
$order_id = $item['order_id'];
$phone = $item['phone_number'];
$order = Orders::where('id', $order_id)->first();
$phone_number = $this->client->lookups->v1->phoneNumbers($phone)->fetch();
if($phone_number) {
$template_value = $order->message;
$sms = $this->client->messages->create($phone, [
'from' => $this->from,
'body' => $template_value,
"method" => 'POST',
"statusCallbackMethod" => 'POST',
"statusCallback" => 'https://example.com/simply/public/api/notification/statusMessageBack?order_id='.$order_id.'',
]);
// print($sms->sid);
}
} // foreach loop end
if($sms){
return Response::json(['success' => 'sms initiated successfully!']);
}
} catch (Exception $e) {
return Response::json(['Error' => $e->getMessage()]);
} catch (RestException $rest) {
return Response::json(['Error' => $rest->getMessage()]);
}
}
function statusMessageBack(){
header('Content-type: text/xml');
header('Cache-Control: no-cache');
$response = new MessagingResponse();
$order_id = $_REQUEST['order_id'];
$user_phone = $_REQUEST['To'];
$MessageSid = (!empty($_REQUEST['MessageSid'])) ? $_REQUEST['MessageSid'] : '';
$MessageStatus = (!empty($_REQUEST['MessageStatus'])) ? $_REQUEST['MessageStatus'] : '';
if($MessageStatus && $MessageStatus == "delivered"){
$notification = Notification::create([
"response_code" => $MessageSid,
"type" => $category,
"table_ref" => "orders",
"table_ref_pk" => $order_id,
"response_status" => "",
"medium" => $user_phone,
"status" => $MessageStatus,
"sender_id" => $sender_id
]);
}
print $response; exit;
}
public function replyToSMS(){
header('Content-type: text/xml');
header('Cache-Control: no-cache');
$response = new MessagingResponse();
$MessageSid = (!empty($_REQUEST['MessageSid'])) ? $_REQUEST['MessageSid'] : '';
$MessageStatus = (!empty($_REQUEST['MessageStatus'])) ? $_REQUEST['MessageStatus'] : '';
$body = $_REQUEST['Body'];
$order_id = $_REQUEST['order_id'];
$from_phone = $_REQUEST['From'];
if (strtolower($body) == 'ok' || strtolower($body) == 'yes' || strtolower($body) == 'confirm') {
$response->message('Your delivery has been confirmed. Thank you', [
'callbackUrl' => "https://example.com/api/notification/reply_status?order_id='.$order_id.'",
'callbackMethod' => "POST"
]);
$notification = Notification::where('order_id', $order_id)->update(array("response_status" => "confirmed"));
} else {
$response->message('Sorry');
$notification = Notification::where('order_id', $order_id)->update(array("response_status" => "call store"));
}
print $response;
}
function reply_status(){
header('Content-type: text/xml');
header('Cache-Control: no-cache');
$response = new MessagingResponse();
echo $order_id = $_REQUEST['order_id'];
$user_phone = $_REQUEST['To'];
$MessageSid = (!empty($_REQUEST['MessageSid'])) ? $_REQUEST['MessageSid'] : '';
$MessageStatus = (!empty($_REQUEST['MessageStatus'])) ? $_REQUEST['MessageStatus'] : '';
if($MessageStatus && $MessageStatus == "delivered"){
}
print $response; exit;
}
The SMS protocol does not any concept of additional metadata with SMS messages, nor does it have the concept of replying to a specific message (you can test this by opening your phone's SMS application and trying to respond to any message from someone that wasn't the last one you received).
You can only really tell what someone may be responding to chronologically. That is, if you have sent them a message, then their response is related to that last message that you sent.
This is an issue if you intend to send more than one message asking for a response at the same time. In this situation, we recommend you use two different From numbers to send the message and store that From number against the order in your system. That way you can tell which message was being responded to by matching up the user's phone number and the phone number that you used to send the message.
I´m using Twilio PHP API to send mass sms to my customers.
Problem is that i can only send like 80st SMS and then i got a server error:
Failed to load resource: the server responded with a status of 503
(Backend fetch failed)
Well i think this might be the error.
Because i get no success echo echo "Sent message to $name and in the twilio SMS log i can only see that 80 SMS of 200 has been sent.
What can cause this error?
foreach ($usrs as $number => $name) {
try{
$sms = $client->account->messages->create(
// the number we are sending to - Any phone number
$number,
array(
// Step 6: Change the 'From' number below to be a valid Twilio number
'from' => "xxxxxxxxxxx",
// the sms body
'body' => "Hey $name. $text"
)
);
// Display a confirmation message on the screen
echo "Sent message to $name <br>";
}
catch (TwilioException $e) {
die( $e->getCode() . ' : ' . $e->getMessage() );
}
}
Twilio developer evangelist here.
Twilio has a limit of 100 concurrent API requests and will only send 1 message a second. As Ahmed suggested in the comments, I recommend you add a delay between calls to the API if you are sending more than 100 messages.
edit
Adds sleep(1) for each message. This will make the page delay a second after sending each message.
foreach ($usrs as $number => $name) {
try{
$sms = $client->account->messages->create(
// the number we are sending to - Any phone number
$number,
array(
// Step 6: Change the 'From' number below to be a valid Twilio number
'from' => "xxxxxxxxxxx",
// the sms body
'body' => "Hey $name. $text"
)
);
// Display a confirmation message on the screen
echo "Sent message to $name <br>";
sleep(1);
}
catch (TwilioException $e) {
die( $e->getCode() . ' : ' . $e->getMessage() );
}
}
I want to send SMS using the smsgateway.me API, but I'm getting this response:
{"response":false,"status":0}
Here is my code:
include "smsGateway.php";
$smsGateway = new SmsGateway('xxxxxx#xxxxxxx.com', 'xxxxxx');
$deviceID = xxxxx;
$number = '+92xxxxxxxxxx';
$message = 'Hello World!';
$options = [
'send_at' => strtotime('+1 minutes'), // Send the message in 10 minutes
'expires_at' => strtotime('+1 hour') // Cancel the message in 1 hour if the message is not yet sent
];
$result = $smsGateway->sendMessageToNumber($number, $message, $deviceID, $options);
echo json_encode($result);
please verify that cURL is enabled in your host
I'm trying to do some SMS messages using Twilio, and so far it's pretty straight forward, but I'm using some test data to capture various scenarios and I used "1234567890" as a phone number to capture an error, but I get the following error when I navigate to the page that queries the twilio api:
Fatal error: Uncaught exception 'Twilio\Exceptions\RestException'
with message '[HTTP 404] Unable to fetch record:
The requested resource /PhoneNumbers/1234567890 was not found'
Here's my code:
use Twilio\Rest\Client;
$client = new Client($sid, $token);
if($ph && preg_match('/^[0-9]{10}$/', $ph)) {
//this returns an array containing type, error_code, and a boolean
//value for is_valid.
$response = lookup($client, $ph);
if($response['is_valid']) {
//send the message via twilio.
$message = $client->messages->create(
$ph,
array(
'from' => 'my_twilio_number_goes_here',
'body' => 'text_body_goes_here'
)
);
//handle twilio response
$status = $message->status;
$sid = $message->sid;
}
How can I capture that response?
$twilio = new TwilioClient(env('TWILIO_ACCOUNT_ID'), env('TWILIO_TOKEN'));
$message=new \StdClass;
try
{
//check mobile number is valid or not
$is_valid_number = $twilio->lookups->v1->phoneNumbers($phone_number)->fetch();
if($is_valid_number)
{
$data['From']=env('TWILIO_FROM_ALPHANUMERIC_NAME');
$data['Body']="Sms testing";
$message = $twilio->messages->create($mobile_number, $data);
}
else{
echo "Your Mobile number is not available.";
}
}
catch(\Exception $e)
{
echo $e->getMessage();
}
I am trying to get the number of emails (read & unread shown separately) for a given search. I've read that the labels.get() function does the trick but I don't know how to use it. Here's the code I have to detect if I have less or more than 100 result for a given sender.
require_once '../../vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('../../client_secrets.json');
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->addScope(Google_Service_Gmail::GMAIL_READONLY);
$client->setAccessType("offline");
$client->setApprovalPrompt('force');
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Gmail($client);
$sender = array();
$sender[] = 'sender1#email.com';
$sender[] = 'sender2#email.com';
$sender[] = 'sender3#email.com';
function countfrom($service, $userId, $expeditor) {
try
{
unset($optParamsamz);
$optParamsamz = [];
$optParamsamz['maxResults'] = 100; // Return Only 5 Messages
$optParamsamz['q'] = "From: '".$expeditor."' ";
$messagesamz = $service->users_messages->listUsersMessages('me',$optParamsamz);
$listamz = $messagesamz->getMessages();
echo sizeof($listamz);
}
catch (Exception $e)
{
print 'An error occurred: ' . $e->getMessage();
}
}
foreach ($sender as $key => $value)
{
echo $value .': ';
countfrom($service,$_SESSION['emaile'],$value) ;
echo '<br/>';
}
------------------- EDIT ----------------------
I have tried a new solution that seems closer to what I'm looking for. The issue now comes from Google who returns some odd number for the resultestimatsize:
<?
require_once '../../vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('../../client_secrets.json');
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->addScope(Google_Service_Gmail::GMAIL_READONLY);
$client->setAccessType("offline");
$client->setApprovalPrompt('force');
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Gmail($client);
$sender_array[] = 'sender1#sender.com';
$sender_array[] = 'sender2#sender.com';
$sender_array[] = 'sender3#sender.com';
$sender_array[] = 'sender4#sender.com';
foreach ($sender_array as $key => $expeditor)
{
$optParamsamz1['q'] = "From: '".$expeditor."' is:read ";
$optParamsamz2['q'] = "From: '".$expeditor."' ";
echo $expeditor.": ".$service->users_messages->listUsersMessages('me',$optParamsamz1)->getResultSizeEstimate() . "
".$service->users_messages->listUsersMessages('me',$optParamsamz2)->getResultSizeEstimate();
echo "<br>";
}
?>
labels.get() will be of no help in this use case, I'm afraid. It only works for labels, so you could get read/unread from e.g. INBOX or CHAT easily, but will be of no help if you want to get all read/unread from e.g. all messages sent from example#gmail.com.
An alternative solution is fairly cheap though:
List messages with the query + AND is:unread, and a second one with the same query +
AND -is:unread.
If the response contains a nextPageToken, you have 100+ read/unread. If it does not contain a nextPageToken, there are response.messages.length amount of read/unread messages.
Example
Request unread
q = from:info#berniesanders.com AND is:unread
GET https://www.googleapis.com/gmail/v1/users/me/messages?q=from%3Ainfo%40berniesanders.com+AND+is%3Aunread&access_token={YOUR_API_KEY}
Response
{
"messages": [
{
"id": "1523144d6e3feb2e",
"threadId": "1523144d6e3feb2e"
},
{
"id": "15227d879ccb601f",
"threadId": "15227d879ccb601f"
}, ...
}
// No nextPageToken => response.messages.length unread = 22 unread
Request NOT unread
q = from:info#berniesanders.com AND -is:unread
GET https://www.googleapis.com/gmail/v1/users/me/messages?q=from%3Ainfo%40berniesanders.com+AND+-is%3Aunread&access_token={YOUR_API_KEY}
Response
{
"messages": [
{
"id": "1522d4af39d7eec6",
"threadId": "1522d4af39d7eec6"
},
{
"id": "1521d6f3dbeaf886",
"threadId": "1521d6f3dbeaf886"
}, ...
"nextPageToken": "32436546446"
}
// nextPageToken in response => 100+ read
You could take it one step further and keep on listing with the nextPageToken until there is no nextPageToken in the response, and just add all the results together, but that might be to slow or inefficient for your use case.