18

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?

Laef
  • 1,086
  • 2
  • 11
  • 27
  • Where are you running the code from (eg. App Engine prod or dev, Compute Engine, locally)? – Adam Feb 15 '16 at 23:59
  • 1
    @Adam Locally, on a Windows / Apache system. However, I'm building for something that will run on a Linux / NGINX system. – Laef Feb 16 '16 at 00:01

6 Answers6

51

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();
jkns.co
  • 738
  • 6
  • 15
  • 2
    Please read “[How do I write a good answer](http://stackoverflow.com/help/how-to-answer)” – fusion3k Feb 16 '16 at 12:51
  • 4
    @fusion3k I can't see any issue with my answer. Okay, it's short, but they've asked "should I define the path in a different way?" and my answer shows how to define the path in a different way, thus answering the question. I believe my answer is self explanatory & does not require any further explanation. "Brevity is acceptable". I'm happy to hear how you think I could improve the answer though? – jkns.co Feb 16 '16 at 16:17
  • First of all: your answer has been reported by several users as ‘unclear’, so more that one think that it is not ‘self explanatory’. I can agree with you: for me - and maybe for the OP - the answer is self-explanatory, but this site is not chat-like, questions and answers exists also for future visitors. A better answer could be like “Your try to set environment variable is not valid, you have to use this syntax instead of... $_ENV means that... see the docs for more details... etc”. There are many way, but the “audience” wants more that one line of code. – fusion3k Feb 16 '16 at 17:57
  • @fusion3k Okay, all fair points & I've updated my answer. The link you first posted doesn't say any of that though, so if you've going to down vote people & request correct answers are deleted, maybe you could explain why first. – jkns.co Feb 16 '16 at 20:36
  • 3
    Thanks got the hint from this. But for laravel project I ended up adding GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json to the .env file. Just giving it here so may other can get help..... – Ashiq Oct 02 '20 at 04:02
5

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'];
?>
Jannie Theunissen
  • 28,256
  • 21
  • 100
  • 127
sunil
  • 832
  • 15
  • 25
2

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'];
executable
  • 3,365
  • 6
  • 24
  • 52
  • 2
    Can you explain that further? Which parts are neccessary and why? – Nico Haase Jan 22 '19 at 09:48
  • I used this way but $client->getAccessToken(); return an invalid token (it looks like 'abcxyz....' - the last characters is all 'dot dot dot'). Do you know why. – VitDuck Aug 25 '21 at 10:22
2

Alternatively you can define a path to your json file like this

$client = new Google_Client();
$client->setAuthConfig('/path/to/credentials.json');
Christian
  • 1,241
  • 2
  • 8
  • 11
2

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)
    ]);
user1994
  • 477
  • 6
  • 12
1

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);
        }
Netwons
  • 1,170
  • 11
  • 14