Getting Precondition check failed - when using gmail api with a service account
Asked Answered
F

2

6

I'm trying to fetch the gmail inbox directly from backend by a cronjob, with no browser or oauth thing.

here is the error i get

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

and here is my code

        $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.
        }

in config/services.php i got this added

'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'),
    ],

I found the client_id easily, but the client_secret i didnt find one in service accounts or api key, just a one into the oauth2 client_id, so i just copied & paste, which i feel is wrong because iam not using oauth to validate the process, but i got nothing else to put there

any ideas to how to solve this, or even a proper documentation for the process ?

Fighter answered 16/10, 2023 at 7:42 Comment(0)
B
5

Precondition check failed.

Means that you are trying to uses a service account with gmail without configuring domain wide delegation from your google workspace account to the service account or have done that and forgot to include the user on the domain to delegate as see 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
Bhayani answered 16/10, 2023 at 9:11 Comment(6)
Is it possible to send subject as multiple users or all the users here. is it only possible for one user at a timeSchmaltzy
A service account can only impersonate one user at a time.Bhayani
Ok, Is it poosible to updateVacation for a set of users as google workspace admin using google APIs ? I clearly can't do this for bunch of users as I have set subject to user's email everytime. Any idea how this can be done ?Schmaltzy
doesnt hurt to set it for each users that can just be done as part of your loop over your users. Unless you have an admin that has access to everyones then you could maybe have them run the updateBhayani
I get "Precondition check failed" on my own account accessing my own mail. It seems pretty random.Longhand
Precondition check failed means you are trying to use a service account with a standard Gmail user. You cant you need to use a google workspace domain user.Bhayani
C
1

if you already have configured domain-wide delegation to the service account, it might take some time to be able to impersonate all users in the workspace.As mentioned in the documentation:

Note: It usually takes a few minutes for impersonation access to be granted after the client ID was added, but in some cases, it might take up to 24 hours to propagate to all users of your Google Account.

consult the Documentation for more info on how to configure domain-wide delegation to the service account.

Confidence answered 21/3, 2024 at 21:55 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.