Google Cloud API - 应用程序默认凭据

lae*_*aef 11 php google-api google-api-php-client google-cloud-platform

我从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');
Run Code Online (Sandbox Code Playgroud)

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

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'
Run Code Online (Sandbox Code Playgroud)

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

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

jkn*_*.co 32

您需要使用putenv()(http://php.net/manual/en/function.putenv.php)而不是尝试使用您使用过的任何方法($_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();
Run Code Online (Sandbox Code Playgroud)

  • @ fusion3k我的答案看不出任何问题.好吧,它很简短,但是他们已经问过"我应该以不同的方式定义路径吗?" 我的答案显示了如何以不同的方式定义路径,从而回答问题.我相信我的答案是自我解释的,不需要任何进一步的解释."简洁是可以接受的".我很高兴听到您认为我可以改进答案的方式吗? (3认同)
  • 谢谢从中得到提示。但对于 laravel 项目,我最终将 GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json 添加到 .env 文件中。只是把它放在这里,这样其他人就可以得到帮助...... (3认同)
  • 请阅读"[我如何写出一个好的答案](http://stackoverflow.com/help/how-to-answer)" (2认同)

sun*_*nil 6

我同意上面的答案,但只想描述用户是否使用 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'];
?>
Run Code Online (Sandbox Code Playgroud)