Created
May 28, 2020 09:51
-
-
Save domthomas-dev/48a205238322767d220bbe6506099b12 to your computer and use it in GitHub Desktop.
How use Token and prepare External API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Services; | |
use Illuminate\Http\Client\RequestException; | |
use Illuminate\Support\Facades\Cache; | |
use Illuminate\Support\Facades\Http; | |
use Illuminate\Support\Facades\Log; | |
class DummyApi | |
{ | |
const DummyTOKEN = 'DummyToken'; | |
const TOKEN_CACHE_LIFETIME_IN_SECONDS = 86400; | |
const MAX_REQUEST_TRIES = 5; | |
private string $url; | |
private string $login; | |
private string $password; | |
/** | |
* Indicates if we need to clear the token in cache to force the request of a new token | |
* @var boolean | |
*/ | |
private $clearTokenCache = false; | |
/** | |
* @var int | |
*/ | |
private $tries; | |
public function __construct() | |
{ | |
$this->url = config('DummyConfigFile.dummyapi.url'); | |
$this->login = config('DummyConfigFile.dummyapi.login'); | |
$this->password = config('DummyConfigFile.dummyapi.password'); | |
$this->tries = 0; | |
} | |
public function isClearTokenCache(): bool | |
{ | |
return $this->clearTokenCache; | |
} | |
public function setClearTokenCache(bool $clearTokenCache = true): self | |
{ | |
$this->clearTokenCache = $clearTokenCache; | |
return $this; | |
} | |
public function getBearer(): string | |
{ | |
if ($this->isClearTokenCache()) { | |
Cache::forget(self::DummyTOKEN); | |
$this->setClearTokenCache(false); | |
} | |
return Cache::remember(self::DummyTOKEN, self::TOKEN_CACHE_LIFETIME_IN_SECONDS, function () { | |
$result = Http::post($this->getUrl().'users/authenticate', [ //Change this | |
'login' => $this->login, | |
'password' => $this->password, | |
]); | |
return collect($result->json())->get('token'); | |
}); | |
} | |
public function getEndpoint(): array | |
{ | |
try { | |
$result = Http::withToken($this->getBearer())->get($this->getUrl().'endpoint', [ | |
// ... | |
]); | |
$result->throw(); | |
return $result->json(); | |
} catch (RequestException $exception) { | |
if (++$this->tries > self::MAX_REQUEST_TRIES) { | |
report($exception); | |
return collect([]); | |
} | |
return $this->setClearTokenCache()->getEndpoint(); | |
} | |
} | |
public function getUrl(): string | |
{ | |
return $this->url; | |
} | |
public function getLogin(): string | |
{ | |
return $this->login; | |
} | |
public function getPassword(): string | |
{ | |
return $this->password; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment