0
votes

I am trying to access google webmaster api using service account. But i am unable to PHP Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }''

I tried following solutions as mentioned in other posts, 1. installed ntp 2. date_default_timezone_set(“Asia/Kolkata”); 3. sudo ntpdate pool.ntp.org

But none worked. Please someone help. I am stucked.

require_once realpath(dirname(__FILE__) . '/google-api-php-client-master/src/Google/autoload.php');

session_start();

$client_email = '[email protected]'; 
$private_key = file_get_contents('Config/myproject.p12');
$scopes = array('https://www.googleapis.com/auth/webmasters');

$credentials = new Google_Auth_AssertionCredentials(
    $client_email,
    $scopes,
    $private_key
);

$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion();
}

$service = new Google_Service_Webmasters($client);
$list = $service->sitemaps->listSitemaps("www.example.com");
print_r($list);
1

1 Answers

0
votes

After struggling a bit, resolved problem on my own. It was small silly mistake in following link of code where i mentioned relative path :

$private_key = file_get_contents('Config/myproject.p12');

It worked when i replaced it with absolute path, i.e. :

$private_key = file_get_contents(dirname(__FILE__) . '/Config/myproject.p12');