Facturas
Facturas
Section titled “Facturas”Dominio: https://test-api-factura.edw-dev.com
Dominio: https://api-financiero.e-dinky.com
Las facturas son documentos electrónicos que respaldan la transferencia de bienes o la prestación de servicios. Son el tipo de documento más común en el sistema de facturación electrónica del SRI.
Información General
Section titled “Información General”- Código SRI:
01
- Tipo de documento: Factura
- Uso: Venta de productos y servicios
- Cliente requerido: Sí
- Emisión automática: Opcional
Endpoint
Section titled “Endpoint”POST /api/v1/documents/create
Headers Requeridos
Section titled “Headers Requeridos”Content-Type: application/jsonAccept: application/jsonAuthorization: Bearer {token}
Parámetros Específicos
Section titled “Parámetros Específicos”Parámetro | Tipo | Requerido | Descripción |
---|---|---|---|
sri_code_document | string | Sí | Debe ser "01" para facturas |
send_to_emit | boolean | No | Si se debe emitir automáticamente al SRI |
customer | object | Sí | Información del cliente |
document | object | Sí | Información del documento |
items | array | Sí | Array de productos/servicios |
payments | array | No | Formas de pago |
aditional_fields | array | No | Campos adicionales |
Estructura del Cliente
Section titled “Estructura del Cliente”{ "identification_number": "0123456789", "name": "Juan", "lastname": "Pérez", "identification_type": "CEDULA", "address": "Quito, Ecuador", "phone": "0987654321"}
Estructura del Documento
Section titled “Estructura del Documento”{ "date": "2024-01-15", "establishment": "001", "point_of_emission": "001", "currency": "DOLAR"}
Estructura de Items
Section titled “Estructura de Items”{ "code": "PROD-001", "description": "Producto de ejemplo", "rate": 10.00, "quantity": 2, "discount": 0, "subtotal": 20.00, "taxes": [ { "code": "2", "percentaje_code": "2", "percentaje_tax": 12, "total_tax": 2.40 } ]}
Ejemplos de Implementación
Section titled “Ejemplos de Implementación”Factura Simple
Section titled “Factura Simple”Solicitud
Section titled “Solicitud”{ "sri_code_document": "01", "send_to_emit": true, "customer": { "identification_number": "0123456789", "name": "Juan", "lastname": "Pérez", "identification_type": "CEDULA", "address": "Quito, Ecuador" }, "document": { "date": "2024-01-15", "establishment": "001", "point_of_emission": "001" }, "items": [ { "code": "PROD-001", "description": "Producto de ejemplo", "rate": 10.00, "quantity": 2, "discount": 0, "subtotal": 20.00, "taxes": [ { "code": "2", "percentaje_code": "2", "percentaje_tax": 12, "total_tax": 2.40 } ] } ]}
Respuesta Exitosa (201)
Section titled “Respuesta Exitosa (201)”{ "message": "Documento creado exitosamente", "status": "CREATED", "payload": { "id": 123456789, "environment": "PROD", "number": 1, "date": "2024-01-15", "total": "22.40", "customer": { "id": 987654321, "full_name": "Juan Pérez", "identification_type": "cedula", "identification_number": "0123456789" }, "sri": { "access_key": "1501202401012345678900110010010000000011234567890", "status": "AUTORIZADO", "sequential_number": "000000001", "establishment": "001", "point_emission": "001", "document_number": "001-001-000000001" }, "items": [ { "position": 1, "code": "PROD-001", "description": "Producto de ejemplo", "rate": "10.00", "quantity": "2.00", "subtotal": "20.00", "total_tax": "2.40", "total": "22.40" } ], "taxes": [ { "tax_type": "IVA", "tax_name": "12%", "tax_rate": "2.40", "tax_subtotal": "20.00" } ] }}
Factura con Datos Completos
Section titled “Factura con Datos Completos”Solicitud
Section titled “Solicitud”{ "sri_code_document": "01", "send_to_emit": true, "customer": { "identification_number": "0123456789", "name": "María", "lastname": "González", "identification_type": "CEDULA", "address": "Guayaquil, Ecuador" }, "document": { "date": "2024-01-15", "establishment": "001", "point_of_emission": "001" }, "items": [ { "code": "SERV-001", "description": "Servicio de consultoría", "rate": 100.00, "quantity": 1, "discount": 10.00, "subtotal": 90.00, "taxes": [ { "code": "2", "percentaje_code": "2", "percentaje_tax": 12, "total_tax": 10.80 } ] } ], "payments": [ { "amount": 100.80, "code": "20" } ], "aditional_fields": [ { "key": "Observaciones", "value": "Servicio prestado en enero 2024", "type": "sri" } ]}
Factura con ICE e IVA
Section titled “Factura con ICE e IVA”Solicitud
Section titled “Solicitud”{ "sri_code_document": "01", "send_to_emit": true, "customer": { "identification_number": "9999999999", "name": "Final", "lastname": "Consumidor", "identification_type": "CEDULA", "address": "Guayaquil" }, "document": { "date": "2024-10-26", "sri_establishment": "001", "sri_point_emi": "004" }, "items": [ { "code": "ICE-001", "description": "ITEM PRUEBAS ICE 2", "rate": 100, "quantity": 1, "subtotal": 100, "total_tax": 26.5, "total": 126.5, "taxes": [ { "code": "3", "percentaje_code": "3053", "percentaje_tax": 10, "total_tax": 10 }, { "code": "2", "percentaje_code": "4", "percentaje_tax": 15, "total_tax": 16.50 } ] } ], "aditional_fields": [ { "key": "Telefono", "value": "099999", "type": "sri" }, { "key": "Email", "type": "sri" } ]}
Respuesta con ICE e IVA (201)
Section titled “Respuesta con ICE e IVA (201)”{ "message": "Documento creado y emitido", "status": "CREATED", "payload": { "id": 894456400, "environment": "TEST", "number": 15, "date": "2024-10-26", "subtotal": "200.00", "tax_amount": "53.00", "total": "253.00", "status": "published", "type": "invoice", "customer": { "id": 61247344, "full_name": "Consumidor Final", "identification_type": "cedula", "identification_number": "9999999999" }, "sri": { "access_key": "2610202401095261517700110010040000000441234567916", "status": null, "sequential_doc": "000000044", "establishment": "001", "point_emi": "004", "number_document": "001-004-000000044", "type_document": "FACTURA", "code_document": "01" }, "items": [ { "position": 1, "code": "ICE-001", "description": "ITEM PRUEBAS ICE 2", "rate": "100.00", "quantity": "1.00", "subtotal": "100.00", "total_tax": "26.50", "total": "126.50", "taxes": [ { "type": "ICE", "name": "ICE Bebidas Gaseosas con Alto Contenido de Azúcar", "code": "3", "percentaje_code": "3053", "rate_before_tax": "100.00", "percentaje_tax": "10.00", "total_tax": "10.00", "rate_after_tax": "110.00" }, { "type": "IVA", "name": "15%", "code": "2", "percentaje_code": "4", "rate_before_tax": "110.00", "percentaje_tax": "15.00", "total_tax": "16.50", "rate_after_tax": "126.50" } ] } ], "taxes": [ { "tax_type": "ICE", "tax_name": "ICE Bebidas Gaseosas con Alto Contenido de Azúcar", "tax_rate": "20.00", "tax_subtotal": "200.00", "tax_code": "3", "tax_code_sri": "3053" }, { "tax_type": "IVA", "tax_name": "15%", "tax_rate": "33.00", "tax_subtotal": "220.00", "tax_code": "2", "tax_code_sri": "4" } ] }}
Ejemplos de Código
Section titled “Ejemplos de Código”curl -X POST "https://dev-facturacion.e-dinky.test/api/v1/documents/create" \ -H "Content-Type: application/json" \ -H "Accept: application/json" \ -H "Authorization: Bearer {token}" \ -d '{ "sri_code_document": "01", "send_to_emit": true, "customer": { "identification_number": "0123456789", "name": "Juan", "lastname": "Pérez", "identification_type": "CEDULA", "email": "[email protected]", "address": "Quito, Ecuador" }, "document": { "date": "2024-01-15", "establishment": "001", "point_of_emission": "001" }, "items": [ { "code": "PROD-001", "description": "Producto de ejemplo", "rate": 10.00, "quantity": 2, "discount": 0, "subtotal": 20.00, "taxes": [ { "code": "2", "percentaje_code": "2", "percentaje_tax": 12, "total_tax": 2.40 } ] } ] }'
<?php
use Illuminate\Support\Facades\Http;
$token = 'your-api-token';
$response = Http::withHeaders([ 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'Authorization' => 'Bearer ' . $token,])->post('https://dev-facturacion.e-dinky.test/api/v1/documents/create', [ 'sri_code_document' => '01', 'send_to_emit' => true, 'customer' => [ 'identification_number' => '0123456789', 'name' => 'Juan', 'lastname' => 'Pérez', 'identification_type' => 'CEDULA', 'address' => 'Quito, Ecuador' ], 'document' => [ 'date' => '2024-01-15', 'establishment' => '001', 'point_of_emission' => '001' ], 'items' => [ [ 'code' => 'PROD-001', 'description' => 'Producto de ejemplo', 'rate' => 10.00, 'quantity' => 2, 'discount' => 0, 'subtotal' => 20.00, 'taxes' => [ [ 'code' => '2', 'percentaje_code' => '2', 'percentaje_tax' => 12, 'total_tax' => 2.40 ] ] ] ]]);
if ($response->successful()) { $document = $response->json(); echo "Factura creada: " . $document['payload']['id']; echo "Número de documento: " . $document['payload']['sri']['document_number']; echo "Clave de acceso: " . $document['payload']['sri']['access_key']; echo "Total: $" . $document['payload']['total'];} else { echo "Error: " . $response->body();}
const axios = require('axios');
const createInvoice = async () => { const token = 'your-api-token';
const config = { method: 'post', url: 'https://dev-facturacion.e-dinky.test/api/v1/documents/create', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': `Bearer ${token}` }, data: { sri_code_document: '01', send_to_emit: true, customer: { identification_number: '0123456789', name: 'Juan', lastname: 'Pérez', identification_type: 'CEDULA', address: 'Quito, Ecuador' }, document: { date: '2024-01-15', establishment: '001', point_of_emission: '001' }, items: [ { code: 'PROD-001', description: 'Producto de ejemplo', rate: 10.00, quantity: 2, discount: 0, subtotal: 20.00, taxes: [ { code: '2', percentaje_code: '2', percentaje_tax: 12, total_tax: 2.40 } ] } ] } };
try { const response = await axios(config); console.log('Factura creada:', response.data.payload.id); console.log('Número de documento:', response.data.payload.sri.document_number); console.log('Clave de acceso:', response.data.payload.sri.access_key); console.log('Total: $', response.data.payload.total); return response.data; } catch (error) { console.error('Error:', error.response?.data || error.message); throw error; }};
// UsocreateInvoice() .then(result => console.log('Éxito:', result)) .catch(error => console.error('Error:', error));
Tipos de Facturas
Section titled “Tipos de Facturas”1. Factura de Productos
Section titled “1. Factura de Productos”- Incluye productos físicos con inventario
- Requiere código de producto válido
- Puede incluir descuentos por volumen
- Aplica IVA según la categoría del producto
2. Factura de Servicios
Section titled “2. Factura de Servicios”- Para prestación de servicios profesionales
- No requiere manejo de inventario
- Puede incluir retenciones en la fuente
- Generalmente gravada con IVA 12%
3. Factura Mixta
Section titled “3. Factura Mixta”- Combina productos y servicios
- Cada item puede tener diferentes impuestos
- Cálculos separados por tipo de item
4. Factura con ICE
Section titled “4. Factura con ICE”- Para productos con Impuesto a Consumos Especiales
- Requiere códigos específicos de ICE
- Cálculo en cascada: ICE primero, luego IVA
- Productos como alcohol, cigarrillos, bebidas
Validaciones Específicas
Section titled “Validaciones Específicas”Cliente
Section titled “Cliente”- RUC: Debe tener 13 dígitos y pasar validación
- Cédula: Debe tener 10 dígitos y pasar validación
- Email: Formato válido requerido
- Dirección: Obligatoria para facturas
Documento
Section titled “Documento”- Fecha: No puede ser futura ni muy antigua
- Establecimiento: Debe estar registrado en el SRI
- Punto de emisión: Debe estar activo
- Secuencial: Se genera automáticamente
- Código: Debe existir en el catálogo
- Descripción: Mínimo 3 caracteres
- Cantidad: Mayor a 0
- Precio: Mayor o igual a 0
- Impuestos: Códigos válidos del SRI
Totales
Section titled “Totales”- Subtotal: Suma de todos los items
- Impuestos: Cálculo correcto según tarifas
- Total: Subtotal + impuestos - descuentos
- Cuadre: Validación matemática exacta
Códigos de Respuesta
Section titled “Códigos de Respuesta”Código | Descripción | Acción |
---|---|---|
201 | Factura creada exitosamente | Continuar con el flujo |
400 | Datos inválidos | Revisar formato de datos |
401 | Token inválido | Renovar autenticación |
422 | Error de validación | Corregir datos según errores |
500 | Error del servidor | Reintentar más tarde |
Errores Comunes
Section titled “Errores Comunes”Error de Validación (422)
Section titled “Error de Validación (422)”{ "message": "Error de validación", "status": "UNPROCESSABLE_ENTITY", "errors": { "customer.identification_number": [ "El número de identificación no es válido" ], "items.0.rate": [ "El precio debe ser mayor a 0" ], "items.0.taxes.0.total_tax": [ "El cálculo del impuesto no es correcto" ] }}
Soluciones
Section titled “Soluciones”-
RUC/Cédula inválida
- Verificar dígito verificador
- Usar algoritmo de validación ecuatoriano
- Confirmar longitud correcta
-
Precio inválido
- Asegurar que sea numérico
- Valor mayor o igual a 0
- Máximo 2 decimales
-
Impuestos incorrectos
- Verificar códigos del SRI
- Calcular porcentajes exactos
- Validar base imponible
Mejores Prácticas
Section titled “Mejores Prácticas”1. Validación Previa
Section titled “1. Validación Previa”// Validar RUC/Cédula antes de enviar$validator = new EcuadorianIdValidator();if (!$validator->isValid($identification)) { throw new InvalidIdentificationException();}
2. Cálculo de Impuestos
Section titled “2. Cálculo de Impuestos”// Calcular IVA correctamenteconst calculateIVA = (subtotal, rate) => { return Math.round((subtotal * rate / 100) * 100) / 100;};
3. Manejo de Errores
Section titled “3. Manejo de Errores”try { $response = $this->createInvoice($data); return $response;} catch (ValidationException $e) { // Manejar errores de validación $this->logErrors($e->getErrors()); throw $e;} catch (SriException $e) { // Manejar errores del SRI $this->retryLater($data);}
4. Testing
Section titled “4. Testing”# Usar ambiente de pruebascurl -X POST "https://api-test.factura-dinky.com/api/v1/documents/create" \ -H "Authorization: Bearer test-token" \ -d @factura-test.json
Flujo Recomendado
Section titled “Flujo Recomendado”-
Validar datos del cliente
- Verificar RUC/cédula
- Confirmar email válido
- Validar dirección
-
Preparar items
- Verificar códigos de productos
- Calcular subtotales
- Aplicar descuentos
- Calcular impuestos
-
Crear factura
- Enviar solicitud POST
- Verificar respuesta
- Manejar errores
-
Procesar resultado
- Guardar ID del documento
- Almacenar clave de acceso
- Notificar al cliente
-
Seguimiento
- Verificar autorización del SRI
- Generar PDF
- Enviar por email
Notas Importantes
Section titled “Notas Importantes”- 📋 Secuenciales únicos: Cada factura tiene un número secuencial único por establecimiento
- 🔐 Firma digital: Las facturas se firman automáticamente con el certificado configurado
- ⏰ Tiempo límite: El SRI tiene hasta 72 horas para autorizar una factura
- 📧 Notificaciones: Los emails se envían automáticamente si están configurados
- 💾 Almacenamiento: Las facturas se almacenan permanentemente en el sistema
- 🔄 Estados: Las facturas pasan por diferentes estados hasta ser autorizadas
- 📊 Reportes: Todas las facturas aparecen en los reportes del SRI automáticamente
- 🚫 Anulación: Las facturas autorizadas no se pueden modificar, solo anular con nota de crédito