【发布时间】:2021-09-17 14:15:09
【问题描述】:
在开发 Recaptcha Enterprise 以使用 V2“我不是机器人”复选框时,我遇到了这个错误:
致命错误:未捕获的 DomainException:无法加载默认凭据。浏览https://developers.google.com/accounts/docs/application-default-credentials了解更多信息
我点击链接并决定对此进行身份验证:
use Google\Cloud\Storage\StorageClient;
$storage = new StorageClient([
'keyFile' => json_decode(file_get_contents($path_to_keyfile), true),
'projectId' => 'MY_PROJECT'
]);
我找不到任何其他建议我需要做的事情更多,构造函数 API 的this link 并不建议我可以将它作为参数传递然后继续。我不想为这个项目使用环境变量,我想在代码中手动连接。我错过了什么?我可以确认我有一个有效的服务帐户。
如果有帮助,我想在我进行身份验证后尝试运行的代码是这样的:
// ==================== CAPTCHA ===================
use Google\Cloud\RecaptchaEnterprise\V1\RecaptchaEnterpriseServiceClient;
use Google\Cloud\RecaptchaEnterprise\V1\Event;
use Google\Cloud\RecaptchaEnterprise\V1\Assessment;
use Google\Cloud\RecaptchaEnterprise\V1\TokenProperties\InvalidReason;
$captcha_response = $_POST['g-recaptcha-response'];
$site_key = "123456789abc";
$client = new RecaptchaEnterpriseServiceClient();
define('SITE_KEY', $site_key);
define('TOKEN', $captcha_response);
define('PROTECTED_ACTION', 'signup');
define('PARENT_PROJECT', 'projects/MY_PROJECT');
$event = (new Event())
->setSiteKey(SITE_KEY)
->setExpectedAction(PROTECTED_ACTION)
->setToken(TOKEN);
$assessment = (new Assessment())
->setEvent($event);
try {
$response = $client->createAssessment(
PARENT_PROJECT,
$assessment
);
if ($response->getTokenProperties()->getValid() == false) {
printf('The CreateAssessment() call failed because the token was invalid for the following reason: ');
printf(InvalidReason::name($response->getTokenProperties()->getInvalidReason()));
} else {
if ($response->getEvent()->getExpectedAction() == PROTECTED_ACTION) {
printf('The score for the protection action is:');
printf($response->getRiskAnalysis()->getScore());
}
else
{
printf('The action attribute in your reCAPTCHA tag does not match the action you are expecting to score');
}
}
} catch (exception $e) {
printf('CreateAssessment() call failed with the following error: ');
printf($e);
}
【问题讨论】:
-
代码的哪一部分产生了错误?您显示使用服务帐户初始化 Cloud Storage,但未显示在代码中使用存储客户端。在您的问题中,Google Cloud Storage 和 ReCaptcha 之间是什么关系?
-
哇,这解释了很多。我认为由于某种原因实际上需要 CloudStorage,因为他们在这里给出了示例:cloud.google.com/docs/authentication/production 但是,我仍然不确定如何将我的服务帐户传递给 Recaptcha?例如,Storage 的 API 页面在构造函数中有
keyFile,但 Recaptcha 的构造函数没有。
标签: php google-cloud-platform recaptcha