78 lines
2.0 KiB
PHP
78 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Api;
|
|
|
|
use Illuminate\Support\Facades\Http;
|
|
use Exception;
|
|
|
|
class BaseApiService
|
|
{
|
|
protected string $baseUrl;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->baseUrl = env('EXTERNAL_API_URL', 'http://localhost:8000/api');
|
|
}
|
|
|
|
protected function get($endpoint, array $params = [])
|
|
{
|
|
try {
|
|
$response = Http::withHeaders($this->getHeaders())
|
|
->get($this->baseUrl . $endpoint, $params);
|
|
|
|
return $this->handleResponse($response);
|
|
} catch (Exception $e) {
|
|
return $this->handleException($e);
|
|
}
|
|
}
|
|
|
|
protected function post($endpoint, array $data = [], $hasFile = false)
|
|
{
|
|
try {
|
|
$http = Http::withHeaders($this->getHeaders());
|
|
|
|
if ($hasFile) {
|
|
$http = $http->asMultipart();
|
|
}
|
|
|
|
$response = $http->post($this->baseUrl . $endpoint, $data);
|
|
return $this->handleResponse($response);
|
|
} catch (Exception $e) {
|
|
return $this->handleException($e);
|
|
}
|
|
}
|
|
|
|
protected function handleResponse($response)
|
|
{
|
|
if ($response->successful()) {
|
|
return [
|
|
'success' => true,
|
|
'data' => $response->json()['data'] ?? $response->json(),
|
|
'message' => 'Operation successful'
|
|
];
|
|
}
|
|
|
|
return [
|
|
'success' => false,
|
|
'message' => $response->json()['message'] ?? 'Operation failed',
|
|
'errors' => $response->json()['errors'] ?? []
|
|
];
|
|
}
|
|
|
|
protected function handleException(Exception $e)
|
|
{
|
|
return [
|
|
'success' => false,
|
|
'message' => 'API service is unavailable',
|
|
'errors' => [$e->getMessage()]
|
|
];
|
|
}
|
|
|
|
protected function getHeaders()
|
|
{
|
|
return [
|
|
'Accept' => 'application/json',
|
|
'Authorization' => 'Bearer ' . session('api_token')
|
|
];
|
|
}
|
|
}
|