Connecting to Twilio API using PHP - php

The example code asks for a $sid and $token.
I logged in to my account and went to Dev Tools → API Keys and created a new key which generated a Sid and Secret.
I went back to Account Settings → API Credentials and I have a AccountSID and AuthToken but the AccountSID is not the same as the Sid shown at Dev Tools → API Keys.
So I have 4 different strings, what am I suppose to do with them? What is the $sid that the example code asks for, is it the Sid in Dev Tools - API Keys or the AccountSID in Account Settings → API Credentials, and what on earth is the $token, I don't see this anywhere?
I've tried using a mixture on the below example code, with PHP error logging enabled, but it just causes the page to load as Server Error 500.
<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once('/twilio-php-master/Services/Twilio.php'); // Loads the library
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "";
$token = "";
$client = new Services_Twilio($sid, $token);
// Loop over the list of numbers and echo a property for each one
foreach ($client->account->incoming_phone_numbers as $number) {
echo "<select>" . $number->phone_number . "</select>";
}
Side note: Does Twilio charge for API calls (actual API usage, not purchasing etc.)?

Twilio developer evangelist here.
I can see how that got confusing. For what you're trying to do, you can just grab the AccountSid and AuthToken from your dashboard. Once you're there, just expand "Show API Credentials" and copy the values.
As for your question, Twilio will not charge for requests like the one you're trying to make. Worth having a look at our billing and pricing FAQ to get some more information.
Hope this helps you

Related

Need Email Address from Google with Access Token that we receive from Alexa Skill?

I was able to Link Account using Google Auth v2 in Alexa Skill. And I am able to get Access Token. Now I want to get the Google Email address with which user has used to link account. So how can I get that Google Email Address?
Use the Oauth2 Scope "https://www.googleapis.com/auth/userinfo.email".
Add the scope to your Google Client (Example with the Google Library for PHP):
$googleClient = new Google_Client();
// Your code here with Client ID, Secret, ...
$googleClient->addScope('https://www.googleapis.com/auth/userinfo.email');
That'll give you the E-Mail of the user.
if(isset($_GET['code'])) {
// Your code here, the login code is in $_GET['code']
/**
* Get access token
*/
$token = $googleClient->fetchAccessTokenWithAuthCode($_GET['code']);
$googleClient->setAccessToken($token['access_token']);
// Create Google Auth Service with the Google Client
$google_auth = new Google_Service_Oauth2($googleClient);
// Get the userinfo
$google_auth_info = $google_auth->userinfo->get();
// Get the E-Mail:
$email = $google_auth_info->email;
}
I think the part you're looking for is authinfo->get()->email, but i added a bit more context so you see how to use this.
Don't forget to enable this scope also in your Google Developers Console:
https://console.cloud.google.com/apis/credentials/consent -> Edit -> Step 2: Scopes

How to get Business Locations (and Reviews) via Service Account authentication

