Google Cloud API - Application Default Credentials - php

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

Related

Google Cloud Storage Signed URL V4 too slow

im using php google SDK (PHP 7.2.27), The process to create signed url v4 takes >1500 ms. what i want to ask is it this normal? or something wrong with my setup? can it be optimized? the real code have caching mechanism so its solved the problem when the url already created, it will be problem if happen for the first time. here's the part of code to create signed url v4 :
<?php
require __DIR__ . '/vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;
$bucketName = <REDACTED>
$objectName = <REDACTED>
$process_time = microtime(true);
$storage = new StorageClient();
$bucket = $storage->bucket($bucketName);
$object = $bucket->object($objectName);
$url = $object->signedUrl(
# This URL is valid for 15 minutes
new \DateTime('30 sec'),
[
'version' => 'v4',
'keyFilePath' => dirname(__FILE__)."/<REDACTED>.json"
]
);
$process_time = microtime(true) - $process_time;
echo "Process Time : ".$process_time."\n";
print('Generated GET signed URL:' . PHP_EOL);
print($url . PHP_EOL);
Update:
the cause is at "$storage = new StorageClient();"
using php 8.1 and its still takes >1500ms
this is snoop file of that "new StorageClient()" do :
Change
$storage = new StorageClient();
to
$storage = new StorageClient([
'projectId' => '<your_related_project_id_to_object_bucket_location>'
]);
the first one (without parameter) is an example from official document that slows down the connection about 1500ms, as someone totally new in GCP this documentation bring more confusion than clear explanation, dont use it.

How can I use dropbox core API in php

I am trying to use Dropbox core API in php (https://www.dropbox.com/developers-v1/core/start/php) but I am stuck while running following code solution given on stack overflow
<?php
require_once "dropbox-php-sdk-1.1.6/lib/Dropbox/autoload.php";
use \Dropbox as dbx;
$dropbox_config = array(
'key' => 'your_key',
'secret' => 'your_secret'
);
$appInfo = dbx\AppInfo::loadFromJson($dropbox_config);
$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
$authorizeUrl = $webAuth->start();
echo "1. Go to: " . $authorizeUrl . "<br>";
echo "2. Click \"Allow\" (you might have to log in first).<br>";
echo "3. Copy the authorization code and insert it into $authCode.<br>";
$authCode = trim('DjsR-iGv4PAAAAAAAAAAAbn9snrWyk9Sqrr2vsdAOm0');
list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
echo "Access Token: " . $accessToken . "<br>";
$dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0");
// Uploading the file
$f = fopen("working-draft.txt", "rb");
$result = $dbxClient->uploadFile("/working-draft.txt", dbx\WriteMode::add(), $f);
fclose($f);
print_r($result);
// Get file info
$file = $dbxClient->getMetadata('/working-draft.txt');
// sending the direct link:
$dropboxPath = $file['path'];
$pathError = dbx\Path::findError($dropboxPath);
if ($pathError !== null) {
fwrite(STDERR, "Invalid <dropbox-path>: $pathError\n");
die;
}
// The $link is an array!
$link = $dbxClient->createTemporaryDirectLink($dropboxPath);
// adding ?dl=1 to the link will force the file to be downloaded by the client.
$dw_link = $link[0]."?dl=1";
echo "Download link: ".$dw_link."<br>";
?>
When I Run this code I got this error
I am commenting some code from dropbox core API which is in
dropbox-php-sdk-1.1.6/lib/Dropbox/RequestUtil.php to run dropbox core API in 5.6 php version
if (strlen((string) PHP_INT_MAX) < 19) {
// Looks like we're running on a 32-bit build of PHP. This could cause problems because some of the numbers
// we use (file sizes, quota, etc) can be larger than 32-bit ints can handle.
throw new \Exception("The Dropbox SDK uses 64-bit integers, but it looks like we're running on a version of PHP that doesn't support 64-bit integers (PHP_INT_MAX=" . ((string) PHP_INT_MAX) . "). Library: \"" . __FILE__ . "\"");
}
Dropbox v1 API has been shutdown on September 28, 2017. The library you are trying to use is made for this retired v1.
You should use one of the v2 PHP libraries instead:
dropbox-php-sdk by Kunal Varma
dropbox-v2-php by Alorel
FYI, API v1 is being retired, so it will return a 400 error with this message: {“error”: “v1_retired”}. This means your work/code relying on API v1 endpoints may stop working.
I think you have not migrated to v2, check out the migration guide for more details.
https://www.dropbox.com/developers/reference/migration-guide

GCP BigQuery PHP client get list of projects

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

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
?>

Rackspace cloudfiles PHP API creating container but not objects . Different errors everytime?

This is the simple code I`m using to upload an image in my rackspace account with PHP :
<?php
$api_username = 'lolcat';
$api_key = 'sexyapi';
require 'cloudfiles.php';
$auth = new CF_Authentication($api_username, $api_key);
$auth->authenticate();
$connection = new CF_Connection($auth);
$images = $connection->create_container("pitch");
$url = $images->make_public();
echo 'The url is '.$url;
$file = 'sherlock.jpg';
$img = $images->create_object($file);
$img->load_from_filename($file)
?>
Also everytime it gives diffrent errors. Like:
"Strict standards: Only variables should be passed by reference in C:\wamp\www\cloudfiles.php on line 1969 "
" Fatal error: Maximum execution time of 30 seconds exceeded in C:\wamp\www\cloudfiles_http.php on line 1249"
A sample of errors (imgur image)
Please help I`ve been trying this simple thing for 2 hours now.
Php-cloudfiles bindings are deprecated. I suggest you to give php-opencloud a try. I shouldn't be hard to port your code. Here's a quick example:
<?php
require 'vendor/autoload.php';
use OpenCloud\Rackspace;
$client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array(
'username' => 'foo',
'apiKey' => 'bar'
));
$service = $client->objectStoreService('cloudFiles', 'DFW');
$container = $service->createContainer('pitch');
$container->enableCdn();
$cdn = $container->getCdn();
//Print "Container SSL URL: " . serialize($cdn);
$files = array(
array(
'name' => 'file_1.txt',
'body' => fopen('files/file_1.txt', 'r+')
)
);
$container->uploadObjects($files);
You can find php-opencloud docs at: https://github.com/rackspace/php-opencloud/blob/master/docs/getting-started.md

Categories