Drupal 7 Not Recognizing Twilio Client in Custom Module - php

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.

Related

How to fix [HTTP 403] Unable to create record in twilio?

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

how do i authenticate against cybersource soap toolkit api on php

I have the following code on my index.php
<?php
// This sample demonstrates how to run a sale request, which combines an
// authorization with a capture in one request.
// Using Composer-generated autoload file.
require __DIR__ . '/vendor/autoload.php';
// Or, uncomment the line below if you're not using Composer autoloader.
//require_once(__DIR__ . '/lib/CybsSoapClient.php');
// Before using this example, you can use your own reference code for the transaction.
$referenceCode = 'holla';
$client = new CybsSoapClient();
$request = $client->createRequest($referenceCode);
// Build a sale request (combining an auth and capture). In this example only
// the amount is provided for the purchase total.
$ccAuthService = new stdClass();
$ccAuthService->run = 'true';
$request->ccAuthService = $ccAuthService;
$ccCaptureService = new stdClass();
$ccCaptureService->run = 'true';
$request->ccCaptureService = $ccCaptureService;
$billTo = new stdClass();
$billTo->firstName = 'John';
$billTo->lastName = 'Doe';
$billTo->street1 = '1295 Charleston Road';
$billTo->city = 'Mountain View';
$billTo->state = 'CA';
$billTo->postalCode = '94043';
$billTo->country = 'US';
$billTo->email = 'null#cybersource.com';
$billTo->ipAddress = '10.7.111.111';
$request->billTo = $billTo;
$card = new stdClass();
$card->accountNumber = '4111111111111111';
$card->expirationMonth = '12';
$card->expirationYear = '2020';
$request->card = $card;
$purchaseTotals = new stdClass();
$purchaseTotals->currency = 'USD';
$purchaseTotals->grandTotalAmount = '90.01';
$request->purchaseTotals = $purchaseTotals;
$reply = $client->runTransaction($request);
// This section will show all the reply fields.
print("\nRESPONSE: " . print_r($reply, true));
and the cybs.ini is like
merchant_id = "firefy"
transaction_key = "5430494897960177107046"
; Modify the URL to point to either a live or test WSDL file with the desired API version.
wsdl = "https://ics2wstest.ic3.com/commerce/1.x/transactionProcessor/CyberSourceTransaction_1.109.wsdl"
when i run the code on my local machine i get the following error messaage.
Fatal error: Uncaught SoapFault exception: [wsse:FailedCheck] Security Data : UsernameToken authentication failed. in C:\xampp\htdocs\cybersourceTest\index.php:50 Stack trace: #0 C:\xampp\htdocs\cybersourceTest\index.php(50): SoapClient->__call('runTransaction', Array) #1 {main} thrown in C:\xampp\htdocs\cybersourceTest\index.php on line 50
How do i know what caused the error above and how can i solve the above error.
I am trying to add payout api to my app and this is giving a headache right now.
Please guys help me out if anyone can.
The error “authentication failed” is saying your merchant_id and transaction_key are not correct.
Assuming that your merchant_id is correct your transaction_key is not the correct format. You can get a transaction_key by going to the business center at https://ebctest.cybersource.com then go to Account Management-> Transaction Security Keys -> Security Keys for the SOAP Toolkit API. Generate a key there.
I found out that i the url that i was pointing to was not valid or something but i fixed it by changing the endpoint of the wsdl from
wsdl="https://ics2wstest.ic3.com/commerce/1.x/transactionProcessor/CyberSourceTransaction_1.109.wsdl"
to
wsdl="https://ics2wstest.ic3.com/commerce/1.x/transactionProcessor/CyberSourceTransaction_1.151.wsdl"
That took care of everything that was wrong with the error that was popping up.

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

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

How can I tell the Google Adwords API which client/account in my MCC I am querying?

