diff --git a/laravel-usage.md b/laravel-usage.md index c54b98d..da9e826 100644 --- a/laravel-usage.md +++ b/laravel-usage.md @@ -59,6 +59,14 @@ class TeamleaderServiceProvider extends ServiceProvider implements DeferrablePro config('services.teamleader.state'), ); + $teamleader->setTokenUpdateCallback(function ($teamleader) { + Storage::disk('local')->put('teamleader.json', json_encode([ + 'accessToken' => $teamleader->getAccessToken(), + 'refreshToken' => $teamleader->getRefreshToken(), + 'expiresAt' => $teamleader->getTokenExpiresAt(), + ])); + }); + if (Storage::exists('teamleader.json') && $json = Storage::get('teamleader.json')) { try { $json = json_decode($json); @@ -70,13 +78,17 @@ class TeamleaderServiceProvider extends ServiceProvider implements DeferrablePro } if (! empty($teamleader->getRefreshToken()) && $teamleader->shouldRefreshToken()) { - $teamleader->connect(); + try { + $teamleader->connect(); + } catch (\Throwable $th) { + $teamleader->setRefreshToken(''); - Storage::disk('local')->put('teamleader.json', json_encode([ + Storage::disk('local')->put('teamleader.json', json_encode([ 'accessToken' => $teamleader->getAccessToken(), 'refreshToken' => $teamleader->getRefreshToken(), 'expiresAt' => $teamleader->getTokenExpiresAt(), ])); + } } return $teamleader; diff --git a/src/Teamleader.php b/src/Teamleader.php index 228fc7c..e0da6a1 100644 --- a/src/Teamleader.php +++ b/src/Teamleader.php @@ -33,6 +33,16 @@ class Teamleader */ private $clientSecret; + /** + * @var Client|null + */ + private $client; + + /** + * @var callable(Connection) + */ + private $tokenUpdateCallback; + /** * @var string */ @@ -219,6 +229,11 @@ public function connect(): void } } + public function setTokenUpdateCallback(callable $callback): void + { + $this->tokenUpdateCallback = $callback; + } + public function get(string $endpoint, array $parameters = []) { try { @@ -249,7 +264,7 @@ public function post(string $endpoint, array $body, array $parameters = []) } } - public function ensureRateLimitingIsNotExceeded() : void + public function ensureRateLimitingIsNotExceeded(): void { if ($this->rateLimitRemaining <= 1) { $seconds = Carbon::createFromFormat('Y-m-d\TH:i:sT', $this->rateLimitReset, 'UTC')->diffInSeconds(); @@ -379,6 +394,10 @@ private function acquireAccessToken(): void $this->accessToken = $body['access_token']; $this->refreshToken = $body['refresh_token']; $this->tokenExpiresAt = time() + $body['expires_in']; + + if (is_callable($this->tokenUpdateCallback)) { + call_user_func($this->tokenUpdateCallback, $this); + } } catch (ClientException $e) { $response = json_decode($e->getResponse()->getBody()->getContents()); throw CouldNotAquireAccessTokenException::make($response->errors[0]->status, $response->errors[0]->title);