I'm trying to get emails from Gmail but I'm not able to refresh token. I also followed this question but I don't know why it doesn't work
How to refresh token with Google API client?
This is how I do it:
$email="xxxx@gmail.com"; //It can't be "me";
$client = new Google_Client();
$client->setAuthConfigFile(CLIENT_SECRET_PATH);
$client->addScope(Google_Service_Gmail::MAIL_GOOGLE_COM);
$client->setRedirectUri($this->redirect_url);
$client->setState('offline');
$client->setAccessType('offline');
$client->setLoginHint($email);
$client->setAccessToken($gmail['access_token']);
if($client->isAccessTokenExpired())
{
$access_token= json_decode($gmail['access_token'],true);
$refresh=$client->refreshToken($access_token["refresh_token"]);
$new_token_array_str=$client->getAccessToken();
/*
Old Token ($access_token):
------------------
array (size=5)
'access_token' => string 'ya29.xQE0___' (length=73)
'token_type' => string 'Bearer' (length=6)
'expires_in' => int 3600
'refresh_token' => string '1/M57-GPcccc' (length=66)
'created' => int 1438679813
New token:
----------
array (size=3)
'access_token' => string 'ya29.xQEllll-jjj-jjj' (length=73)
'expires_in' => int 3600
'created' => int 1438689530
*/
}
$j=0;
do
{
try
{
$messagesResponse = $service->users_messages->listUsersMessages($email, $opt_param);
if ($messagesResponse->getMessages())
{
$messages = array_merge($messages, $messagesResponse->getMessages());
$pageToken = $messagesResponse->getNextPageToken();
}
$j++;
}
catch (Exception $e)
{
print 'An error occurred: ' . $e->getMessage();
}
}while ($pageToken);
And this is what I get:
An error occurred: Error calling GET https://www.googleapis.com/gmail/v1/users/xxxx%40gmail.com%20/messages?q=in%3Ainbox: (403) Delegation denied for xxxx@gmail.com
The first time, I get the emails. My problem is when token access token has expired, I don't know why it doesn't work.