📊 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

Idempotency Handling (Shared Concept)

Both creation endpoints (/api/document/register and /api/document/batch/register) use the same idempotency behavior to avoid duplicates and keep responses consistent.

  • Send a new Idempotency-Key for each new business operation.
  • Reuse the same Idempotency-Key only when retrying the exact same payload.
  • If the same key arrives with a different payload, API returns 409.
  • If the same key is still processing, API returns 409.
  • If the same key was already completed, API replays the stored response.

Tipo de Documentos Soporteed

SRI Tax Table

Use these codigo / codigoPorcentaje combinations for invoice and credit note taxes.

Request Parameters

HeaderRequiredDescripción
-------------------------------
AuthorizationBearer token
Content-Typeapplication/json
Idempotency-KeyUnique key for create/retry safety
TypeCódigoDescripciónExamples
-----------------------------------
Factura01Sales invoice with taxes and payment detailsFactura Examples
Nota de Crédito04Document modification or cancellationNota de Crédito Examples
Retención07Tax withholding certificateRetención Examples
TypeSRI codePercentage codeNameRateEstado
-----------------------------------------------------
IVA200%0.00%Active
IVA2213%13.00%Active
IVA255% - Construction5.00%Active
IVA26Tax exempt / not subject0.00%Active
IVA27VAT exempt0.00%Active
IVA2415%15.00%Active
IRBPNR52Plastics2.00%Active
ICE33031Alcoholic beverages0.00%Active
ICE33011Cigarettes0.00%Active
ICE33051Soft drinks0.00%Active
ICE33041Beer0.00%Active
ICE33073Vehicles0.00%Active
ParameterTypeRequiredDescripciónValidation
----------------------------------------------------
rucstringRUC de Empresa (13 digits)`requiredstringregex:/^[0-9]{13}$/exists:companies,ruc`
tipostringDocument type (01, 04, 07)`requiredin:01,04,07`
id_externostringExternal document ID`requiredstringmax:100`
fecha_emisionstringIssue date (DD/MM/YYYY)`requireddate_format:d/m/Y`
establecimientostringEstablishment code (3 digits)`requiredstringregex:/^[0-9]{3}$/`
punto_emisionstringEmission point code (3 digits)`requiredstringregex:/^[0-9]{3}$/`
secuencialstringSecuencial number (9 digits)`requiredstringregex:/^[0-9]{9}$/`
compradorobjectCliente informationCliente validation rules
detallesarrayDocument items arrayItem validation rules
formas_pagoarrayPayment methods arrayPayment validation rules
informacion_adicionalarrayAdditional informationAdditional 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

TypeCódigoDescripción
-------------------------
RUC04RUC de Empresa (13 digits)
DNI05National ID (10 digits)
Passport06Foreign passport
Consumer Final07Final consumer
Foreign ID08Foreign 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)

Payment Methods

CódigoPercentageDescripción
------------------------------
00%Exempt
212%Regular IVA
314%Special IVA
40%Exempt export
6NoIVA subject to IVA
CódigoDescripción
-------------------
01Cash
15Credit card
16Bank debit
17Bank deposit
18Bank transfer
20Cash 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

Batch Processing Flow

  • API validates the payload and billing limits.
  • Batch record is created with status PENDING.
  • Queue job (SendDocumentBatchJob) starts processing and moves status to PROCESSING.
  • Every item is processed independently:
  • - éxito item status: COMPLETED - failed item status: FAILED
  • Final batch status:
  • - COMPLETED if all items succeed - FAILED if one or more items fail

    Request Parameters

HeaderRequiredDescripción
-------------------------------
AuthorizationBearer token
Content-Typeapplication/json
Idempotency-KeyRequired for idempotent batch registration
ParameterTypeRequiredDescripciónValidation
----------------------------------------------------
rucstringRUC de Empresa (13 digits)`requiredstringsize:13regex:/^[0-9]{13}$/`
tipostringDocument type for entire batch`requiredin:01,04,07`
documentosarrayBatch documents list`requiredarraymin:1max:50`
documentos.*.id_externostringExternal unique ID per item`requiredstringmax:100`

Importante Business Rules

  • Maximum 50 documents per batch.
  • Maximum total XML size: 512 KB.
  • id_externo cannot be duplicated inside the same batch.
  • serie + secuencial cannot be duplicated inside the same batch.
  • Billing limit is validated before registration (billing_limit validation error).
  • Request and item structure must match selected tipo:
  • - 01 requires factura - 04 requires nota - 07 requires retencion

    cURL 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

    ParameterTypeRequiredDescripciónValidation
    ----------------------------------------------------
    rucstringRUC de Empresa (13 digits)`requiredstringregex:/^[0-9]{13}$/exists:companies,ruc`
    statusstringFilter by document statusin:GENERATED,SIGNED,RECEIVED,AUTHORIZED,REJECTED,ERROR
    external_idstringFilter by external ID`stringmax:100`
    access_keystringFilter by access key`stringmax:49`
    date_fromstringFilter documents from datedate_format:Y-m-d
    date_tostringFilter documents to datedate_format:Y-m-d
    per_pageintegerResults per page`integermin:1max:100`
    pageintegerPage number`integermin:1`
    include_xmlbooleanInclude XML content in responseboolean

    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

    ParameterTypeRequiredDescripciónValidation
    ----------------------------------------------------
    access_keystring49-digit document access key (URL parameter)`requiredstringsize:49`
    rucstringRUC de Empresa for validation`requiredstringregex:/^[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

    Annulment Reasons

    ParameterTypeRequiredDescripciónValidation
    ----------------------------------------------------
    accessKeystringClave de acceso del documento-
    reasonstringMotivo de anulación`requiredstringin:ERROR_IN_ISSUANCE,OPERATION_NOT_REALIZED,OTHERS`
    justificationstringDescripción adicional`sometimesstringmax:1000`
    CódigoDescripción
    -------------------
    ERROR_IN_ISSUANCEError en los datos del documento
    OPERATION_NOT_REALIZEDLa operación no se concretó
    OTHERSOtro 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ódigoDescripciónResolution
    ------------------------------------
    AUTH_001Invalid credentialsCheck API token
    AUTH_002Account inactiveContact administrator
    COMP_001Company not foundVerify company RUC
    COMP_002Company inactiveActivate company account
    DOC_001Document sequence existsUse next sequential number
    DOC_002Total amount mismatchVerify calculations
    DOC_003Invalid customer typeCheck identification datos
    SRI_001Certificate invalidUpload valid certificate
    SRI_002Document not authorizedWait for authorization
    ANN_001Annulment deadline passedCheck 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 status field 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
    • Error Handling

    • Parse error responses - Use error_code for 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
    • Security

    • 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

    • 📚 Related Documentación

    • 📘 Authentication Guide
    • 🏢 Company Management
    • ✅ Validation Rules
    • 📋 SRI Annulment Rules 2025
    • 📄 Factura Examples
    • 📝 Nota de Crédito Examples
    • 🧾 Retention Examples

    • 🤝 Soporte & Resources

    • API Demo: Interactive Demo
    • Soporte Email: [email protected]
    • Documentación: Main Guide
    • GitHub Issues: Report Issues


    Last updated: January 2025 API Version: 1.0.0 SRI Rules Version: 2025