Answer the question
In order to leave comments, you need to log in
Goole api Oauth 2.0 authorization ,server-side, refresh token issue, why token not working after refresh?
public function getClient()
{
$client = new Google_Client();
$client->setApplicationName($this->application_name);
$client->setClientId($this->client_id);
$client->setClientSecret($this->client_secred);
$client->setScopes($this->scopes);
$client->setAuthConfig($this->client_secret_path);
$client->setRedirectUri($this->redirect_uri);
$client->setAccessType("offline");
$client->setApprovalPrompt('force');
$client->setIncludeGrantedScopes(true);
if (file_exists($this->client_credential_path))
{
$access_token = json_decode(file_get_contents($this->client_credential_path), true);
} else
{
if (isset($_GET['code']))
{
$authCode = $_GET['code'];
// Exchange authorization code for an access token.
$access_token = $client->authenticate($authCode);
$access_token['refresh_token'] = $client->getRefreshToken();
// Store the credentials to disk.
if (array_key_exists('access_token', $access_token))
{
if (!file_exists(dirname($this->client_credential_path)))
{
mkdir(dirname($this->client_credential_path), 0700, true);
}
file_put_contents($this->client_credential_path, json_encode($access_token));
}
} else
{
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
exit;
}
}
$client->setAccessToken($access_token);
if ($client->isAccessTokenExpired())
{
$refresh_token = isset($access_token['refresh_token']) ? $access_token['refresh_token'] : NULL;
$client->refreshToken($refresh_token);
$new_access_token = $client->getAccessToken();
$new_access_token['refresh_token'] = $refresh_token;
file_put_contents($this->client_credential_path, json_encode($new_access_token));
$client->setAccessToken($new_access_token);
}
return $client;
}
if ($client->isAccessTokenExpired())
{
$refresh_token = isset($access_token['refresh_token']) ? $access_token['refresh_token'] : NULL;
$client->refreshToken($refresh_token);
$new_access_token = $client->getAccessToken();
$new_access_token['refresh_token'] = $refresh_token;
file_put_contents($this->client_credential_path, json_encode($new_access_token));
$client->setAccessToken($new_access_token);
}
Google_Service_Exception [ 401 ]: { "error": { "code": 401, "message": "Request had invalid authentication credentials.", "errors": [ { "message": "Request had invalid authentication credentials.", "domain": "global", "reason": "unauthorized" } ], "status": "UNAUTHENTICATED" } }
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question