How to use MySQL query to Twilio SMS phone based on results - php

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']);
}

Related

How to send custom message before, proxy session send actual message

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
}

Invalid Registration error in GCM

I am getting following error I am trying to integrate Google Cloud Messaging in PHP to Android, Any solution
{"multicast_id":5864514048533725299,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration" }]}
PHP CODE
<?php
if (isset($_GET["regId"]) && isset($_GET["receiver_id"]) && isset($_GET["sender_id"])) {
$regId = $_GET["regId"];
$receiver_id = $_GET["receiver_id"];
$sender_id = $_GET["sender_id"];
include_once './db_functions.php';
include_once './GCM.php';
$db = new DB_Functions();
$gcm = new GCM();
//echo $sender_id. $receiver_id; exit;
$res = $db->storeUser($sender_id, $receiver_id);
$registatoin_ids = array($regId);
$message = array("message" => 'You have friend request');
$result = $gcm->send_notification($registatoin_ids, $sender_id, $receiver_id, $message);
echo $result;
}
?>
Check your device id is updated?
check whether API_key you have entered in web api is available at console.google.com?
check whether API_key belongs to the same project number you have used to generate device token?
Invalid Registration ID Check the formatting of the registration ID
that you pass to the server. Make sure it matches the registration ID
the phone receives in the com.google.android.c2dm.intent.REGISTRATION
intent and that you're not truncating it or adding additional
characters. Happens when error code is InvalidRegistration. Source
So basically you are making an error in sending the DeviceID received by the phone to the server.

This payment request must be authorized by the sender - Paypal

Ok, here is what I did:
Created a PayRequest
SetPaymentOptions - https://developer.paypal.com/webapps/developer/docs/classic/api/adaptive-payments/SetPaymentOptions_API_Operation/
ExecutePayment - "This payment request must be authorized by the sender". I have ran out of idea on why am I not able to execute the payment. From what I understand, once I execute the payment successfully, I will be given a payKey which I shall use this to redirect user to paypal. https://developer.paypal.com/webapps/developer/docs/classic/api/adaptive-payments/ExecutePayment_API_Operation/
Attached are the source codes that I used. The values are all hardcoded. I have tried my best to look through at similar questions, and it makes no sense to me as it contradicts what I understand. Some answers were pointing out that the buyer needs to approve the payment first before you executePayment.
I just want to see the details of all items when I reach the paypal login page.
//1. Obtain endpoint. For live, no need sandbox?
$endPoint = "https://svcs.sandbox.paypal.com/AdaptivePayments/Pay";
//2. Format the HTTP headers needed to make the call.
$appID = "xxx"; //Sandbox test AppID:
$username = "xxx;
$password = "xxx";
$signature = "xxx";
$paypalHeaders = array(
"X-PAYPAL-SECURITY-USERID :" . $username,
"X-PAYPAL-SECURITY-PASSWORD :" . $password,
"X-PAYPAL-SECURITY-SIGNATURE :" . $signature,
"X-PAYPAL-APPLICATION-ID :" . $appID,
"X-PAYPAL-REQUEST-DATA-FORMAT : JSON",
"X-PAYPAL-RESPONSE-DATA-FORMAT : JSON"
);
$data = array();
$data['actionType'] = "CREATE"; //PAY
$data['currencyCode'] = "SGD";
$receiver['amount'] = $orderTotal;
$receiver['email'] = $receiverEmail;
$data['receiverList'] = array();
$data['receiverList']['receiver'][] = $receiver;
$data['returnUrl'] = $returnURL;
$data['cancelUrl'] = $cancleURL;
$requestEnvelope = array();
$requestEnvelope['errorLanguage'] = "en_US";
$data['requestEnvelope'] = $requestEnvelope;
//I omitted the POST call
//print_r($returnedData);
$payKey = $returnedData->payKey;
$paymentStatus = $returnedData->paymentExecStatus;
/*
* Set payment options
*/
$endPoint = "https://svcs.sandbox.paypal.com/AdaptivePayments/SetPaymentOptions";
//paymentDetailsData
$paymentDetailsData = array();
//set payKey
echo "payKey: " . $payKey;
$paymentDetailsData['payKey'] = $payKey;
//displayOptions
$displayOptions['businessName'] = "My Business";
$paymentDetailsData['displayOptions'] = $displayOptions;
//senderOptions
$senderOptions = array();
$senderOptions['requireShippingAddressSelection'] = true; //set to true if courier is chosen
$senderOptions['shippingAddress']['addresseeName'] = "Ny Name";
$senderOptions['shippingAddress']['street1'] = "Address 1Avenue 3";
$senderOptions['shippingAddress']['street2'] = "#xx-112";
$senderOptions['shippingAddress']['city'] = "Singapore";
$senderOptions['shippingAddress']['state'] = "Singapore";
$senderOptions['shippingAddress']['zip'] = "123456";
$senderOptions['shippingAddress']['country'] = "Singapore";
$paymentDetailsData['senderOptions'] = $senderOptions;
//item
$item = array();
$item['name'] = "Korea";
$item['itemPrice'] = 11;
//there is still price, and itemcount
//invoiceData
$invoiceData = array();
$invoiceData['item'] = $item;
//receiverOptions
$receiverOptions = array();
$receiverOptions['description'] = "Product description.";
$receiverOptions['invoiceData'] = $invoiceData;
$paypalEmail = "test#test.com"; //I may need to change this
$receiver['email'] = $paypalEmail;
$receiverOptions['receiver'] = $receiver;
$paymentDetailsData['receiverOptions'] = $receiverOptions;
//requestEnvelope. I have set the request envelope above. It is the same. Can still be used.
$paymentDetailsData['requestEnvelope'] = $requestEnvelope;
makePaypalCall($endPoint, $paypalHeaders, $paymentDetailsData);
/*
* Get payment options. I can see the result of get payment options correctly,
*/
echo "GETTING PAYMENT OPTIONS";
$endPoint = "https://svcs.sandbox.paypal.com/AdaptivePayments/GetPaymentOptions";
$getPaymentData['payKey'] = $payKey;
$getPaymentData['requestEnvelope'] = $requestEnvelope;
makePaypalCall($endPoint, $paypalHeaders, $getPaymentData);
$endPoint = "https://svcs.sandbox.paypal.com/AdaptivePayments/ExecutePayment";
/*
* ExecutePayment. Ok, I get the error here. This payment request must be authorized by the sender
*/
$executePaymentData = array();
echo "paykey: " . $payKey;
$executePaymentData['payKey'] = $payKey;
//$executePaymentData['actionType'] = "PAY";
$executePaymentData['requestEnvelope'] = $requestEnvelope;
I hope I understand you correctly.
To me it seems like you are skipping the step where the user needs to authorize the payment. When you do a Pay (Create) operation you should see get a RedirectURL in the response from PayPal. You need to redirect the user to this URL for them to authorize the payment on PayPal.
Once they have approved the payment, then you'll be able to execute the payment.
Your steps need to change to:
Create PayRequest
Set PaymentOptions
Redirect to PayPal (RedirectURL from the PayRequest response) for user authorization
If authorized, ExecutePayment
PayPal hints at this on the Pay API operation page
URL to redirect the sender's browser to after the sender has logged into PayPal and approved a payment; it is always required but only used if a payment requires explicit approval
After the step 3, the user will be returned to the URL your provided in $data['returnUrl'] = $returnURL;
I am using Delayed Chained Payment and often i end up with this error "This payment request must be authorized by the sender". Actually it was due to a small mistake in the logic.
wrong procedure (# step 3)
generate a payKey successfully
save it to database
refresh the page for some reason which results in generating new payKey (this new payKey doesn't update to database)
payRequest = pay();
.....
if(empty(db_record)) {
.....
db_record->payKey = payRequest->payKey;
db_record->save();
}
paid with new payKey ( ie. payment approved by sender)
trying to execute payment with payKey from database (which is indeed old one. That payKey was not used to make payment)
Solution
update database with last payKey which used for making payment by getting approval of sender
step 3 should be like
if(empty(db_record) || is_expired(db_record->payKey)) {
payRequest = pay();
.....
.....
db_record->payKey = payRequest->payKey;
db_record->save();
}

can i send multiple messages to multiple devices at a time using GCM push plugin in php

how to send multiple messages to multiple devices at a time
$apiKey = "xxxxx";
$registrationIdArray = array('xxx_1','xxx_2');
$msg = array('message' => 'message_1','title'=> 'title_1','message' => 'message_2','title'=> 'title_2');
$pusher = new Pusher($apiKey);
$pusher->notify($registrationIdArray, $msg);
I have edited my code please use this
<?php
include_once './GCM.php';
$regid = $_POST['regid'];//your registration id array
$fields1=$_POST['message'];//your message array
$total_message = count($fields1);//count total no of message
$total_records = count($regid);//Count total number of registration id
for($j=0;$j< $total_message;$j++)//loop for sending multiple messgae
{
for($i=0;$i< $total_records;$i++)//loop for sending to multiple device
{
$registatoin_ids = array($regid[$i]);
$message = array("price" => $total_message[$j]);
$result = $gcm->send_notification($registatoin_ids, $message);
}
}
?>

Drupal 7 Not Recognizing Twilio Client in Custom Module

I have a Twilio account and I am writing a mass text message module for my Drupal site. At the beginning of the module I have set up the Twilio client with the following code:
$path = drupal_get_path("library", "twilio");
require($path . "twilio/Services/Twilio.php");
$accountSID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$authToken = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$client = new Services_Twilio($accountSID, $authToken);
$from = "xxxxxxxxxx";
The myModule_submit() queries the database for phone numbers and sends them out via the Twilio PHP libraries referenced above. I am using code found on the Twilio site for something similar here(http://www.twilio.com/docs/howto/sms-notifications-and-alerts). The problem is when I fill in the forms for the SMS message to be sent out and press submit I get the following error message:
Notice: Undefined variable: client in myModule_submit() (line 128 of /var/www/erosas/anysite.com/sites/all/modules/myModule/myModule.module).
Notice: Trying to get property of non-object in myModule_submit() (line 128 of /var/www/erosas/anysite.com/sites/all/modules/myModule/myModule.module).
Notice: Trying to get property of non-object in myModule_submit() (line 128 of /var/www/erosas/anysite.com/sites/all/modules/myModule/myModule.module).
The submit function is:
function myModule_submit($form, &$form_state){
// Retrieve the values from the fields of the custom form
$values = $form_state['values'];
// Use Database API to retrieve current posts.
$query = db_select('field_data_field_phone_number', 'n');
$query->fields('n', array('field_phone_number_value'));
// Place queried data into an array
$phone_numbers = $query->execute();
$body = $values['sms_message'];
// Iterate over array and send SMS
foreach($phone_numbers as $number){
$client->account->sms_messages->create($from, $number, $body); // This is line 128
}
}
Any thoughts/help would be greatly appreciated, I tried searching this site and Google for an answer, but nothing specific to Drupal came up.
$client object is n/a to the submit function. Try putting the same code
$path = drupal_get_path("library", "twilio");
require($path . "twilio/Services/Twilio.php");
$accountSID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$authToken = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$client = new Services_Twilio($accountSID, $authToken);
$from = "xxxxxxxxxx";
in the beginning of the submit function.
function pulsesurf_submit($form, &$form_state){
$path = drupal_get_path("library", "twilio");
require($path . "twilio/Services/Twilio.php");
$accountSID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$authToken = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$client = new Services_Twilio($accountSID, $authToken);
$from = "xxxxxxxxxx";
// Retrieve the values from the fields of the custom form
$values = $form_state['values'];
// Use Database API to retrieve current posts.
$query = db_select('field_data_field_phone_number', 'n');
$query->fields('n', array('field_phone_number_value'));
// Place queried data into an array
$phone_numbers = $query->execute();
$body = $values['sms_message'];
// Iterate over array and send SMS
foreach($phone_numbers as $number){
$client->account->sms_messages->create($from, $number, $body); // This is line 128
}
...
Better making some include function without arguments the simply includes the library files and sets the tokens/sid for ease of use.
and btw, your site's domain is in the error message.

Categories