failedPrecondition在使用服务帐户向Google API进行身份验证时出错


failedPrecondition error when authenticating with service account to Google API

我正在尝试使用Google API 2.0.0 RC4 for PHP从我自己的收件箱(作为项目所有者)获取给定的电子邮件。

我有一个项目设置,下载了JSON格式的身份验证文件,并在Google开发者控制台中启用了gmail API。

但当我运行以下代码时,我会收到一个"Bad Request"错误,原因是"failedPrecondition"。现在,这让我相信访问权限有问题,但我不知道我需要在这里做什么。

代码:

<?php
    require_once("google-api-php-client-2.0.0-RC4/vendor/autoload.php");
    $client = new Google_Client();
    // set the scope(s) that will be used
    $client->setScopes(["https://www.googleapis.com/auth/gmail.readonly"]);
    $client->setApplicationName("MyProject");
    // set the authorization configuration using the 2.0 style
    $client->setAuthConfigFile("myAuthFile.json");
    $gmailHandle = new Google_Service_Gmail($client);
    $messages = $gmailHandle->users_messages->get("myemail@mydomain.com", "12343445asd56");
    echo json_encode($messages);
?>

完整的错误看起来是这样的:

致命错误:未捕获异常"Google_Service_exception",消息为"{"error":{"errors":[{"domain":"global","reason":"failedPrecondition","message":"Bad Request"}],"code":400,"message":"Bad Request"}}'

我刚刚遇到了这个问题,并最终找到了解决方案。您之所以出现此错误,是因为您使用的服务帐户没有在配置中指定"主题"。API需要知道您在使用服务帐户时使用的电子邮件地址。您可以在Google_Client::createApplicationDefaultCredentials 中看到它试图使用此主题

解决方案是在调用setAuthConfig()后在代码中添加以下行

$client->setConfig('subject', 'you@email.com');

从收件箱提取邮件时,请确保使用关键字"我",因为您现在充当的是您配置为"主题"的电子邮件地址。