Google Cloud API - Application Default Credentials

我有以下代码,从Google的文档修改而来:

        $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');

然而,当我运行它时,它返回错误:

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'

我尝试了各种配置,例如更改文件的路径。正如你所看到的,我还完成了我可以立即想到的三种不同形式的变量(两个环境,一个没有)。

我不太确定下一步该去哪里看。我应该研究设置环境变量的不同方法,还是应该以不同的方式定义路径?正确的方法是什么?有没有其他错误原因?


答案 1

您需要使用 (http://php.net/manual/en/function.putenv.php) 而不是尝试使用您使用过的任何方法( 或 )。putenv()$_ENV$_SERVER

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

答案 2

我同意上面的答案,但只想描述用户是否使用nlp google在php中遇到错误:

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

推荐