freescout2ant/Services/AmeiseTokenService.php
2025-04-21 13:19:16 +02:00

56 lines
1.6 KiB
PHP
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace Modules\AmeiseModule\Services;
use Modules\AmeiseModule\Entities\AmeiseToken;
use Carbon\Carbon;
use Illuminate\Support\Facades\Http;
class AmeiseTokenService
{
/**
* Liefert garantiert einen gültigen AccessToken zurück.
*/
public function getValidAccessToken(): string
{
$token = AmeiseToken::first();
if (! $token) {
throw new \RuntimeException('Kein OAuthToken gefunden bitte einmalig den OAuthFlow durchlaufen.');
}
// 60 Sekunden Puffer
if ($token->expires_at->lessThan(now()->addMinute())) {
$token = $this->refreshToken($token);
}
return $token->access_token;
}
/**
* Tauscht einen abgelaufenen Token gegen einen neuen aus.
*/
public function refreshToken(AmeiseToken $token): AmeiseToken
{
$response = Http::asForm()->post(config('ameisemodule.ameise_oauth_token_url'), [
'grant_type' => 'refresh_token',
'refresh_token' => $token->refresh_token,
'client_id' => config('ameisemodule.ameise_client_id'),
'client_secret' => config('ameisemodule.ameise_client_secret'),
]);
if ($response->failed()) {
throw new \RuntimeException('TokenRefresh fehlgeschlagen: '.$response->body());
}
$data = $response->json();
$token->update([
'access_token' => $data['access_token'],
'refresh_token' => $data['refresh_token'] ?? $token->refresh_token,
'expires_at' => Carbon::now()->addSeconds($data['expires_in']),
]);
return $token;
}
}