Search code examples
phpgoogle-api-php-clientgoogle-directory-api

{ "error" : "invalid_grant" } error with Google Directory API PHP Client SDK


So I am trying all day already and I just can't seem to correctly authenticate to the google API. This is what I did to set up a connection so far:

  1. I first created a service account for my application
  2. Then I added that service account in the third party client access settings on the admin page for our Google Apps domain. I added the scopes for users and groups
  3. I generated a new Client ID for web applications
  4. I downloaded the .p12 file, the secret JSON file for my web Client ID and stored them locally

So I think that's all I need to succesfully authenticate.. I then used the following code to set everything up:

$this->client = new Google_Client();
$this->client->setAuthConfigFile(STORAGE_PATH.'client_secrets.json');
$this->client->addScope(static::$scopes);

$cred = new Google_Auth_AssertionCredentials(
    static::$service_account_email,
    static::$scopes,
    file_get_contents(STORAGE_PATH.'TRICS-key.p12'));
$cred->sub = static::$delegated_admin;

$this->client->setAssertionCredentials($cred);

$this->directory_service = new Google_Service_Directory($this->client);

Does someone know if I am forgetting something?


Solution

  • Oops. I was a fool. I accidentally used the email of the Web Client instead of the service account email. :') The rest of the code seems to function as it should.