我正在尝试通过PHP使用Google Cloud Vision API。我创建了我的第一个测试页,并且从网站运行时,PHP可以正常工作,没有任何问题。我的项目有一个新问题,我想从终端运行相同的PHP代码。
我现在遇到的问题是,我收到一个错误,提示我的脚本未加载凭据。
这是我用来加载可在我的网站版本中使用的凭据文件的代码...
putenv('GOOGLE_APPLICATION_CREDENTIALS=Credential-file.json');
这不适用于我的终端运行版本的代码。所以我尝试了其他一些选择,例如...
putenv('GOOGLE_APPLICATION_CREDENTIALS=/Full/Path/To/Credential-file.json');
和
$_ENV['GOOGLE_APPLICATION_CREDENTIALS'] = "/Full/Path/To/Credential-file.json";
确切的错误是...
PHP Fatal error: Uncaught DomainException: Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentials for more information in /Library/WebServer/Documents/google_vision/vendor/google/auth/src/ApplicationDefaultCredentials.php:156
我的问题是...当尝试从终端运行PHP时,是否有更好的方法来加载凭据文件?还是我在版本中犯了什么错误?
我应该提到的是,我正在MacOS上使用Google Cloud客户端库运行它。
任何帮助/建议将不胜感激。
谢谢!
答案 0 :(得分:0)
错误消息表明变量设置不正确(与将其设置为无效路径相反)。
putenv
仅持续当前脚本的持续时间。在$_ENV
上设置值不会使其对getenv
(Google身份验证库使用的方法)可用。您是否正在执行的同一脚本中设置凭据环境变量?
您也可以在调用中提供值:
GOOGLE_APPLICATION_CREDENTIALS=/path/to/keyfile.json php my-script.php
或在终端会话中设置变量:
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/keyfile.json
php my-script.php
如果您使用的是Google\Cloud\Vision\V1\ImageAnnotatorClient
,则可以直接通过密钥文件进行身份验证:
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
$vision = new ImageAnnotatorClient([
'credentials' => '/path/to/keyfile.json
]);
或使用Google\Cloud\Vision\VisionClient
:
use Google\Cloud\Vision\VisionClient;
$vision = new VisionClient([
'keyFilePath' => '/path/to/keyfile.json'
]);