使用服务帐户对 Google API 进行身份验证时出现 failedPrecondition 错误

failedPrecondition error when authenticating with service account to Google API

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

我有一个项目设置,一个下载的 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);

?>

完整的错误如下所示:

Fatal error: Uncaught exception 'Google_Service_Exception' with message '{ "error": { "errors": [ { "domain": "global", "reason": "failedPrecondition", "message": "Bad Request" } ], "code": 400, "message": "Bad Request" } } '

我只是 运行 进入这个并最终找到了解决方案。您收到该错误是因为您在使用服务帐户时未指定 "subject" 作为配置的一部分。 API 需要知道您在使用服务帐户时使用的是哪个电子邮件地址。您可以在 Google_Client::createApplicationDefaultCredentials

中看到它试图使用此主题

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

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

请务必在从收件箱中提取邮件时使用关键字 'me',因为您现在充当的是您配置为 'subject' 的电子邮件地址。