<?php
// PHP 8+, extensión cURL. Ejecutar sólo deliberadamente con material autorizado.
function envRequired($name) { $v=getenv($name); if ($v===false || $v==='') throw new RuntimeException("Falta ".$name); return $v; }
$base='https://sandbox-integracfdi.cfdicomplete.com';
function callApi($method,$path,$headers=[],$body=null) {
 global $base; $h=curl_init($base.$path);
 curl_setopt_array($h,[CURLOPT_CUSTOMREQUEST=>$method,CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>120,CURLOPT_FOLLOWLOCATION=>false,CURLOPT_HTTPHEADER=>$headers]);
 if($body!==null) curl_setopt($h,CURLOPT_POSTFIELDS,$body);
 $text=curl_exec($h);$status=curl_getinfo($h,CURLINFO_HTTP_CODE);$failed=($text===false);curl_close($h);
 if($failed) throw new RuntimeException('Transporte incierto; no reenviar');
 return [$status,json_decode($text,true,512,JSON_THROW_ON_ERROR)];
}
[$status,$auth]=callApi('POST','/api/v1/auth/token',['Content-Type: application/json'],json_encode(['username'=>envRequired('CFDI_USERNAME'),'password'=>envRequired('CFDI_PASSWORD')],JSON_THROW_ON_ERROR));
if($status!==200) throw new RuntimeException('Autenticación rechazada');
$headers=['Authorization: Bearer '.$auth['accessToken']];
[$status,$balance]=callApi('GET','/api/v1/folios/balance',$headers);
if($status!==200) throw new RuntimeException('No se obtuvo saldo');
$bytes=file_get_contents(envRequired('CFDI_XML_PATH'));if($bytes===false) throw new RuntimeException('No se pudo leer XML');
[$status,$result]=callApi('POST','/api/v1/cfdi/stamp',array_merge($headers,['Content-Type: application/xml','Idempotency-Key: '.envRequired('CFDI_IDEMPOTENCY_KEY')]),$bytes);
if($status===200){/* entregar stampedXml sólo al flujo seguro del cliente, si existe */}
elseif($status===422){/* atender error.code y mensaje seguro; no repetir automáticamente */}
elseif($status===202){[$status,$state]=callApi('GET','/api/v1/cfdi/operations/'.rawurlencode($result['operationId']),$headers);}
else{/* distinguir 409/429/503 sin reintento automático */}
// No imprimir cuerpos, tokens ni XML. No reenviar al capturar errores de transporte.
