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

时间:2016-01-08 13:51:55

标签: php google-api gmail google-api-php-client gmail-api

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

我有一个项目设置,一个JSON格式的下载身份验证文件,我在Google Developers Console中启用了gmail API。

但是当我运行以下代码时,我得到一个"错误请求"错误的原因" 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);

?>

完整的错误如下所示:

  

致命错误:未捕获的异常&#39; Google_Service_Exception&#39;消息&#39; {&#34;错误&#34;:{&#34;错误&#34;:[{&#34;域&#34;:&#34;全球&#34;,&#34;原因&#34 ;:   &#34; failedPrecondition&#34;,&#34; message&#34;:&#34; Bad Request&#34; }],&#34;代码&#34;:400,   &#34;消息&#34;:&#34;错误请求&#34; }&#39;

1 个答案:

答案 0 :(得分:9)

我刚碰到这个,终于找到了解决方案。您收到该错误是因为您使用的是服务帐户而未指定&#34; subject&#34;作为配置的一部分。这需要API知道您在使用服务帐户时所使用的电子邮件地址。您可以在Google_Client :: createApplicationDefaultCredentials

中看到它尝试使用此主题

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

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

请务必使用关键字&#39; me&#39;从收件箱中提取邮件时,您现在充当了已配置为&#39; subject&#39;的电子邮件地址。

相关问题