src/Services/ApiConsumer.php line 61

Open in your IDE?
  1. <?php
  2. namespace App\Services;
  3. use App\Utils\EAS256CBC;
  4. use Psr\Cache\InvalidArgumentException;
  5. use Psr\Log\LoggerInterface;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Contracts\Cache\CacheInterface;
  8. use Symfony\Contracts\Cache\ItemInterface;
  9. use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
  10. use Symfony\Contracts\HttpClient\HttpClientInterface;
  11. class ApiConsumer
  12. {
  13.     private const API_TIMEOUT_SECONDS 8;
  14.     private const API_MAX_DURATION_SECONDS 20;
  15.     private const API_TOTAL_ATTEMPTS 1;
  16.     protected HttpClientInterface $client;
  17.     protected CacheInterface $cache;
  18.     protected EAS256CBC      $EAS256CBC;
  19.     private LoggerInterface  $logger;
  20.     private LoggerInterface  $errorLogger;
  21.     private $cliente 'tomatsa';
  22.     private $pass    'ETCHEBARNE';
  23.     protected static string $apiUrl 'http://10.10.10.8/whMainWebApi/';
  24.     public static string $key "hUf3eof71VCa8IIjFlNewZ73yBWjckdX";
  25.     public function __construct(CacheInterface $cacheEAS256CBC $EAS256CBCHttpClientInterface $clientLoggerInterface $loggerLoggerInterface $errorLogger)
  26.     {
  27.         $this->client    $client;
  28.         $this->cache     $cache;
  29.         $this->EAS256CBC $EAS256CBC;
  30.         $this->logger    $logger;
  31.         $this->errorLogger $errorLogger;
  32.     }
  33.     public function getDataApi($service$parameters$json false$expire 3600)
  34.     {
  35.         if ($service == 'getPedidoSeguimiento2') {
  36.             $cache_key md5(uniqid());
  37.         } else {
  38.             $cache_key md5($service '-' json_encode($parameters));
  39.         }
  40.         try {
  41.             if ($this->cache->hasItem($cache_key)) {
  42.                 return $this->cache->getItem($cache_key)->get();
  43.             }
  44.             for ($attempt 1$attempt <= self::API_TOTAL_ATTEMPTS$attempt++) {
  45.                 try {
  46.                     $startTime microtime(true);
  47.                     $response $this->client->request('POST'self::$apiUrl $service, [
  48.                         'headers' => [
  49.                             'accept' => '*/*'
  50.                         ],
  51.                         'body'         => $parameters,
  52.                         'timeout'      => self::API_TIMEOUT_SECONDS,
  53.                         'max_duration' => self::API_MAX_DURATION_SECONDS,
  54.                     ]);
  55.                     $content $json json_decode($response->getContent()) : $response->getContent();
  56.                     $durationMs = (microtime(true) - $startTime) * 1000;
  57.                     $this->logger->info('API response time', [
  58.                         'service' => $service,
  59.                         'duration_ms' => round($durationMs2),
  60.                         'attempt' => $attempt,
  61.                         'parameters' => $parameters,
  62.                     ]);
  63.                     $cacheItem $this->cache->getItem($cache_key);
  64.                     $cacheItem->set($content);
  65.                     $cacheItem->expiresAfter($expire);
  66.                     $this->cache->save($cacheItem);
  67.                     return $content;
  68.                 } catch (TransportExceptionInterface $e) {
  69.                     $this->errorLogger->warning('API transport error, retrying', [
  70.                         'service' => $service,
  71.                         'attempt' => $attempt,
  72.                         'max_attempts' => self::API_TOTAL_ATTEMPTS,
  73.                         'parameters' => $parameters,
  74.                         'exception' => $e,
  75.                     ]);
  76.                     if ($attempt === self::API_TOTAL_ATTEMPTS) {
  77.                         throw $e;
  78.                     }
  79.                 }
  80.             }
  81.             // Nunca deberia llegar aqui, pero evita retornos implicitos si cambian los intentos.
  82.             throw new \RuntimeException('No fue posible obtener respuesta del API.');
  83.         } catch (TransportExceptionInterface|InvalidArgumentException|\Exception $e) {
  84.             $this->errorLogger->error('API error', [
  85.                 'service' => $service,
  86.                 'parameters' => $parameters,
  87.                 'exception' => $e,
  88.             ]);
  89.             return new Response('Error al consumir la API: ' $e->getMessage(), 500);
  90.         }
  91.     }
  92.     public function getLoginToken(): string
  93.     {
  94.         return $this->getDataApi('getLoginToken', [
  95.             'TokenApi' => $this->EAS256CBC->encrypt('dm#dm'self::$key)
  96.         ]);
  97.     }
  98.     public function getWorkToken()
  99.     {
  100.         return $this->getDataApi('LoginByToken', [
  101.             'LoginToken' => $this->getLoginToken()
  102.         ]);
  103.     }
  104.     public function getClienteValidar($userPasswordHash)
  105.     {
  106.         return $this->getDataApi('getClienteValidar', [
  107.             'WorkToken' => $this->getWorkToken(),
  108.             'UserToken' => $userPasswordHash,
  109.         ],                       true);
  110.     }
  111.     //SOLO DE PRUEBA
  112.     public function getTokenUserPass()
  113.     {
  114.         return $this->getDataApi('getTokenUserPass', [
  115.             'WorkToken' => $this->getWorkToken(),
  116.             'usuario'   => $this->cliente$this->cliente,
  117.             'password'  => $this->pass,
  118.         ]);
  119.     }
  120.     public function getclientList($userPasswordHash)
  121.     {
  122.         return $this->getDataApi('getClienteListado', [
  123.             'WorkToken' => $this->getWorkToken(),
  124.             'UserToken' => $userPasswordHash,
  125.         ],                       true);
  126.     }
  127.     public function getclientInv($id$userPasswordHash)
  128.     {
  129.         return $this->getDataApi('getInventario', [
  130.             'WorkToken'   => $this->getWorkToken(),
  131.             'UserToken'   => $userPasswordHash,
  132.             'cod_cliente' => $id,
  133.         ],                       true600);
  134.     }
  135.     public function getImportsTasksList($id$userPasswordHash)
  136.     {
  137.         return $this->getDataApi('getImportsTasksList', [
  138.             'WorkToken'   => $this->getWorkToken(),
  139.             'UserToken'   => $userPasswordHash,
  140.             'cod_cliente' => $id,
  141.         ],                       true600);
  142.     }
  143.     public function getImportsTasksFormats($id$userPasswordHash)
  144.     {
  145.         return $this->getDataApi('getImportsTasksFormats', [
  146.             'WorkToken' => $this->getWorkToken(),
  147.             'UserToken' => $userPasswordHash,
  148.             'id_Tarea'  => $id,
  149.         ],                       true600);
  150.     }
  151.     public function getPedidoSeguimiento($cod_cliente$userPasswordHash)
  152.     {
  153.         return $this->getDataApi('getPedidoSeguimiento', [
  154.             'WorkToken'   => $this->getWorkToken(),
  155.             'UserToken'   => $userPasswordHash,
  156.             'cod_cliente' => $cod_cliente,
  157.         ],                       true0);
  158.     }
  159.     public function getPedidoSeguimientoDetalle($cod_cliente$order_id$userPasswordHash)
  160.     {
  161.         return $this->getDataApi('getPedidoSeguimientoDetalle', [
  162.             'WorkToken'   => $this->getWorkToken(),
  163.             'UserToken'   => $userPasswordHash,
  164.             'cod_cliente' => $cod_cliente,
  165.             'Pedido'      => $order_id,
  166.         ],                       true600);
  167.     }
  168.     public function getImportsTasksFile($userPasswordHash$cod_cliente$id_seguimiento$id_tarea$archivo_64)
  169.     {
  170.         /*dump([
  171.                  'WorkToken'      => $this->getWorkToken(),
  172.                  'UserToken'      => $userPasswordHash,
  173.                  'cod_cliente'    => $cod_cliente,
  174.                  'id_seguimiento' => (string)$id_seguimiento,
  175.                  'id_tarea'       => $id_tarea,
  176. //                 'Extension'      => 'txt',
  177.                  'Archivo64'      => $archivo_64,
  178.              ]);
  179.         exit;*/
  180.         return $this->getDataApi('getImportsTasksFile', [
  181.             'WorkToken'      => $this->getWorkToken(),
  182.             'UserToken'      => $userPasswordHash,
  183.             'cod_cliente'    => $cod_cliente,
  184.             'id_seguimiento' => (string)$id_seguimiento,
  185.             'id_tarea'       => $id_tarea,
  186.             'Extension'      => 'txt',
  187.             'Archivo64'      => $archivo_64,
  188.         ],                       false0);
  189.     }
  190.     public function getImportsTasksTracking($id_seguimiento$BatchId$userPasswordHash$json false)
  191.     {
  192.         return $this->getDataApi('getImportsTasksTracking', [
  193.             'WorkToken'      => $this->getWorkToken(),
  194.             'UserToken'      => $userPasswordHash,
  195.             'id_seguimiento' => $id_seguimiento,
  196.             'BatchId'        => $BatchId,
  197.         ],                       $json0);
  198.     }
  199.     public function getFacturaResumen($userPasswordHash)
  200.     {
  201.         return $this->getDataApi('getFacturaResumen', [
  202.             'WorkToken' => $this->getWorkToken(),
  203.             'UserToken' => $userPasswordHash,
  204.         ],                       true);
  205.     }
  206.     public function getFacturaPDF($userPasswordHash$folio)
  207.     {
  208.         return $this->getDataApi('getFacturaPDF', [
  209.             'WorkToken' => $this->getWorkToken(),
  210.             'UserToken' => $userPasswordHash,
  211.             'Folio'     => $folio,
  212.         ],                       false);
  213.     }
  214.     public function getPowerBIList($userPasswordHash)
  215.     {
  216.         return $this->getDataApi('getPowerBiList', [
  217.             'WorkToken' => $this->getWorkToken(),
  218.             'UserToken' => $userPasswordHash,
  219.         ],                       true);
  220.     }
  221. }