Skip to content

Commit

Permalink
Add public method to refresh tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
KFoobar committed Dec 1, 2023
1 parent 63c088d commit 81d3423
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/Commands/RefreshTokensCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class RefreshTokensCommand extends Command
public function handle(Client $client)
{
try {
$client->get('settings/company');
$client->refresh();
} catch (\Exception $e) {
$this->components->error('Failed to refresh tokens!');
$this->components->error('Message: ' . $e->getMessage());
Expand Down
17 changes: 15 additions & 2 deletions src/Services/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use KFoobar\Fortnox\Exceptions\FortnoxException;
use KFoobar\Fortnox\Interfaces\ClientInterface;

Expand Down Expand Up @@ -100,6 +101,16 @@ public function delete(string $endpoint, array $data = []): mixed
return $response;
}

/**
* Refresh the access token.
*
* @return mixed
*/
public function refresh(): mixed
{
return $this->refreshAccessToken();
}

/**
* Catch given error message from Fortnox.
*
Expand Down Expand Up @@ -156,12 +167,13 @@ protected function getClientSecret(): ?string

/**
* Gets the access token.
* Cache is set to 55 minutes (3300).
*
* @return null|string
*/
protected function getAccessToken(): ?string
{
return Cache::remember('fortnox-access-token', 3500, function () {
return Cache::remember('fortnox-access-token', 3300, function () {
return $this->refreshAccessToken();
});
}
Expand Down Expand Up @@ -198,6 +210,7 @@ protected function getTimeout(): ?string

/**
* Refreshes the access and refresh token.
* Cache is set to 25 day (2160000).
*
* @throws \KFoobar\Fortnox\Exceptions\FortnoxException
*
Expand Down Expand Up @@ -225,7 +238,7 @@ protected function refreshAccessToken(): string
throw new FortnoxException('Failed to retrieve refresh token from response.');
}

Cache::put('fortnox-refresh-token', $response->json('refresh_token'), 2160000); // 25 days
Cache::put('fortnox-refresh-token', $response->json('refresh_token'), 2160000);

return $response->json('access_token');
}
Expand Down

0 comments on commit 81d3423

Please sign in to comment.