ldc-legaulois/app/Lib/Axepta/AxeptaTokenManager.php

52 lines
1.7 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Lib\Axepta;
use Illuminate\Support\Facades\Cache;
use GuzzleHttp\Exception\RequestException;
class AxeptaTokenManager
{
private const string CACHE_KEY = "AxeptaBearerToken";
public function __construct(
private readonly AxeptaApiGateway $gateway,
private readonly AxeptaConfig $config
) {}
public function getToken(): string
{
if (Cache::has(self::CACHE_KEY)) {
return Cache::get(self::CACHE_KEY);
}
try {
$response = $this->gateway->postForm('/authorization/oauth/token', [
'grant_type' => 'client_credentials',
'client_id' => $this->config->merchantId,
'client_secret' => $this->config->apiKey
]);
if ($response->getStatusCode() !== 200) {
throw new \RuntimeException('Token request failed');
}
$body = json_decode($response->getBody()->getContents());
if (json_last_error() !== JSON_ERROR_NONE || !isset($body->access_token) || !isset($body->expires_in)) {
throw new \RuntimeException('Invalid token response');
}
Cache::put(self::CACHE_KEY, $body->access_token, $body->expires_in);
return $body->access_token;
} catch (RequestException $e) {
$errorBody = $e->hasResponse() ? $e->getResponse()->getBody()->getContents() : '{}';
$errorData = json_decode($errorBody, true);
$message = $errorData['error'] ?? $errorData['responseDescription'] ?? $e->getMessage();
throw new \RuntimeException("Axepta token error: {$message}", 0, $e);
}
}
}