I'm using Xero OAuth2.0 APIs, I am refreshing token once token is expired. Xero Documentation I'm storing token in JSON file so i can retrive next time.
Erorr Response:
{
"error": "invalid_grant"
}
Please refer below code i've used
public function getAccessToken($code = null) {
if(file_exists($this->tokenPath) && isset($code)) {
$accessToken = $this->getAccessTokenFromAuthCode($code);
} else if (file_exists($this->tokenPath)) {
$accessToken = $this->getAccessTokenFromJSON();
try {
if (time() > $accessToken->expires) {
$accessToken = $this->provider->getAccessToken('refresh_token', [
'refresh_token' => $accessToken->refresh_token
]);
}
} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
//header('Location: ' . $this->getAuthorizationUrl());
}
} else if(isset($code)){
$accessToken = $this->getAccessTokenFromAuthCode($code);
} else {
header('Location: ' . $this->getAuthorizationUrl());
}
return $accessToken;
}
public function getAccessTokenFromAuthCode($code) {
return $this->storeAccessTokenToJSON($this->provider->getAccessToken('authorization_code', ['code' => $code]));
}
public function getAccessTokenFromJSON(){
return json_decode(file_get_contents($this->tokenPath));
}
public function storeAccessTokenToJSON($accessToken){
file_put_contents($this->tokenPath, json_encode($accessToken));
return json_decode(file_get_contents($this->tokenPath));
}