cms-laravel/app/Services/ApiService.php

73 lines
2.1 KiB
PHP

<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Log;
class ApiService
{
protected $baseUrl;
public function __construct()
{
$this->baseUrl = config('app.api_base_url');
}
public function fetchData($url, $token = null)
{
try {
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . ($token ?: Session::get('token', '')),
])->get($this->baseUrl . $url);
if ($response->successful()) {
return $response->json();
} else {
$this->handleError($response);
return null;
}
} catch (\Exception $e) {
Log::error('API Fetch Error: ' . $e->getMessage());
Session::flash('error', 'Failed to fetch data: ' . $e->getMessage());
return null;
}
}
public function logout($token = null)
{
try {
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . ($token ?: Session::get('token', '')),
])->get($this->baseUrl . '/logout');
if ($response->successful()) {
Session::forget('token');
Session::flash('success', 'Logged out successfully.');
return true;
} else {
$this->handleError($response);
return false;
}
} catch (\Exception $e) {
Log::error('Logout Error: ' . $e->getMessage());
Session::flash('error', 'Logout failed: ' . $e->getMessage());
return false;
}
}
public function handleError($response)
{
$status = $response->status();
if ($status === 401) {
Session::forget('token');
throw new \Exception('Session expired. Please login again.');
} elseif ($status === 404) {
throw new \Exception('API resource not found.');
} else {
throw new \Exception('API error: ' . ($response->body() ?: 'Unknown error'));
}
}
}