Question

I have the following problem with authentication to Google API:

PHP Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'' in /home/bot/bot/vendor/google/apiclient/src/Google/Auth/OAuth2.php:328

However, the issue is very strange, because same code works on my local PC and stops working on the server. Is it possible, that it has something to do with server time? I have my system clock synchronized, but server is about ~1 minute backwards. Seriously, I ran out of ideas why it doesn't work anymore though I haven't changed the code at all. It used to work before, but all of the sudden this problem appeared.

What can I do with that?

<?php
$client = new Google_Client();
$client->setApplicationName('My App');
$client->setClientId($clientId);
$client->setClassConfig(
    'Google_Cache_File',
    ['directory' => __DIR__.'/res/tmp']
);

$service = new Google_Service_Calendar($client);

$cred = new Google_Auth_AssertionCredentials(
    $serviceAccountName,
    // https://www.googleapis.com/auth/calendar
    [Google_Service_Calendar::CALENDAR],
    $keyFile
);
$client->setAssertionCredentials($cred);

var_dump($service->calendarList->listCalendarList());
Was it helpful?

Solution

The solution was synchronizing the server time. Server time was only 40 seconds different to atomic clock, but after sending ticket to my hosting provider I managed to get it working. Problem has gone. However, if someone could explain why does OAuth is such rigourous on the precise date and time, I would be grateful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top