GCP BigQuery PHP client get list of projects - php

This is my current code that brings back just one project.
How can i get a list of all accessible projects?
# Includes the autoloader for libraries installed with composer
require __DIR__ . '/../vendor/autoload.php';
# Imports the Google Cloud client library
use Google\Cloud\BigQuery\BigQueryClient;
$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/../gcp-bigquery-key.json');
$scopes = implode(' ', [Google_Service_Bigquery::BIGQUERY]);
$client->setScopes($scopes);
$service = new Google_Service_Bigquery($client);
$tQ = $service->projects->listProjects();
print_r($tQ);

I see that you are using BigQuery token for as authorisation. As that key is valid for BigQuery, you are getting the project which contains that BigQuery.
For seeing all projects you can check this code found in the documentation [1]:
require_once __DIR__ . '/vendor/autoload.php';
$client = new Google_Client();
$client->setApplicationName('Google-CloudResourceManagerSample/0.1');
$client->useApplicationDefaultCredentials();
$client->addScope('https://www.googleapis.com/auth/cloud-platform');
$service = new Google_Service_CloudResourceManager($client);
$optParams = [];
do {
$response = $service->projects->listProjects($optParams);
foreach ($response['projects'] as $project) {
// TODO: Change code below to process each `project` resource:
echo '<pre>', var_export($project, true), '</pre>', "\n";
}
$optParams['pageToken'] = $response->getNextPageToken();
} while ($optParams['pageToken']);
?>

Related

Adding sites to Google Search Console via API

I have a site that has hundred of sub-domains. I need to add these sub-domains to google search console via api and using cron job with php language script.
Can you please take a look at my code bellow and let me know what is wrong with it. There is no error message but it does not add the sub-domain to the right account. Thank you!
<?php
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}
require_once __DIR__ . '/vendor/autoload.php';
$DEVELOPER_KEY = 'My_key';
$client = new Google_Client();
$client->setApplicationName("MyProjectName");
$client->setDeveloperKey($DEVELOPER_KEY);
$client->setAuthConfig('file.json');
$scopes = array('https://www.googleapis.com/auth/webmasters');
$client->setScopes($scopes);
$url = "http://sub.example.com";
$webmasters = new Google_Service_Webmasters($client);
$webmasters->sites->add($url); // my problem is here
print_r( $webmasters->sites->listSites()); //works fine, gets back sub-domain
?>

Google drive api scope