Using the latest PHP CLient Library (v2.6.3) I can't seem to figure out to get all campaigns for a client in my MCC (my client center) account.
I can easily get all accounts via:
$user = new AdWordsUser(NULL, $email, $password, $devToken, $applicationToken, $userAgent, NULL, $settingsFile);
$service = $user->GetServicedAccountService();
$selector = new ServicedAccountSelector();
$selector->enablePaging = false;
$graph = $service->get($selector);
$accounts = $graph->accounts; // all accounts!
Now that I've done that, I want to get all the campaigns within each account. Running the code as documented here doesn't work.
// Get the CampaignService.
// ** Different than example because example calls a private method ** //
$campaignService = $user->GetCampaignService('v201101');
// Create selector.
$selector = new Selector();
$selector->fields = array('Id', 'Name');
$selector->ordering = array(new OrderBy('Name', 'ASCENDING'));
// Get all campaigns.
$page = $campaignService->get($selector);
// Display campaigns.
if (isset($page->entries)) {
foreach ($page->entries as $campaign) {
print 'Campaign with name "' . $campaign->name . '" and id "'
. $campaign->id . "\" was found.\n";
}
}
All the above code will do is throw an error:
Fatal error: Uncaught SoapFault exception: [soap:Server]
QuotaCheckError.INVALID_TOKEN_HEADER # message=null
stack=com.google.ads.api.authserver.common.AuthException at
com.go;
I have a feeling that the reason this fails is that GetCampaignService needs an account's id...but I can't figure out how to specify this id.
What am I doing wrong?
The problem ended up being that I was given the wrong developerToken. I didn't think INVALID_TOKEN_HEADER really meant what it said because SOME calls still worked with the faulty token. I don't know why.

Dialogflow V2 API - How to pass context and/or payload [PHP]

I am trying to send context and payload to the Dialogflow V2 API. I am able to successfully send a queryString and get a response from my agent. However, I need to pass context and payload parameters with this query and I cannot seem to find ANY help on this for PHP. Please see my code below. I am able to create the context object and the payload object (atleast I think its created), but how do I pass it to the API?
Any help would be appreciated as I am very new to dialogflow and have been struggling with this for a few days now.
function detect_intent_texts($projectId, $text, $sessionId, $context, $parameters, $languageCode = 'en-US') {
// new session
$test = array('credentials' => 'client-secret.json');
$sessionsClient = new SessionsClient($test);
$session = $sessionsClient->sessionName($projectId, $sessionId ?: uniqid());
//printf('Session path: %s' . PHP_EOL, $session);
// create text input
$textInput = new TextInput();
$textInput->setText($text);
$textInput->setLanguageCode($languageCode);
$contextStruct = new Struct();
$contextStruct->setFields($context['parameters']);
$paramStruct = new Struct();
$paramStruct->setFields($parameters['parameters']);
$contextInput = new Context();
$contextInput->setLifespanCount($context['lifespan']);
$contextInput->setName($context['name']);
$contextInput->setParameters($contextStruct);
$queryParams = new QueryParameters();
$queryParams->setPayload($paramStruct);
// create query input
$queryInput = new QueryInput();
$queryInput->setText($textInput);
// get response and relevant info
$response = $sessionsClient->detectIntent($session, $queryInput); // Here I don't know how to send the context and payload
$responseId = $response->getResponseId();
$queryResult = $response->getQueryResult();
$queryText = $queryResult->getQueryText();
$intent = $queryResult->getIntent();
$displayName = $intent->getDisplayName();
$confidence = $queryResult->getIntentDetectionConfidence();
$fulfilmentText = $queryResult->getFulfillmentText();
$returnResponse = array(
'responseId' => $responseId,
'fulfillmentText' => $fulfilmentText
);
$sessionsClient->close();
return $returnResponse;
}
Just as it happens, the moment I post my question, I get a result.
Thanks to this post How to set query parameters dialogflow php sdk.
I added the following to my code and it worked.
Added
$optionalsParams = ['queryParams' => $queryParams];
Changed
$response = $sessionsClient->detectIntent($session, $queryInput, $optionalsParams);

Categories