Search code examples
google-api-php-clientservice-accountsgoogle-indexing-api

Not able to authenticate a service account with Google API PHP Client


I am new to this so I took cue from various official documentations to create a service account etc and use PHP client for Google API to make HTTP requests by using the credentials JSON for that service account.

But I am not sure what's going wrong, it just doesn't work ( for context I am trying to use the Indexing API - https://developers.google.com/search/apis/indexing-api/v3/prereqs#php )

require_once ABSPATH . '/googlelibraries/google-api-php-client/vendor/autoload.php';

$client = new Google_Client();
$serviceKeyFile = __DIR__ . '/daxxxxx-b1xxxxxxc8.json';
$client->setAuthConfig( $serviceKeyFile );
$client->useApplicationDefaultCredentials();

$client->setSubject( '[email protected]' );
$client->addScope('https://www.googleapis.com/auth/indexing');
$client->setAccessType('offline');
// $client->createApplicationDefaultCredentials();
// $client->setClientId( '10xxxxxxxxxxx' );
$endpoint = 'https://indexing.googleapis.com/v3/urlNotifications:publish';

This is what I have, almost the same as the one on the example documentation, however, when I call $client->authorize() to get a Guzzle client authenticated to make request I see nothing, everything just becomes blank, no error, I was able to debug it later and the error goes like -

Fatal error: Uncaught Exception: Magic request methods require a URI and optional options array
in /var/www/html/googlelibraries/google-api-php-client/vendor/guzzlehttp/guzzle/src/Client.php on line 84

I do not care if it authenticates or not, the problem right now is that authorize method itself it throwing an error and I don't know exactly what it is, there's no detailed guide on it that I would find. Any ideas?


Solution

  • Not all google apis support service account authentication. You appear to be trying to use the indexing api. If you check the documentation #OAuth2Authorizing You will find that it only mentions Oauth2 authorization this is because service account authorization is not supported by this api.

    You will need to switch to Oauth2.