📊 Document Management
Complete documentation for creating and managing electronic documents in SRI system.
📄 Create Document
Endpoint: POST /api/document/register
Create electronic documents (invoices, credit notes, withholdings) with automatic XML generation and SRI submission.
Required Headers
| Header | Required | Descripción | |||||
| -------- | ---------- | ------------- | |||||
Authorization | ✅ | Bearer token | |||||
Content-Type | ✅ | application/json | |||||
Idempotency-Key | ✅ | Unique key for create/retry safety | |||||
| Type | Código | Descripción | Examples | ||||
| ------ | ------ | ------------- | ---------- | ||||
| Factura | 01 | Sales invoice with taxes and payment details | Factura Examples | ||||
| Nota de Crédito | 04 | Document modification or cancellation | Nota de Crédito Examples | ||||
| Retención | 07 | Tax withholding certificate | Retención Examples | ||||
| Type | SRI code | Percentage code | Name | Rate | Estado | ||
| ------ | ---------- | ----------------- | ------ | ------ | -------- | ||
| IVA | 2 | 0 | 0% | 0.00% | Active | ||
| IVA | 2 | 2 | 13% | 13.00% | Active | ||
| IVA | 2 | 5 | 5% - Construction | 5.00% | Active | ||
| IVA | 2 | 6 | Tax exempt / not subject | 0.00% | Active | ||
| IVA | 2 | 7 | VAT exempt | 0.00% | Active | ||
| IVA | 2 | 4 | 15% | 15.00% | Active | ||
| IRBPNR | 5 | 2 | Plastics | 2.00% | Active | ||
| ICE | 3 | 3031 | Alcoholic beverages | 0.00% | Active | ||
| ICE | 3 | 3011 | Cigarettes | 0.00% | Active | ||
| ICE | 3 | 3051 | Soft drinks | 0.00% | Active | ||
| ICE | 3 | 3041 | Beer | 0.00% | Active | ||
| ICE | 3 | 3073 | Vehicles | 0.00% | Active | ||
| Parameter | Type | Required | Descripción | Validation | |||
| ----------- | ------ | ---------- | ------------- | ------------ | |||
ruc | string | ✅ | RUC de Empresa (13 digits) | `required | string | regex:/^[0-9]{13}$/ | exists:companies,ruc` |
tipo | string | ✅ | Document type (01, 04, 07) | `required | in:01,04,07` | ||
id_externo | string | ✅ | External document ID | `required | string | max:100` | |
fecha_emision | string | ✅ | Issue date (DD/MM/YYYY) | `required | date_format:d/m/Y` | ||
establecimiento | string | ✅ | Establishment code (3 digits) | `required | string | regex:/^[0-9]{3}$/` | |
punto_emision | string | ✅ | Emission point code (3 digits) | `required | string | regex:/^[0-9]{3}$/` | |
secuencial | string | ✅ | Secuencial number (9 digits) | `required | string | regex:/^[0-9]{9}$/` | |
comprador | object | ✅ | Cliente information | Cliente validation rules | |||
detalles | array | ✅ | Document items array | Item validation rules | |||
formas_pago | array | ✅ | Payment methods array | Payment validation rules | |||
informacion_adicional | array | ❌ | Additional information | Additional info validation |
Ejemplo de Solicituds
#### 📄 Factura Example
curl -X POST "{{ url('/api/document/register') }}" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"ruc": "1712345678001",
"tipo": "01",
"id_externo": "FACT-2025-001",
"fecha_emision": "15/01/2025",
"establecimiento": "001",
"punto_emision": "001",
"secuencial": "000001234",
"comprador": {
"tipo_identificacion": "04",
"identificacion": "9999999999999",
"razon_social": "CONSUMIDOR FINAL",
"direccion": "Quito, Ecuador",
"email": "[email protected]",
"telefono": "+593 1234567"
},
"detalles": [
{
"codigo_principal": "PROD-001",
"descripcion": "Servicio de consultoría TI",
"cantidad": 1,
"precio_unitario": 100.00,
"detalles_adicionales": [
{
"codigo": "IVA",
"codigo_porcentaje": "2",
"base_imponible": 100.00,
"valor": 12.00
}
]
}
],
"formas_pago": [
{
"forma_pago": "20",
"total": 112.00,
"plazo": 0,
"unidad_tiempo": "dias"
}
]
}'
#### JavaScript Example
const createInvoice = async (invoiceData) => {
const response = await fetch('{{ url('/api/document/register') }}', {
method: 'POST',
headers: {
'Authorization': `Bearer ${localStorage.getItem('api_token')}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
ruc: "1712345678001",
tipo: "01",
id_externo: "FACT-2025-001",
fecha_emision: "15/01/2025",
establecimiento: "001",
punto_emision: "001",
secuencial: "000001234",
...invoiceData
})
});
const result = await response.json();
if (result.success) {
console.log('Invoice created:', result.data);
} else {
console.error('Error:', result.errors);
}
return result;
};
Cliente Object Structure
{
"tipo_identificacion": "04",
"identificacion": "9999999999999",
"razon_social": "CONSUMIDOR FINAL",
"direccion": "Guayaquil, Ecuador",
"email": "[email protected]",
"telefono": "+593 1234567"
}
#### Cliente Identification Types
| Type | Código | Descripción |
| ------ | ------ | ------------- |
| RUC | 04 | RUC de Empresa (13 digits) |
| DNI | 05 | National ID (10 digits) |
| Passport | 06 | Foreign passport |
| Consumer Final | 07 | Final consumer |
| Foreign ID | 08 | Foreign identification |
Item Object Structure
{
"codigo_principal": "PROD-001",
"codigo_auxiliar": "AUX-001",
"descripcion": "Product or service description",
"cantidad": 1.50,
"precio_unitario": 100.00,
"descuento": 0.00,
"detalles_adicionales": [
{
"codigo": "IVA",
"codigo_porcentaje": "2",
"base_imponible": 150.00,
"valor": 18.00
}
]
}
Tax Códigos (IVA)
| Código | Percentage | Descripción |
| ------ | ----------- | ------------- |
0 | 0% | Exempt |
2 | 12% | Regular IVA |
3 | 14% | Special IVA |
4 | 0% | Exempt export |
6 | NoIVA subject to IVA | |
| Código | Descripción | |
| ------ | ------------- | |
01 | Cash | |
15 | Credit card | |
16 | Bank debit | |
17 | Bank deposit | |
18 | Bank transfer | |
20 | Cash with reference |
Ejemplo de Respuestas
#### Success Response (201 Created)
{
"status": "ok",
"code": 200,
"message": "Register document successfully",
"data": {
"id": 12345,
"external_id": "FACT-2025-001",
"access_key": "12345678901234567890123456789012345678901",
"series": "001",
"sequential": "000001234",
"status": "GENERATED",
"issue_date": "2025-01-15",
"company_id": 789,
"created_at": "2025-01-15T10:30:00.000000Z",
"updated_at": "2025-01-15T10:30:00.000000Z"
}
}
#### Validation Error (422)
{
"status": "error",
"code": 422,
"message": "The given data was invalid.",
"errors": {
"ruc": ["The company RUC is required and must be 13 digits."],
"secuencial": ["The sequential number is required and must be 9 digits."],
"comprador.email": ["The email field is required when customer type is 04."]
},
"error_code": "DOC_001"
}
#### Authentication Error (401)
{
"status": "info",
"code": 401,
"message": "Invalid or expired API token.",
"error_code": "AUTH_003"
}
📦 Create Documents in Batch
Endpoint: POST /api/document/batch/register
Register up to 50 electronic documents in one request. The API validates and stores the batch first, then processes each item asynchronously in queue.
Required Headers
| Header | Required | Descripción | |||||
| -------- | ---------- | ------------- | |||||
Authorization | ✅ | Bearer token | |||||
Content-Type | ✅ | application/json | |||||
Idempotency-Key | ✅ | Required for idempotent batch registration | |||||
| Parameter | Type | Required | Descripción | Validation | |||
| ----------- | ------ | ---------- | ------------- | ------------ | |||
ruc | string | ✅ | RUC de Empresa (13 digits) | `required | string | size:13 | regex:/^[0-9]{13}$/` |
tipo | string | ✅ | Document type for entire batch | `required | in:01,04,07` | ||
documentos | array | ✅ | Batch documents list | `required | array | min:1 | max:50` |
documentos.*.id_externo | string | ✅ | External unique ID per item | `required | string | max:100` |
Importante Business Rules
id_externo cannot be duplicated inside the same batch.serie + secuencial cannot be duplicated inside the same batch.billing_limit validation error).tipo:01 requires factura - 04 requires nota - 07 requires retencioncURL Example (Factura Batch)
curl -X POST "{{ url('/api/document/batch/register') }}" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"ruc": "0707012605001",
"tipo": "01",
"documentos": [
{
"id_externo": "BATCH-INV-001",
"factura": {
"fecha": "18/05/2026",
"establecimiento": "001",
"puntoEmision": "001",
"secuencial": "000010001",
"descuento": 0,
"propina": 0,
"total": 115,
"cliente": {
"tipoIdentificacion": "05",
"documento": "0912345678",
"nombre": "Diego Jimenez",
"correo": "[email protected]",
"direccion": "Machala"
}
},
"detalles": [
{
"codigoPrincipal": "P-001",
"descripcion": "Producto A",
"cantidad": 1,
"precioUnitario": 100,
"descuento": 0,
"precioTotalSinImpuesto": 100,
"impuestos": [
{
"codigo": "2",
"codigoPorcentaje": "4",
"tarifa": 15,
"baseImponible": 100,
"valor": 15
}
]
}
],
"pagos": [
{
"formaPago": "01",
"total": 115,
"plazo": 0,
"unidadTiempo": "dias"
}
]
},
{
"id_externo": "BATCH-INV-002",
"factura": {
"fecha": "18/05/2026",
"establecimiento": "001",
"puntoEmision": "001",
"secuencial": "000010002",
"descuento": 0,
"propina": 0,
"total": 57.5,
"cliente": {
"tipoIdentificacion": "05",
"documento": "0923456789",
"nombre": "Cliente Dos",
"correo": "[email protected]",
"direccion": "Guayaquil"
}
},
"detalles": [
{
"codigoPrincipal": "P-002",
"descripcion": "Servicio B",
"cantidad": 1,
"precioUnitario": 50,
"descuento": 0,
"precioTotalSinImpuesto": 50,
"impuestos": [
{
"codigo": "2",
"codigoPorcentaje": "4",
"tarifa": 15,
"baseImponible": 50,
"valor": 7.5
}
]
}
],
"pagos": [
{
"formaPago": "01",
"total": 57.5,
"plazo": 0,
"unidadTiempo": "dias"
}
]
}
]
}'
Success Response (201 Created)
{
"status": "ok",
"code": 201,
"message": "Lote registrado correctamente",
"data": {
"batch_id": 18,
"batch_key": "01JVJZYQ4NWS4HYAYN1R3C9A6P",
"tipo": "01",
"documents_count": 2,
"total_size_bytes": 21340,
"status": "PENDING"
}
}
Ejemplo de Error de Validación (422)
{
"message": "The given data was invalid.",
"errors": {
"billing_limit": [
"Has alcanzado el limite mensual de documentos de tu plan Starter (300/300)."
],
"documentos": [
"El id_externo 'BATCH-INV-001' está repetido en el lote."
]
}
}
Recommended Follow-up
After receiving batch_id and batch_key, query your document status endpoint to track generated records as the queue processes the batch.
📊 Consultar Estado del Documento
Endpoint: GET /api/document/status
Query and monitor the status of submitted documents.
Request Parameters
| Parameter | Type | Required | Descripción | Validation | |||
| ----------- | ------ | ---------- | ------------- | ------------ | |||
ruc | string | ✅ | RUC de Empresa (13 digits) | `required | string | regex:/^[0-9]{13}$/ | exists:companies,ruc` |
status | string | ❌ | Filter by document status | in:GENERATED,SIGNED,RECEIVED,AUTHORIZED,REJECTED,ERROR | |||
external_id | string | ❌ | Filter by external ID | `string | max:100` | ||
access_key | string | ❌ | Filter by access key | `string | max:49` | ||
date_from | string | ❌ | Filter documents from date | date_format:Y-m-d | |||
date_to | string | ❌ | Filter documents to date | date_format:Y-m-d | |||
per_page | integer | ❌ | Results per page | `integer | min:1 | max:100` | |
page | integer | ❌ | Page number | `integer | min:1` | ||
include_xml | boolean | ❌ | Include XML content in response | boolean |
Ejemplo de Solicituds
#### Get All Company Documents
curl -X GET "{{ url('/api/document/status') }}?ruc=1712345678001" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json"
#### Filter by Estado
# Get only authorized documents
curl -X GET "{{ url('/api/document/status') }}?ruc=1712345678001&status=AUTHORIZED" \
-H "Authorization: Bearer YOUR_TOKEN"
#### Get Specific Document
# Get by external ID
curl -X GET "{{ url('/api/document/status') }}?ruc=1712345678001&external_id=FACT-2025-001" \
-H "Authorization: Bearer YOUR_TOKEN"
# Get by access key
curl -X GET "{{ url('/api/document/status') }}?ruc=1712345678001&access_key=12345678901234567890123456789012345678901" \
-H "Authorization: Bearer YOUR_TOKEN"
#### Date Range Query
# Get documents from January 2025
curl -X GET "{{ url('/api/document/status') }}?ruc=1712345678001&date_from=2025-01-01&date_to=2025-01-31" \
-H "Authorization: Bearer YOUR_TOKEN"
#### Paginated Results
curl -X GET "{{ url('/api/document/status') }}?ruc=1712345678001&per_page=10&page=2" \
-H "Authorization: Bearer YOUR_TOKEN"
JavaScript Example
const getDocuments = async (filters = {}) => {
const params = new URLSearchParams({
ruc: '1712345678001',
status: 'AUTHORIZED',
include_xml: true,
per_page: 20,
page: 1,
...filters
});
const response = await fetch(`{{ url('/api/document/status') }}?${params}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${localStorage.getItem('api_token')}`,
'Content-Type': 'application/json'
}
});
return response.json();
};
Ejemplo de Respuestas
#### Single Document Response
{
"status": "ok",
"code": 200,
"message": "Document status retrieved successfully",
"data": {
"document": {
"id": 12345,
"external_id": "FACT-2025-001",
"access_key": "12345678901234567890123456789012345678901",
"series": "001",
"sequential": "000001234",
"document_type": "01",
"status": "AUTHORIZED",
"authorization_number": "1234567890123456789",
"authorization_date": "2025-01-15T14:30:00.000000Z",
"issue_date": "2025-01-15",
"company": {
"id": 789,
"ruc": "1712345678001",
"razon_social": "EMPRESA DE EJEMPLO"
},
"created_at": "2025-01-15T10:30:00.000000Z",
"updated_at": "2025-01-15T14:45:00.000000Z"
}
}
}
#### Paginated Response
{
"status": "ok",
"code": 200,
"message": "Documents status retrieved successfully",
"data": {
"documents": [
{
"id": 12345,
"external_id": "FACT-2025-001",
"access_key": "12345678901234567890123456789012345678901",
"series": "001",
"sequential": "000001234",
"document_type": "01",
"status": "AUTHORIZED",
"company": {
"id": 789,
"ruc": "1712345678001",
"razon_social": "EMPRESA DE EJEMPLO"
}
}
],
"pagination": {
"current_page": 1,
"per_page": 10,
"total": 25,
"last_page": 3,
"has_more": true
},
"summary": {
"total_documents": 25,
"by_status": {
"GENERATED": 2,
"SIGNED": 3,
"RECEIVED": 5,
"AUTHORIZED": 10,
"REJECTED": 3,
"ERROR": 2
},
"finalized_documents": 15,
"processing_documents": 10
}
}
}
📥 Descargar PDF RIDE
Endpoint: GET /api/document/{access_key}/ride
Descargar PDF RIDE (Representación Impresa de Documentos Electrónicos) for authorized documents.
Request Parameters
| Parameter | Type | Required | Descripción | Validation | |||
| ----------- | ------ | ---------- | ------------- | ------------ | |||
access_key | string | ✅ | 49-digit document access key (URL parameter) | `required | string | size:49` | |
ruc | string | ✅ | RUC de Empresa for validation | `required | string | regex:/^[0-9]{13}$/ | exists:companies,ruc` |
Ejemplo de Solicituds
#### Descargar PDF RIDE
# Basic download
curl -X GET "{{ url('/api/document/12345678901234567890123456789012345678901/ride') }}?ruc=1712345678001" \
-H "Authorization: Bearer YOUR_TOKEN" \
-o "RIDE_document.pdf"
# Download with custom filename
curl -X GET "{{ url('/api/document/12345678901234567890123456789012345678901/ride') }}?ruc=1712345678001" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Disposition: attachment; filename=\"factura_001.pdf\"" \
-o "custom_filename.pdf"
#### JavaScript Download
const downloadRide = async (accessKey, ruc) => {
const response = await fetch(`{{ url('/api/document/${accessKey}/ride') }}?ruc=${ruc}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${localStorage.getItem('api_token')}`,
'Content-Type': 'application/json'
}
});
if (response.ok) {
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `RIDE_${accessKey}.pdf`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
} else {
const error = await response.json();
console.error('Download failed:', error.message);
}
};
// Usage
await downloadRide('12345678901234567890123456789012345678901', '1712345678001');
Ejemplo de Respuestas
#### Successful Download (200 OK)
- Estado: 200 OK
- Content-Type: application/pdf
- Content-Disposition: attachment; filename="RIDE_12345678901234567890123456789012345678901.pdf"
- Body: PDF file content
#### Document Not Found (404)
{
"status": "error",
"code": 404,
"message": "Document not found or access denied"
}
#### Document Not Authorized (422)
{
"status": "error",
"code": 422,
"message": "Only authorized documents can download RIDE PDF. Current status: RECEIVED",
"current_status": "RECEIVED",
"access_key": "12345678901234567890123456789012345678901"
}
#### RIDE File Not Found (404)
{
"status": "error",
"code": 404,
"message": "RIDE file not found. Please try regenerating.",
"access_key": "12345678901234567890123456789012345678901"
}
🔄 Document Annulment
Endpoint: POST /api/document/{accessKey}/annulment
Annullar documento de forma directa e inmediata. Solo requiere que el documento tenga estado AUTHORIZED.
Request Parameters
| Parameter | Type | Required | Descripción | Validation | ||
| ----------- | ------ | ---------- | ------------- | ------------ | ||
accessKey | string | ✅ | Clave de acceso del documento | - | ||
reason | string | ✅ | Motivo de anulación | `required | string | in:ERROR_IN_ISSUANCE,OPERATION_NOT_REALIZED,OTHERS` |
justification | string | ❌ | Descripción adicional | `sometimes | string | max:1000` |
| Código | Descripción | |||||
| ------ | ------------- | |||||
ERROR_IN_ISSUANCE | Error en los datos del documento | |||||
OPERATION_NOT_REALIZED | La operación no se concretó | |||||
OTHERS | Otro motivo justificado |
Ejemplo de Solicituds
#### Anular Documento
curl -X POST "{{ url('/api/document/2104202601179214876600120010010000001041234567890/annulment') }}" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"reason": "ERROR_IN_ISSUANCE",
"justification": "Factura emitida por error"
}'
Ejemplo de Respuestas
#### Success Response (200 OK)
{
"success": true,
"message": "Documento anulado exitosamente",
"data": {
"document": {
"access_key": "2104202601179214876600120010010000001041234567890",
"status": "ANNULLED"
},
"annulment": {
"id": 1,
"verification_code": "ANUL-A1B2C3D4E5F6",
"annulment_type": "ONLINE",
"reason": "Error en emisión",
"status": "Completada",
"annulled_at": "21/04/2026 10:30"
}
}
}
#### Error - Documento no autorizado
{
"success": false,
"message": "Solo pueden anularse documentos autorizados."
}
#### Error - Documento no encontrado
{
"success": false,
"message": "Documento no encontrado"
}
🛡️ Error Handling
Common Error Códigos
| Error Código | Descripción | Resolution |
| ----------- | ------------- | ------------ |
AUTH_001 | Invalid credentials | Check API token |
AUTH_002 | Account inactive | Contact administrator |
COMP_001 | Company not found | Verify company RUC |
COMP_002 | Company inactive | Activate company account |
DOC_001 | Document sequence exists | Use next sequential number |
DOC_002 | Total amount mismatch | Verify calculations |
DOC_003 | Invalid customer type | Check identification datos |
SRI_001 | Certificate invalid | Upload valid certificate |
SRI_002 | Document not authorized | Wait for authorization |
ANN_001 | Annulment deadline passed | Check SRI rules |
Error Response Structure
{
"status": "error",
"code": 400,
"message": "Human readable error message",
"error_code": "ERROR_CODE",
"errors": {
"field_name": ["Specific validation error message"]
},
"retry_after": 60,
"details": {
"additional_context": "Additional information for debugging"
}
}
📈 Best Practices
Request Management
- ✅ Always validate responses - Check
statusfield first - ✅ Handle rate limits - Implement exponential backoff
- ✅ Use appropriate HTTP methods - POST for creation, GET for queries
- ✅ Include proper headers - Authorization and Content-Type
- ✅ Validate input datos - Client-side validation before sending
- ✅ Handle file uploads - Use FormData for multipart/form-datos
- ✅ Parse error responses - Use
error_codefor programmatic handling - ✅ Display user-friendly mensajes - Show validation errores to users
- ✅ Implement retry logic - Retry recoverable errores with backoff
- ✅ Log errores for debugging - Record failed requests
- ✅ Handle network errores - Show connectivity issues
- ✅ Validate tokens - Handle expired or invalid tokens
- ✅ Protect API tokens - Store securely, never expose in frontend
- ✅ Use HTTPS | Always use secure connections
- ✅ Validate inputs | Sanitize all user inputs
- ✅ Implement rate limiting | Prevent abuse of API endpoints
- ✅ Check permissions | Validate user access to resources
- ✅ Audit logging | Log document operations for compliance
- 📘 Authentication Guide
- 🏢 Company Management
- ✅ Validation Rules
- 📋 SRI Annulment Rules 2025
- 📄 Factura Examples
- 📝 Nota de Crédito Examples
- 🧾 Retention Examples
- API Demo: Interactive Demo
- Soporte Email: [email protected]
- Documentación: Main Guide
- GitHub Issues: Report Issues
Error Handling
Security
📚 Related Documentación
🤝 Soporte & Resources
Last updated: January 2025 API Version: 1.0.0 SRI Rules Version: 2025