I can't get the Locations list from my business under my code (PHP using the "Google APIs Client Library for PHP" together with "Google_Service_MyBusiness" Classes) when I use the "Service Account" authentication, the API returns an empty Location List.
I already have the Prerequisites and did the Basic setup, by the way, I got the information with success on OAuth Playground, under a specific AccountId, Eg: 1111111111, provided by another response there on the "OAuth Playground".
(PS: I tested with my "PERSONAL" and "LOCATION_GROUP" accounts and got success with both).
But when I try to do it over my code via Server Account authentication, I can't get all the information, just the Account data that return another AccoundId, Eg: 2222222222, different of the Accounts that I got on OAuth Playground.
I did the Authentication process on OAuth Playground, using the same project where I created the "Service Account", by the way, the Permission of this "Service Account" is OWNER.
Previously, my role in my company on the Google My Business was "SITE_MANAGER", so I saw a forum answer where just "MANAGER" level/role can list the Locations, so I requested to change my permission, but continues as not the success on Locations listing.
So, I saw another Google My Business support article recommending create a "Location Group" and put my current "Location" into this group to make easy handle it, I did it and no success again.
My code is simple, based on Google guide, OAuth 2.0 for Server to Server Applications, and some Forum Questions (BTW the author's question have the same issue than me):
<?php
putenv('GOOGLE_APPLICATION_CREDENTIALS=service-account-credentials.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope("https://www.googleapis.com/auth/plus.business.manage");
require_once('Google_Service_MyBusiness.php');
$mybusinessService = new Google_Service_MyBusiness($client);
$accounts = $mybusinessService->accounts;
$accountsList = $accounts->listAccounts()->getAccounts();
foreach ($accountsList as $accKey => $account) {
var_dump('$account->name', $account->name);
$locations = $mybusinessService->accounts_locations;
$locationsList = $locations->listAccountsLocations($account->name)->getLocations();
var_dump('$locationsList', $locationsList);
// Final Goal of my Code
if (empty($locationsList)===false) {
foreach ($locationsList as $locKey => $location) {
$reviews = $mybusinessService->accounts_locations_reviews;
$listReviewsResponse = $reviews->listAccountsLocationsReviews($location->name);
$reviewsList = $listReviewsResponse->getReviews();
var_dump('$reviewsList', $reviewsList);
}
}
}
I expected the Location of my business (also the reviews, but it a next step), but I just got the empty Location list.
Finally, I got success using the ClientId/ClientSecret keys together with Refresh Token previously received on Google OAuth 2 Playground on the first time that I give permission to (my) App, instead "Service Account" authentication way :)
$client = new Google_Client();
$client->setClientId($clientId);
$client->setClientSecret($clientSecret);
$client->addScope("https://www.googleapis.com/auth/plus.business.manage");
$client->setSubject('my email user on GMB');
$client->refreshToken(' ###### ')
Now I got all the needed data for my application.

SageOne Accounts API in PHP

I have found an API class (https://github.com/eddieharrison/sageone-api-php) in PHP for the SageOne Accounts Cloud Software.
I used the code found in auth.php with my apps CLIENT_ID and CLIENT_SECRET to gain an access code.
I then tried this code (/examples/get-ledger-accounts.php):
define('SAGE_CLIENT_ID', 'my client id');
define('SAGE_CLIENT_SECRET', 'my client secret');
// If you do not already have an access token please see:
// /examples/auth.php
define('SAGE_ACCESS_TOKEN', 'access code from auth.php');
$client = new SageOne(SAGE_CLIENT_ID, SAGE_CLIENT_SECRET);
$client->setAccessToken(SAGE_ACCESS_TOKEN);
$result = $client->getLedgerAccounts();
echo '<pre>';
print_r($result);
echo '</pre>';
however when testing this code, i get the following:
string(26) "{"error":"invalid_token"} " int(0)
Array
(
[error] => invalid_token
)
Does anyone know what this means and how i can fix it to gain access to our accounts data from SageOne?
Assuming you have signed up via developers.sageone.com, an invalid_token error is expected if you try to use the token beyond the expiration time, which is 1 hour after issuance.
Another thing I noticed is that the library you mentioned does not support the request signing which is required.
Are you working on a client app or accounting integration?
I've put up a wrapper for the Sage One Accounting API v 1.1.1, which uses an Api Key instead of clientId / accessToken. This will work better if you're going for automation.
https://github.com/Sharnw/sage-one-accounting-api
API docs here: https://accounting.sageone.co.za/Marketing/DeveloperProgram.aspx

Google Apps Admin SDK Directory API 403 in PHP

I'm getting
Error calling GET https://www.googleapis.com/admin/directory/v1/users/email#example.com.com: (403) Not Authorized to access this resource/api
when running
$client = new Google_Client();
$client->setClientId(GOOGLEAPPS_CLIENT_ID);
$client->setApplicationName(SITE_NAME);
$key = file_get_contents(APPLICATION_PATH . 'googleapps-privatekey.p12');
$assertion = new Google_AssertionCredentials(
GOOGLEAPPS_EMAIL_ADDRESS, // the service account name
array('https://www.googleapis.com/auth/admin.directory.user'), // see https://developers.google.com/admin-sdk/directory/v1/guides/authorizing
$key);
$client->setAssertionCredentials($assertion);
$service = new Google_DirectoryService($client);
$user = $service->users->get('email#example.com');
I followed the instructions https://developers.google.com/admin-sdk/directory/v1/guides/prerequisites
and ticked Enable API Access. I used the Google APIs console https://code.google.com/apis/console to generate a Service Account key and got that working OK.
https://groups.google.com/forum/#!msg/google-api-php-client/LM-mwmuZe7I/IA_K5v1R1UMJ
I used the Google PHP library and followed the instructions https://code.google.com/p/google-api-php-client/wiki/OAuth2?hl=no#Service_Accounts to try and get service accounts working. Debugging into their code: I'm authorising fine and getting a fresh Access token as expected https://developers.google.com/accounts/docs/OAuth2ServiceAccount.
I can't figure out why I'm getting the "Not Authorized to access this resource/api" message when everything I have read says I've switched it all on OK. Any ideas?
Just got it working. You need to include the user email of the admin so oAuth authorizes you for that user. Try
$assertion = new Google_AssertionCredentials(
GOOGLEAPPS_EMAIL_ADDRESS, // the service account name
array('https://www.googleapis.com/auth/admin.directory.user'), // see https://developers.google.com/admin-sdk/directory/v1/guides/authorizing
$key,
'notasecret',
'http://oauth.net/grant_type/jwt/1.0/bearer',
'admin_user#email.com'
);
Also after that you need to authorize the client_id for the scope you are requesting from Admin console->Security->Advanced Settings->Authentication->Manage OAuth Client access
I was having a similar problem. I'm using the .NET libraries. The [DriveService][1] example was missing a parameter when creating the provider: ServiceAccountUser, which appears to have to be the email address of an ADMIN. I missed that it was an admin and was getting:
Not Authorized to access this resource/api [403]
as soon as I switched it to an admin account, it worked. I'm afraid I don't speak PHP but I hope this helps.
If you get an error
Class 'Google_AssertionCredentials' not found
you are using the newer libraries, and Google_AssertionCredentials is now Google_Auth_AssertionCredentials.
See:
https://github.com/google/google-api-php-client/blob/master/src/Google/Auth/AssertionCredentials.php
Did you grant the service account access to the given scopes within your Control Panel? See the instructions in the Drive SDK and substitute in the Admin SDK scopes as needed.

Connecting to the Google Sites API as a "Service Account"

I am trying to read a feed from a Google Sites account (Google apps).
I don't need my app to require every user to login so i created my ClientID as a "Service Account" in the "Google API console".
I have added this Client ID and the scope (https://sites.google.com/feeds/) to the "Mange API client access" page in my google apps control panel.
I connect using the code below, all constants are defined in my code with the right values.
// api dependencies
require_once(GOOGLE_API_PATH);
// create client object and set app name
$client = new Google_Client();
$client->setApplicationName(GOOGLE_API_NAME);
// set assertion credentials
$client->setAssertionCredentials(
new Google_AssertionCredentials(
GOOGLE_API_EMAIL,
array(GOOGLE_API_SCOPE),
file_get_contents(GOOGLE_API_PK)
));
$client->setClientId(GOOGLE_API_CLIENTID);
// create service
$req = new Google_HttpRequest("https://sites.google.com/feeds/content/<herismydomainname.com>/intranet");
$val = $client->getIo()->authenticatedRequest($req);
// The contacts api only returns XML responses.
$response = json_encode($val->getResponseBody());
print "<pre>" . print_r(json_decode($response, true), true) . "</pre>";
The response i get is "Not authorized to access this feed "
When i try to get this feed in the OAuth2.0 playground logging in using my google apps account i get the expected response.
What am i overlooking here?
Service accounts and Google Sites can't be used together currently. Google Apps provides a consumer secret that can be used to access data across your domain as Two-Legged OAuth within OAuth 1.0a.
Check out http://support.google.com/a/bin/answer.py?hl=en&answer=162105 for how to configure your Apps account, and the sample code at https://developers.google.com/gdata/docs/auth/oauth#2LeggedOAuth.

Categories