Files
musadaq-saas/app/Services/JoFotara/JoFotaraGateway.php

75 lines
2.1 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Services\JoFotara;
use GuzzleHttp\Client;
use App\Core\Redis;
use Exception;
final class JoFotaraGateway
{
private Client $client;
private string $baseUrl;
public function __construct()
{
$this->client = new Client();
$this->baseUrl = $_ENV['JOFOTARA_BASE_URL'] ?? 'https://backend.jofotara.gov.jo/core/invoices';
}
/**
* Submit invoice to JoFotara with Circuit Breaker
*/
public function submitInvoice(string $companyId, string $xmlBase64, array $credentials): array
{
$cbKey = "cb:jofotara:{$companyId}";
if ($this->isCircuitOpen($cbKey)) {
throw new Exception("بوابة جو-فواتير غير متاحة حالياً لهذه الشركة، يرجى المحاولة لاحقاً");
}
try {
$response = $this->client->post($this->baseUrl, [
'json' => [
'clientId' => $credentials['clientId'],
'secretKey' => $credentials['secretKey'],
'invoiceType' => 'invoice',
'invoiceData' => $xmlBase64
],
'timeout' => 30
]);
$result = json_decode($response->getBody()->getContents(), true);
$this->resetFailures($cbKey);
return $result;
} catch (\Throwable $e) {
$this->recordFailure($cbKey);
throw $e;
}
}
private function isCircuitOpen(string $key): bool
{
$redis = Redis::getInstance();
return (bool)$redis->get("{$key}:open");
}
private function recordFailure(string $key): void
{
$redis = Redis::getInstance();
$failures = (int)$redis->incr("{$key}:failures");
if ($failures >= 5) {
$redis->setex("{$key}:open", 300, 1); // Open for 5 minutes
}
}
private function resetFailures(string $key): void
{
$redis = Redis::getInstance();
$redis->del(["{$key}:failures", "{$key}:open"]);
}
}