获取先决条件检查失败 - 将 gmail api 与服务帐户一起使用时

问题描述 投票:0回答:2

我正在尝试通过 cronjob 直接从后端获取 gmail 收件箱,没有浏览器或 oauth 的东西。

这是我得到的错误

Google\Service\Exception: {
  "error": {
    "code": 400,
    "message": "Precondition check failed.",
    "errors": [
      {
        "message": "Precondition check failed.",
        "domain": "global",
        "reason": "failedPrecondition"
      }
    ],
    "status": "FAILED_PRECONDITION"
  }
}

这是我的代码

        $client = new Google_Client();
        $client->setAuthConfig(base_path('config/keys/ticketing-system-401805-20cdedb73268.json'));

        $gmailConfig = config('services.gmail');

        $client->setClientId($gmailConfig['client_id']);
        $client->setClientSecret($gmailConfig['client_secret']);
        $client->setScopes($gmailConfig['scopes']);
        
        // Create a Gmail service using the service account client
        $service = new Google_Service_Gmail($client);

        // List the user's Gmail messages
        $messages = $service->users_messages->listUsersMessages('me', []);

        foreach ($messages->getMessages() as $message)
        {
            // Retrieve and process each email
            $email = $service->users_messages->get('me', $message->getId());
            // You can access the email content with $email->getBody() and other properties.
        }

在config/services.php中 我添加了这个

'gmail' => [
        'client_id' => 'CLIENT_ID',
        'client_secret' => 'CLIENT_SECRET',
        'project_id' => 'ticketing-system-401805',
        // ...
        'scopes' => [
            'https://www.googleapis.com/auth/gmail.readonly',
            // Add other required scopes as needed
        ],
        'key_file' => base_path('config/keys/ticketing-system-401805-20cdedb73268.json'),
    ],

我很容易找到client_id,但是client_secret我在服务帐户或api密钥中没有找到,只是在oauth2 client_id中找到了一个,所以我只是复制并粘贴,我觉得这是错误的,因为我没有使用oauth来验证过程,但我没有其他东西可以放在那里

关于如何解决这个问题的任何想法,甚至是该过程的适当文档?

php google-api gmail-api google-api-php-client service-accounts
2个回答
2
投票

前提条件检查失败。

意味着您正在尝试通过 gmail 使用服务帐户,而没有配置从您的 Google Workspace 帐户到服务帐户的域范围委派,或者已完成此操作但忘记将用户包含在要委派的域中,请参见

setSubject

const CREDENTIALS = 'C:\Development\FreeLance\GoogleSamples\Credentials\workspaceserviceaccount.json';
const SCOPES = [Google_Service_Drive::GMAIL];   // scope must be configured in workspace.

printf("Service Account Access to google gmail api, with google workspace.\n");

// Create service account client, with drive scopes.
$client = new Google\Client();
$client->setAuthConfig(CREDENTIALS);
$client->setScopes(SCOPES);
$client->setSubject("[email protected]");   // remember to add user

0
投票

如果您已经配置了对服务帐户的域范围委派,则可能需要一些时间才能模拟工作区中的所有用户。如文档中所述:

注意:添加客户端 ID 后,通常需要几分钟时间才能授予模拟访问权限,但在某些情况下,可能需要长达 24 小时才能传播到您 Google 帐户的所有用户。

请参阅文档,了解有关如何配置服务帐户的域范围委派的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.