Benjamin de Bos Benjamin de Bos - 1 year ago 204
PHP Question

Google-api-php Refresh Token returns invalid_grant

I've nearly searched every result of the first page of google for this. But can't seem to find the answer. I'm working with a refresh_token by Google's API and receiving:

Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }

What i'm doing. First: i'm creating and storing a persistant connection to the google api:

$client = new Google_Client();

if (isset($_GET['code'])) {
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));

if (isset($_SESSION['token'])) {

if (isset($_REQUEST['logout'])) {

if ($client->getAccessToken()) {

$jsonarray = json_decode($client->getAccessToken());

$myFile = "refreshtoken.conf";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $client->getAccessToken());



$service = new Google_DriveService($client);
$file = new Google_DriveFile();
$file->setTitle('My document.txt');
$file->setDescription('A test document');

$data = file_get_contents('document.txt');

$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',


// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
} else {
$auth = $client->createAuthUrl();
header("Location: $auth");

So basicly everything runs and the token gets stored in a textfile:


When i'm trying to auth using the following code:

$client = new Google_Client();

I'm getting the following error:
Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }

Answer Source

Before Authenticate, there must be something like:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download