0

When I first enter my index.php from my web browser I get redirected to Google to aprove that my applications right to access my account. Then I want the application to save the refresh token and never ask me again. But when I try to access index.php trhou another browser it ask me the same thing again. I want to access index.php as a cronjob so it must not ask for an google account each time.

Here is my code:

$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);

if (isset($_REQUEST['logout'])) {
    write_token("");
}

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

if (strlen(read_token()) > 1) {
    $client->setAccessToken(read_token());
    if ($client->isAccessTokenExpired()) {
        write_token("");
    }
} elseif(!isset($_GET['code'])) { // The IF NOT CODE prevent loop when refreshing token
    $authUrl = $client->createAuthUrl();
    header('Location: ' . $authUrl); // Update token if expired
}

Thanks!

/ Erik

1 Answers1

0

The prompt can be skipped for users that have already authorized the application before using the following code. See this answer for more information.

To make this work in a cron job, when there is no user signed into the browser, you'll need to request offline access and use a refresh token. See this answer for more information.

Community
  • 1
  • 1
Eric Koleda
  • 12,420
  • 1
  • 33
  • 51