This is my code
<?php
require_once '/home/bachus03/domains/bachus03.vot.pl/public_html/fb/vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=/home/bachus03/domains/bachus03.vot.pl/public_html/fb/public/service-account.json');
$client = new Google_Client();
$client->setScopes(['https://www.googleapis.com/auth/drive.metadata']);
$client->useApplicationDefaultCredentials();
$files = new Google_Service_Drive_DriveFile($client);
$response = $files->getOwners();
echo json_encode($response) . "\n";
?>
And after I run my test.php script I get:
[bachus03#s14:: ~ ]:$ /usr/local/php/p56/bin/php /home/bachus03/domains/bachus03.vot.pl/public_html/fb/public/test.php
NUll
What I am doing wrong?

Google Cloud API - Application Default Credentials

I have the following code, modified from Google's documentation:
$GOOGLE_APPLICATION_CREDENTIALS = "./[path].json";
$_ENV["GOOGLE_APPLICATION_CREDENTIALS"] = "./[path].json";
$_SERVER["GOOGLE_APPLICATION_CREDENTIALS"] = "./[path].json";
$projectId = "[my project's ID']";
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes(['https://www.googleapis.com/auth/books']);
$service = new Google_Service_Books($client);
$results = $service->volumes->listVolumes('Henry David Thoreau');
Yet when I run it it returns the error:
PHP Fatal error: Uncaught exception 'DomainException' with message 'Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentials for more information'
I have tried various configurations, for example changing the path of the file. As you see, I've also done the three different forms of variables that I could immediately think of (two environment, one not).
I'm not quite sure where to look next. Should I look into different ways of setting the environment variable or should I define the path in a different way? What are the correct ways of doing this? Is there any other reason for the error?
You need to use putenv() (http://php.net/manual/en/function.putenv.php) instead of trying to use any of the methods you have used ($_ENV or $_SERVER).
Taken from https://github.com/google/google-api-php-client/blob/master/UPGRADING.md#google_auth_assertioncredentials-has-been-removed
// OR use environment variables (recommended)
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
$client->useApplicationDefaultCredentials();
I agree with the above answer, but only want to describe if user getting error in php using nlp google:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';
# Imports the Google Cloud client library
use Google\Cloud\Language\LanguageClient;
putenv('GOOGLE_APPLICATION_CREDENTIALS=/home/sgupta/www/practise/nlp/google/cred.json'); //your path to file of cred
//$client->useApplicationDefaultCredentials();
# Your Google Cloud Platform project ID
$projectId = 'nlp-project-nname'; //your project name
# Instantiates a client
$language = new LanguageClient([
'projectId' => $projectId
]);
# The text to analyze
$text = 'Sachin Tendulkar';
# Detects the sentiment of the text
$annotation = $language->analyzeSentiment($text);
$sentiment = $annotation->sentiment();
echo "<pre>";
print_r($annotation); die;
echo 'Text: ' . $text . '
Sentiment: ' . $sentiment['score'] . ', ' . $sentiment['magnitude'];
?>
Use this one it's working for me
# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=../service-account.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$client->refreshTokenWithAssertion();
$token = $client->getAccessToken();
$accessToken = $token['access_token'];
Alternatively you can define a path to your json file like this
$client = new Google_Client();
$client->setAuthConfig('/path/to/credentials.json');
Attempt to use the ImageAnnotator like below
When running the code, observe that you get an error:
Could not construct ApplicationDefaultCredentials
solution
putenv("GOOGLE_APPLICATION_CREDENTIALS=/home/netwons/Downloads/AIz.json");
but not work.
OS: Ubuntu
PHP version: 7.2.4
Package name and version: google/cloud-vision 0.19.1
this is code
$imageAnnotator = new ImageAnnotatorClient();
// $client->setAuthConfig('key.json');
# the name of the image file to annotate
$fileName = '2.png';
# prepare the image to be annotated
$image = file_get_contents($fileName);
# performs label detection on the image file
$response = $imageAnnotator->labelDetection($image);
$labels = $response->getLabelAnnotations();
if ($labels) {
echo("Labels:" . PHP_EOL);
foreach ($labels as $label) {
echo($label->getDescription() . PHP_EOL);
}
} else {
echo('No label found' . PHP_EOL);
}
You can pass the following array to your client
[
'credentials' => json_decode(file_get_contents('path_to_your_file_.json')), true)
]
In my case its text to speech client, so it can be following
$textToSpeechClient = new TextToSpeechClient([
'credentials' => json_decode(file_get_contents('path_to_your_file.json')), true)
]);

PHP Google Cloud Storage

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.

(401) Login Required Error for retrieve a users from Google apps domain?

how to retrieve a all users from a Google apps doamin . I have tried with the following coed but google return error like "Error calling GET https://www.googleapis.com/admin/directory/v1/users?domain=domainname.com: (401) Login Required "
set_include_path(get_include_path() . PATH_SEPARATOR . 'E:\wamp\www\Google APIs\google-api-php-client\src');
ini_set("memory_limit", -1);
require_once 'google-api-php-client/src/Google/Client.php';
require_once 'google-api-php-client/src/Google/Service/Drive.php';
require_once 'google-api-php-client/src/Google/Service/Oauth2.php';
require_once 'google-api-php-client/src/Google/Service/Directory.php';
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
$client->setClientId('42X74XXXXXercontent.com');
$client->setClientSecret('OxzVALdXwd');
$client->setRedirectUri('http://localhost/Google%20APIs/index.php');
$client->setAccessType("offline");
$client->setApprovalPrompt("force");
$client->setDeveloperKey("AIXXXXXJDUdX48");
$SCOPES = array(
'https://www.googleapis.com/auth/admin.directory.user',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile');
$client->setScopes($SCOPES);
$token = '{"access_token":"ya29.1.AAXXXaeTg","token_type":"Bearer","expires_in":3600,"id_token":"eyJhbXXXXXXX9cEjDMUMe6PVrgo","refresh_token":"1\/sN-XXXXX5qdIGMeEW95tJv-0a1ujWk","created":1397878356}';
$decoded = json_decode($token);
$client->setAccessToken($token);
if ($client->isAccessTokenExpired()) {
$client->refreshToken($decoded->refresh_token);
}
$adminsdk = new Google_Service_Directory($client);
$users_list = $adminsdk->users->listUsers(array('domain'='domainon.info'));
Note : I have Perform a authorization with
$SCOPES = array(
'https://www.googleapis.com/auth/admin.directory.user',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile');
Please help me
You say you're performing the authorization for those scopes, but those scopes aren't included in the client. Make sure you include this code before you run $client->refreshToken():
$client->setScopes($SCOPES);

Categories