I'm trying to use Google Cloud Storage in my PHP project - but not on the AppEngine platform. All the links and tutorials I found always use the AppEngine platform and therefor can use the gs:// links. Does anyone know how to connect and for example list objects in a bucket - or at least connect to the storage trough php without AppEngine?
try this code:
set_include_path("../src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once("Google/Service/Storage.php");
$client_id = '<client-id>'; //Client ID
$service_account_name = '<service_account_name(email)>'; //Email Address
$key_file_location = 'key.p12'; //your key.p12 file
echo pageHeader("Service Account Access");
if ($client_id == '<YOUR_CLIENT_ID>'
|| !strlen($service_account_name)
|| !strlen($key_file_location)) {
echo missingServiceAccountDetailsWarning();
}
$client = new Google_Client();
$client->setApplicationName("<your application name>");
$service = new Google_Service_Storage($client);
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/devstorage.full_control'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$acl = new Google_Service_Storage_ObjectAccessControl();
$acl->setEntity('allUsers');
$acl->setRole('READER');
$acl->setBucket('<your bucket name>');
$acl->setObject('your object name');
$service = new Google_Service_Storage($client);
$return_value = $service->objects->get('<bucket_name>','<object-name>');
You can use the JSON api.
To see it in action go here:
https://developers.google.com/apis-explorer/#p/storage/v1/storage.objects.list
Then enable OAuth2 in the top right and fill in your bucket name to see an example request and response.
Related
I'm just starting to use the api libraries from google and I'm having some trouble accessing to user data. For experimentation I used code from a previos question in this field.
My code executes a petition for the google search console api but it returns an empty array. I autorized the service account from the admin console (https://developers.google.com/identity/protocols/OAuth2ServiceAccount) so I don't know why doesn't it return anything.
set_include_path(get_include_path() . PATH_SEPARATOR . '$path/google-api-php-client-master/src');
require_once realpath('$path/google-api-php-client-master/src/Google/autoload.php');
$client_id = "my-client-id";
$service_account_name = "my-service-account-name#developer.gserviceaccount.com";
$key_file_location = "privatekey.p12";
$client = new Google_Client();
$client->setApplicationName("WMtools_application");
$service = new Google_Service_Webmasters($client);
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/webmasters.readonly'),
$key
);
try{
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
}catch(Exception $e){
echo "Exception captured", $e->getMessage(), "\n";
}
try{
$results = $service->sites->listSites();
$siteList = $results->siteEntry;
var_dump($siteList);
}catch(Exception $e2){
echo "No results", $e2->getMessage(), "\n";
}
I solved the problem. The case is that i have delegated domain-wide authority to my service account and I didn't include in my petition to the API the user email from whom I want to access the data. To solve It just need to add it to the google_Auth_AssertionCredentials this way:
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/webmasters.readonly'),
$key
);
$cred->sub = $service_account_user_email; //example#google.com
I have a problem just using an example of actual version of PHP api, and using the "service-account.php" file of examples folder.
the original is for show the "Books API", and with my personal credentials configuration it works well, but in my xcase I need to access by directory.groups.get service to have the list of members accounts of a google groups mail list, so I change the original code in this:
<?php
session_start();
include_once "templates/base.php";
/************************************************
Make an API request authenticated with a service
account.
************************************************/
require_once realpath(dirname(__FILE__) . '/../autoload.php');
/************************************************
************************************************/
// MY ACCOUNT DATA HERE
$client_id = 'xxx';
$service_account_name = 'xxx'; //Email Address
$key_file_location = 'xxx.p12'; //key.p12
$groupKey = 'xxx';
echo pageHeader("My Service Account Access");
if ($client_id == '<YOUR_CLIENT_ID>'
|| !strlen($service_account_name)
|| !strlen($key_file_location)) {
echo missingServiceAccountDetailsWarning();
}
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
//$service = new Google_Service_Books($client); //ORIGINAL
$service = new Google_Service_Directory($client);
/************************************************
************************************************/
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$authArray = array(
'https://www.googleapis.com/auth/admin.directory.group',
'https://www.googleapis.com/auth/admin.directory.group.readonly',
'https://www.googleapis.com/auth/admin.directory.group.member',
'https://www.googleapis.com/auth/admin.directory.group.member.readonly'
);
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
$authArray, //array('https://www.googleapis.com/auth/books'), //ORIGINAL
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
/************************************************
************************************************/
//$optParams = array('filter' => 'free-ebooks'); //ORIGINAL
$optParams = array('fields' => 'id');
//$results = $service->volumes->listVolumes('Henry David Thoreau', $optParams); //ORIGINAL
$results = $service->groups->get($groupKey, $optParams);
echo "<h3>Results Of Call:</h3>";
foreach ($results as $item) {
//echo $item['volumeInfo']['title'], "<br /> \n"; //ORIGINAL
echo "<pre>".print_r ($item, true)."</pre>";
}
echo pageFooter(__FILE__);
whatever I do, providing authorization for API SDK, and using file and credentials just created in API Credentials panel of the console's developer, I receive alwais the 403 error.
Here's the error stack:
#0 /var/www/html/google_local/google-api-php-client-master/src/Google/Http/REST.php(41):
Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request))
#1 /var/www/html/google_local/google-api-php-client-master/src/Google/Client.php(546):
Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#2 /var/www/html/google_local/google-api-php-client-master/src/Google/Service/Resource.php(190):
Google_Client->execute(Object(Google_Http_Request))
#3 /var/www/html/google_local/google-api-php-client-master/src/Google/Service/Directory.php(1494):
Google_Service_Resource->call('get', Array, 'Google_Service_...')
#4 /var/www/html/google_local/googl in /var/www/html/google_local/google-api-php-client-master/src/Google/Http/REST.php on line 76
Any suggestions?
Thanks,
Roberto
The root of the problem is that the service account is not an administrator on the domain, so it cannot access the Admin SDK Directory API. Instead, you need to enable domain-wide delegation for your service account, and then have the service account impersonate a domain admin when it makes the request:
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
$authArray,
$key
);
$cred->sub = "admin#yourdomain.com";
I'm trying to get access bigquery api using PHP library, but I always have this error:
Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/bigquery/v2/projects/primeval-shadow-571/datasets/Test/tables: (401) Login Required' in ...
I have a web application, that needs to get some data from table in bigquery. The Remote account is not mine, but it was created by some guy (and I don't have login and pass to log in), who gave me the .json file which included thoose parameters:
auth_uri,
client_secret,
token_uri,
client_email,
client_x509_cert_url,
client_id and
auth_provider_x509_cert_url.
Here is my php code:
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Bigquery.php';
$client = new Google_Client();
$client->setAuthConfigFile('google-config.json');
$service = new Google_Service_Bigquery($client);
$service->tables->listTables('primeval-shadow-571', 'Test');
But finally I got error that's above.
Can anybody tell me where am I wrong?
P.S. I just started work with google api two days ago, so I'm just beginning learn it.
Thanks a lot.
Here is a sample code that works for us:
session_start();
define('PROJECT_ID', 'edited');
define('DATASET_ID', 'edited');
define('API_KEY', 'edited');
$client_id = 'edited';
$service_account_name = 'edited';
$key_file_location = '.ssh/privatekey-bigquery.p12';
$service_token_file_location = 'bigquery_current_service_token.json';
set_include_path("google-api-php/src/" . PATH_SEPARATOR . get_include_path());
require_once 'google-api-php/src/Google/Client.php';
require_once 'google-api-php/src/Google/Service/Bigquery.php';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
//$client->setDeveloperKey(API_KEY);
if (!is_file($service_token_file_location)) {
if (!is_writable($service_token_file_location)) {
#chmod($service_token_file_location, 0777);
if (!is_writable($service_token_file_location)) {
die('Service token file is not writable: ' . $service_token_file_location);
}
}
file_put_contents($service_token_file_location, '');
} else {
if (!is_writable($service_token_file_location)) {
#chmod($service_token_file_location, 0777);
if (!is_writable($service_token_file_location)) {
die('Service token file is not writable: ' . $service_token_file_location);
}
}
}
$service_token = #file_get_contents($service_token_file_location);
if (!empty($service_token)) {
$client->setAccessToken($service_token);
}
if (!file_exists($key_file_location)) {
die('Key file is missing: ' . $key_file_location);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name, array(
'https://www.googleapis.com/auth/bigquery',
), $key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service_token = $client->getAccessToken();
file_put_contents($service_token_file_location, $service_token);
// start using $client
I am trying to access my Google Drive files from a php script that will be run in a cron job, but I can't see my files.
I am using a Service account set up in Google Developpers console, which do not need authorisation interaction with the user (me).
This is my code:
require_once 'Google/Client.php';
require_once 'Google/Service/Drive.php';
$client_id = '260186860844-kg9uiqe7pjms3s54gabqfnph0iamjdjn.apps.googleusercontent.com';
$service_account_name = '260186860844-kg9uiqe7pjms3s54gabqfnph0iamjdjn#developer.gserviceaccount.com';
$key_file_location = 'privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("Whatever");
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/drive'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$service = new Google_Service_Drive($client);
$parameters = array(
// 'maxResults' => 10,
);
$dr_results = $service->files->listFiles($parameters);
foreach ($dr_results as $item) {
echo $item->title, "<br /> \n";
}
It seems I am correctly connected (got token, no errors prompted), but I only get one single file listed, which is not part of my Drive, and which is named "How to get started with Drive"!
I am using latest Google APIs Client Library for PHP , with php 5.4
Google will create its own google drive for service account.
What you need to do is SHARE your folder with service's account email from console.
Give it permission "can edit".
I made a shared folder in my GUI accessible drive, then I insert the files from the commandline under this folder shared, so I see them ;)
I am implementing cloud storage api in php for uploading mp3 files and loading those in site.
I want to upload the files without authorization dialog is that possible? is there any sample without oauth2?
Everything going to cloud storage needs auth key. You can set up a service account get a bearer key without the user logging in. I modified some code from google-api-php-client. To provide the bearer key. Using the following.
function getMediaKey(){
/************************************************
Make an API request authenticated with a service
account.
************************************************/
set_include_path("../google-api-php-client/src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
$client_id = '<your clientid>';
$service_account_name = '<serviceaccountemail';
$key_file_location = '< location of you privatekey.p12>';
//echo pageHeader("Service Account Access");
if ($client_id == '<YOUR_CLIENT_ID>'
|| !strlen($service_account_name)
|| !strlen($key_file_location)) {
echo missingServiceAccountDetailsWarning();
}
$client = new Google_Client();
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/devstorage.full_control'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$bearerKey = $client->getAccessToken();
return $bearerKey;
}
Then you can post your media files using the bearer key.
checkout https://developers.google.com/storage/docs/json_api/
Try it for examples