I am using the Google API Client to read emails from Gmail. Now I want to add a Cronjob so it reads every 5 minutes the mails.
The problem using the Google API Client is that it needs to allow the user to first click on the authorization link and allow the user to use the Google API Client.
I have a class Inbox with a function initialize that initliazes the Google API Client. But the cronjob doesn't work because I have to get an access_token.
public function initialize() {
$configuration = Configuration::getConfiguration('class_Inbox');
// Creates the Google Client
$this->client = new Google_Client();
$this->client->setApplicationName('Tiptsernetwork');
$this->client->setClientId($configuration['clientId']);
$this->client->setClientSecret($configuration['clientSecret']);
$this->client->setRedirectUri('http://www.tipsternetwork.nl/cronjob/authenticate');
$this->client->addScope('https://mail.google.com/');
$this->client->setApprovalPrompt('force');
$this->client->setAccessType('offline');
// Creates the Google Gmail Service
$this->service = new Google_Service_Gmail($this->client);
// Authenticates the user.
if (isset($_GET['code'])) {
$this->authenticate($_GET['code']);
}
// Check if we have an access token in the session
if (isset($_SESSION['access_token'])) {
$this->client->setAccessToken($_SESSION['access_token']);
} else {
$loginUrl = $this->client->createAuthUrl();
echo '<a href="'.$loginUrl.'">Click Here</a>';
}
// If the token is expired it used the refresh token to generate a new Access Token
if($this->client->isAccessTokenExpired()) {
$this->client->refreshToken($configuration['refreshToken']);
}
}
public function authenticate($code) {
// Creates and sets the Google Authorization Code
$this->client->authenticate($code);
$_SESSION['access_token'] = $this->client->getAccessToken();
$this->client->refreshToken($configuration['refreshToken']);
// Redirect the user back after authorizaton
$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($url, FILTER_VALIDATE_URL));
}
Do you guys know how to fix it using the refresh token or whatever? I can't get it working and I am out of ideas.
If I am accessing the URL and click on "Click Here" and allow it it works succesfully but not with a Cronjob because I can't click on the "Click Here" URL...
I hope you people understand it and can help me :).
Kind regards,
Yanick