Guzzle (PHP)
Ejemplos con Guzzle para integrar OCR Platform desde PHP/Laravel.
Reemplaza YOUR_API_KEY, rutas de archivo e IDs de ejemplo. URL base: https://ocr.789.com.mx/v1.
Instalación
composer require guzzlehttp/guzzle
Cliente base
use GuzzleHttp\Client;
$client = new Client([
'base_uri' => 'https://ocr.789.com.mx/v1/',
'headers' => [
'Accept' => 'application/json',
'X-API-Key' => 'YOUR_API_KEY',
],
'http_errors' => false,
]);
Health check (sin API Key)
$health = (new Client())->get('https://ocr.789.com.mx/health/live');
echo $health->getBody();
Crear documento
$response = $client->post('documents', [
'headers' => [
'Idempotency-Key' => (string) \Illuminate\Support\Str::uuid(),
],
'multipart' => [
['name' => 'file', 'contents' => fopen('/ruta/al/archivo.pdf', 'r'), 'filename' => 'archivo.pdf'],
['name' => 'profile', 'contents' => 'general_document'],
['name' => 'output_formats[]', 'contents' => 'markdown'],
['name' => 'output_formats[]', 'contents' => 'json'],
],
]);
$data = json_decode((string) $response->getBody(), true);
$documentId = $data['data']['id'] ?? null;
Consultar documento (polling)
$response = $client->get('documents/doc_01JXXXXXXXX');
$payload = json_decode((string) $response->getBody(), true);
$status = $payload['data']['status'] ?? null;
Repite hasta completed, partial_success, failed o cancelled.
Resultado OCR
$response = $client->get('documents/doc_01JXXXXXXXX/result', [
'query' => [
'format' => 'markdown',
'download' => 'false',
],
]);
Crear extracción
$response = $client->post('extractions', [
'headers' => [
'Content-Type' => 'application/json',
'Idempotency-Key' => (string) \Illuminate\Support\Str::uuid(),
],
'json' => [
'document_id' => 'doc_01JXXXXXXXX',
'custom_instruction' => 'Factura mexicana. Montos como número decimal sin símbolo de moneda.',
'response_schema' => [
'type' => 'object',
'additionalProperties' => false,
'required' => ['supplier_name', 'invoice_number', 'total'],
'properties' => [
'supplier_name' => ['type' => ['string', 'null']],
'invoice_number' => ['type' => ['string', 'null']],
'total' => ['type' => ['number', 'null'], 'description' => 'Total a pagar con impuestos.'],
],
],
'input_result_type' => 'markdown',
],
]);
Consultar extracción
$response = $client->get('extractions/ext_01JXXXXXXXX');
Resultado de extracción
$response = $client->get('extractions/ext_01JXXXXXXXX/result');
$datos = json_decode((string) $response->getBody(), true)['data']['result'];
Errores HTTP
Con http_errors => false Guzzle no lanza excepciones: comprueba $response->getStatusCode() y lee el error del cuerpo JSON.
if ($response->getStatusCode() >= 400) {
$body = json_decode((string) $response->getBody(), true);
$codigo = $body['error']['code']; // ej. validation_error
$mensaje = $body['error']['message'];
$detalles = $body['error']['details'] ?? null;
$requestId = $body['meta']['request_id'];
}
Ver Errores comunes.
Siguiente paso
- cURL — mismos flujos desde terminal.
- Referencia de endpoints — rutas
/v1disponibles.