diff --git a/src/AccessTokenHandler.php b/src/AccessTokenHandler.php index 4ca8037..b5f5353 100644 --- a/src/AccessTokenHandler.php +++ b/src/AccessTokenHandler.php @@ -8,6 +8,7 @@ class AccessTokenHandler { private $client; + private $accessToken; public function __construct(Client $client) { @@ -29,22 +30,27 @@ public function __invoke(callable $handler) private function getAccessToken() { - $base64Credentials = base64_encode(sprintf('%s:%s', - $this->client->getConfig('client_id'), - $this->client->getConfig('client_secret'))); - - $response = $this->client->post('/oauth2/token', [ - 'headers' => [ - 'Authorization' => sprintf('Basic %s', $base64Credentials) - ], - 'form_params' => [ - 'grant_type' => 'client_credentials', - 'scope' => 'tasks deliveries' - ] - ]); - - $data = json_decode((string) $response->getBody(), true); - - return $data['access_token']; + if (null === $this->accessToken) { + + $base64Credentials = base64_encode(sprintf('%s:%s', + $this->client->getConfig('client_id'), + $this->client->getConfig('client_secret'))); + + $response = $this->client->post('/oauth2/token', [ + 'headers' => [ + 'Authorization' => sprintf('Basic %s', $base64Credentials) + ], + 'form_params' => [ + 'grant_type' => 'client_credentials', + 'scope' => 'tasks deliveries' + ] + ]); + + $data = json_decode((string) $response->getBody(), true); + + $this->accessToken = $data['access_token']; + } + + return $this->accessToken; } }