Using Twilio API in Phalcon3 - twilio

I want to integrate Twilio SMS Api in Phalcon 3 using dependency injection.It would be great if anyone could guide me in this process.

Just like any other PHP library that you want to use, you first need to check what is the installation method.
As noted by Nikolay Mihaylov in the comments, check the documentation for Twillo here:
https://www.twilio.com/docs/libraries/php
As you will see they do offer an installation through composer. All you need to do in your project then is:
composer require twilio/sdk
Registering Twillo in your DI container is the same as any other service:
// Your Account SID and Auth Token from twilio.com/console
$config = [
'sid' => 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
'token' => 'your_auth_token',
]
// $di is the DI container
// Using the $config variable in the current scope
$di->set(
'db',
function () use ($config) {
$sid = $config['sid'];
$token = $config['token'];
$client = new \Twilio\Rest\Client($sid, $token);
return $client;
}
);
References:
https://docs.phalconphp.com/en/latest/reference/di.html
https://www.twilio.com/docs/libraries/php

Related

How to switch an ongoing Twilio phone call to a <Pay> connector

I would like to use the < Pay> connector optionally while in an ongoing phone call. I cannot find out how to do trigger a new resource during an ongoing phone call.
You can modify an "in progress" call by passing new TwiML (XML) to execute which could contain your "<Pay>".
You must provide
the ID of the call you want to modify (the "CallSid" "CAe1644a7eed5088b159577c5802d8be38")
and an URL where Twilio will find the instructions (the "Url" "http://demo.twilio.com/docs/voice.xml")
I don't know what language you're using but in PHP with Twilio's library the code would look someting like this:
// see https://getcomposer.org/doc/01-basic-usage.md
require_once '/path/to/vendor/autoload.php';
use Twilio\Rest\Client;
// Find your Account Sid and Auth Token at twilio.com/console
// DANGER! This is insecure. See http://twil.io/secure
$sid = "ACc0966dd96e4d55d26ae72df4d6dc3494";
$token = "your_auth_token";
$twilio = new Client($sid, $token);
$call = $twilio->calls("CAe1644a7eed5088b159577c5802d8be38")
->update(array(
"method" => "POST",
"url" => "http://demo.twilio.com/docs/voice.xml"
)
);
print($call->to);
You can read more about this here
(https://www.twilio.com/docs/voice/tutorials/how-to-modify-calls-in-progress).

How to record-from-answer-dual with Twilio's object oriented interface?

I understand how to enable the 'record-from-answer-dual' with the XML style command set, but I'm not finding any way to accomplish the same thing with the more object-oriented style code, such as:
<?php
require_once 'twilio-php-master/Twilio/autoload.php';
$response = new Twilio\Twiml();
$sayMsg = 'Attention! Attention! The network operations
center has opened a ticket concerning an ATMS failure in the Eastern
region. The ticket number is ECHO,1,5,7,4. I repeat, the ticket number is
ECHO,1,5,7,4. Thank you.';
$response->record();
$response->say($sayMsg, array('voice' => 'alice'));
$response->hangup();
echo $response;
I've tried adding it to the new line, and the record line as an array-style entry, similar to enabling the Alice voice. No dice.
I want to record the entire call, from answer, including the message spoken by Twilio.
Thanks for any information anyone can provide!
Twilio developer evangelist here.
<Record> is used to record messages from a call, not to record the TwiML that follows. It's more useful if you are building a messaging or voicemail system for voice.
Given that your message sounds like some kind of announcement, I am guessing that you are generating this call from the REST API. In that case, you can use the Record parameter when you place the call and the entire call will be recorded. In PHP, that would be something like this:
require_once '/path/to/vendor/autoload.php';
use Twilio\Rest\Client;
// Your Account Sid and Auth Token from twilio.com/console
$sid = "your_account_sid";
$token = "your_auth_token";
$client = new Client($sid, $token);
$call = $client->calls->create(
$to, $from,
array(
"url" => $url,
"record" => true
)
);
Check out the documentation on the parameters you can use when making a call, including Record here.
Let me know if that helps at all.
Update from Jeffrey's comment
This is the Perl version, using the unofficial Twilio Perl module:
use WWW::Twilio::API;
my ($twilaccountsid, $twilauthtoken, $fromnum, $tonum, $twiml_uri) = #_;
my $twilio = WWW::Twilio::API->new(AccountSid => $twilaccountsid, AuthToken => $twilauthtoken);
my $response = $twilio->POST( 'Calls', From => $fromnum, To => $tonum, Record => 'true', Url => $twiml_uri);
return $response->{content};

How to get "clientCustomerId" from Adwrods API in PHP with OAuth?

I am developing a Google Adwords app. I tried using the API libraries available in PHP. I found, I need "clientCustomerId" in "adsapi_php.ini". I don't see anyway to get this "clientCustomerId" using API with OAuth. Am I trying something wrong?
This really depends on your application design.
My setup is using a top-level manager account that has access to all the client accounts.
clientCustomerID is set to that manager id.
With that, you can grab a list of your clients using the ManagedCustomerService->get() method provided by the PHP library. You can look at the example code here:
https://github.com/googleads/googleads-php-lib/blob/master/examples/AdWords/v201710/AccountManagement/GetAccountHierarchy.php
That repo is now depreciated. As of Oct 2018 you should use this documentation: https://github.com/googleads/googleads-php-lib/blob/master/examples/AdWords/v201802/AccountManagement/GetAccountHierarchy.php
Try CustomerService
CustomerService provides information about your accounts. It has a
getCustomers() method that takes no arguments and returns a list of
Customer objects containing fields such as customerId, currencyCode,
and dateTimeZone. CustomerService
Reference: Managing Accounts
Google Adwords Authencation code ( Using PHP Client Lib )
You may check code samples from Google Adwords PHP sample
Get Credentials for API use
$oauth2 = new OAuth2([
'authorizationUri' => 'https://accounts.google.com/o/oauth2/v2/auth',
'tokenCredentialUri' => 'https://www.googleapis.com/oauth2/v4/token',
'redirectUri' => 'http://localhost/adwordsWork/index.php',
'clientId' => '1139632-xxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
'clientSecret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'scope' => 'https://www.googleapis.com/auth/adwords'
]);
if (!isset($_GET['code'])) {
$oauth2->setState(sha1(openssl_random_pseudo_bytes(1024)));
$_SESSION['oauth2state'] = $oauth2->getState();
$config = [
'access_type' => 'offline'
];
header('Location: ' . $oauth2->buildFullAuthorizationUri($config));
exit;
}
elseif (empty($_GET['state'])
|| ($_GET['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
exit('Invalid state.');
} else {
$oauth2->setCode($_GET['code']);
$authToken = $oauth2->fetchAuthToken();
$refresh_token = $authToken['refresh_token'];
}
/* --------------------------- Authencation section End --------------------------------*/
// echo "<pre>";
// print_r($authToken);
// die;
/*---------------------------- Session Builder -----------------------------------------*/
$session = (new AdWordsSessionBuilder())
->fromFile('adsapi_php.ini')
->withOAuth2Credential($oauth2)
->build();
/* ------------------------- Session build ---------------------------------------------*/
/* -------------------------------- Adwords Services section ----------------------------*/
/* Creating object of Adwords services */
$adWordsServices = new AdWordsServices();
/* Adwords Customer services */
$customerService = $adWordsServices->get($session, CustomerService::class);
$customers = $customerService->getCustomers();
$customerId = $customers[0]->getCustomerId(); // Getting main customer client id
echo $customerId; // customer id from adwords account

Twilio REST API How to get Sid

I am still new to Twilio. I am writing a PHP script which will connect to Twilio and parse some information about calls. I am using the code from this page:
https://www.twilio.com/docs/api/rest/call
Here is my code:
require_once '../twilio-library/Services/Twilio.php';
// Twilio REST API version
$version = '2010-04-01';
// Set our AccountSid and AuthToken
$sid = 'abc132xxxxx';
$token = 'xxxxeeffv';
// Instantiate a new Twilio Rest Client
$client = new Services_Twilio($sid, $token, $version);
// Loop over the list of calls and echo a property for each one
foreach ($client->account->calls as $call) {
echo "->".$call->Sid."<- <br/>";
}
The browser just outputs many blanks. No Sid values. What am I doing wrong?
Twilio Developer Evangelist here.
Try doing the following to get call information.
<?php
require_once '../twilio-library/Services/Twilio.php';
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = 'abc132xxxxx';
$token = 'xxxxeeffv';
$client = new Services_Twilio($sid, $token);
// Loop over the list of calls and echo a property for each one
foreach ($client->account->calls as $call) {
echo $call->sid;
}
Notice that if you're using the latest version of the library, you don't need to specify a version on your request. Double check that the path ../twilio-library/Services/Twilio.php is correct for you though.
If you're only testing, you could move the file Twilio.php to the same directory where your code is and just import Twilio.php on it.
If you then decide to filter the logs by date, here's how you would do it.
// Loop over the list of calls and echo a property for each one
foreach ($client->account->calls->getIterator(0, 50, array(
"Status" => "completed",
"StartTime>" => "2015-03-01",
"StartTime<" => "2015-05-10"
)) as $call
) {
echo $call->sid;
}
Let me know how it goes.

Google Analytics API Returning 401 On Example Code

I am attempting to retrieve the data from our content experiments from google analytics...
I am using the following code, my creds are good, and have been censored for this post...
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName('Hello Analytics API Sample');
// Visit https://cloud.google.com/console to generate your
// client id, client secret, and to register your redirect uri.
$client->setDeveloperKey('xxxxx');
$service = new Google_Service_Analytics($client);
try {
$results = $service->management_experiments->listManagementExperiments('xxxx', 'xxxx', 'xxxx');
} catch (apiServiceException $e) {
print 'There was an Analytics API service error ' . $e->getCode() . ':' . $e->getMessage();
} catch (apiException $e) {
print 'There was a general API error ' . $e->getCode() . ':' . $e->getMessage();
}
echo '<pre>';
print_r($results);
echo '</pre>';
I am using the following example ....
https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtExperimentsGuide#list
Any ideas on why I am getting a 401 unauthorized? That a login is required?
The problem is that you haven't Authorized access to your data yet. Since you say its only your own data you want to access i sugest you look into a service account. By setting up a service account in Google apis console it will allow you to access your own data with out needing to login and autenticate the code all the time.
Check the following link. Read though Before you begin make sure you do all that.
https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtExperimentsGuide#service
Register your application in the Google Developers Console
Authorize access to Google Analytics data.
Create an Analytics service object
You have skiped the first two steps and gone directly to step 3 creating the service object. Once you have done step 1 you can use the following code for step 2.
Here is an example of how to use a service account in php ServiceAccount
That sample project is for the PredictionService not the google analytics service. You need to edit it slightly.
require_once '../../src/Google/Client.php';
require_once '../../src/Google/Service/Analytics.php';
// Set your client id, service account name, and the path to your private key.
// For more information about obtaining these keys, visit:
// https://developers.google.com/console/help/#service_accounts
const CLIENT_ID = 'INSERT_YOUR_CLIENT_ID';
const SERVICE_ACCOUNT_NAME = 'INSERT_YOUR_SERVICE_ACCOUNT_NAME';
// Make sure you keep your key.p12 file in a secure location, and isn't
// readable by others.
const KEY_FILE = '/super/secret/path/to/key.p12';
$client = new Google_Client();
$client->setApplicationName("Google Analytics Sample");
// Load the key in PKCS 12 format (you need to download this from the
// Google API Console when the service account was created.
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME(Email),
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents(KEY_FILE))
);
$client->setClientId(CLIENT_ID);
$service = new Google_Service_Analytics($client);
Now you have $service that you can use with the rest of your calls. Note: I didnt have time to test that code let me know if it doesnt work and i will give you a hand in fixing it.

Resources