Google Cloud API - Application Default Credentials

Laef picture Laef · Feb 15, 2016 · Viewed 18.5k times · Source

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?

Answer

jkns.co picture jkns.co · Feb 16, 2016

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