arcos-backend/app/Services/ConsultaEstatalService.php

115 lines
3.2 KiB
PHP

<?php
namespace App\Services;
use Exception;
use Illuminate\Support\Facades\Log;
class ConsultaEstatalService
{
private string $soapUrl;
public function __construct()
{
$this->soapUrl = config('services.padron_estatal.url');
}
/**
* Consulta el padrón vehicular estatal vía SOAP
*/
private function consultarPadron(string $tipo, string $valor): array
{
// Construir el Data en formato JSON
$data = json_encode([
'tipo' => $tipo,
'valor' => $valor
]);
// Construir el cuerpo SOAP
$soapBody = <<<XML
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsdl="http://mx/tgc/ConsultaPadronVehicular.wsdl">
<soapenv:Header/>
<soapenv:Body>
<wsdl:getVehiculosRepuve>
<Data>{$data}</Data>
</wsdl:getVehiculosRepuve>
</soapenv:Body>
</soapenv:Envelope>
XML;
// Configurar cURL
$ch = curl_init($this->soapUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $soapBody);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: text/xml; charset=utf-8',
'SOAPAction: ""',
'Content-Length: ' . strlen($soapBody)
]);
try {
// Ejecutar la petición
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
if ($error) {
throw new Exception("Error en la petición: {$error}");
}
if ($httpCode !== 200) {
throw new Exception("Error HTTP {$httpCode}");
}
// Parsear la respuesta
return $this->parsearRespuesta($response);
} finally {
unset($ch);
}
}
/**
* Parsea la respuesta y extrae los datos del vehículo
*/
private function parsearRespuesta(string $soapResponse): array
{
// Extraer el contenido del tag <result>
preg_match('/<result>(.*?)<\/result>/s', $soapResponse, $matches);
if (!isset($matches[1])) {
throw new Exception("No se pudo extraer el resultado del padrón estatal");
}
$jsonContent = trim($matches[1]);
// Decodificar el JSON
$result = json_decode($jsonContent, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception("Error al decodificar JSON: " . json_last_error_msg());
}
if (!isset($result[0])) {
throw new Exception("Formato de respuesta inesperado");
}
$data = $result[0];
// Verificar si hay error
if ($data['error'] !== 0) {
throw new Exception("Error en consulta: código {$data['error']}");
}
// Verificar si hay datos
if (!isset($data['datos'][0])) {
throw new Exception("No se encontraron datos del vehículo");
}
return $data['datos'][0];
}
}