Skip to main content

Quick Start Guide

This guide will walk you through creating your first electronic invoice (Factura Afecta) using LibreDTE Core.
This example demonstrates basic usage. In production, you’ll need valid SII certificates, authorized folios, and proper configuration.

Basic Setup

1

Initialize the Application

First, create an instance of the LibreDTE Core application:
<?php

require 'vendor/autoload.php';

use libredte\lib\Core\Application;

// Initialize in development mode
$app = Application::getInstance('dev', true);
2

Access the Billing Package

Get the billing package which contains all document-related functionality:
// Get the billing package service
$billing = $app->getService('libredte.lib.billing');

// Access components
$documentComponent = $billing->getDocumentComponent();
$tradingPartiesComponent = $billing->getTradingPartiesComponent();
$integrationComponent = $billing->getIntegrationComponent();

Create Your First Invoice

Here’s a complete example of creating an electronic invoice:
<?php

require 'vendor/autoload.php';

use libredte\lib\Core\Application;

// Initialize application
$app = Application::getInstance('dev', true);

// Get billing package
$billing = $app->getService('libredte.lib.billing');

// Get components
$tradingParties = $billing->getTradingPartiesComponent();
$documentComponent = $billing->getDocumentComponent();

// Create issuer (Emisor)
$emisorFactory = $tradingParties->getEmisorFactory();
$emisor = $emisorFactory->create([
    'rut' => '76192083-9',
    'razon_social' => 'SASCO SpA',
    'giro' => 'Servicios de Tecnología',
    'actividad_economica' => '620200',
    'direccion' => 'Santa Cruz 123',
    'comuna' => 'Santiago',
]);

// Create recipient (Receptor)
$receptorFactory = $tradingParties->getReceptorFactory();
$receptor = $receptorFactory->create([
    'rut' => '66666666-6',
    'razon_social' => 'Empresa Demo Ltda',
    'giro' => 'Comercio',
    'direccion' => 'Providencia 456',
    'comuna' => 'Providencia',
]);

// Create invoice document
$document = $documentComponent->createDocument([
    'tipo_documento' => 33, // Factura Afecta
    'folio' => 1,
    'fecha_emision' => date('Y-m-d'),
    'emisor' => $emisor,
    'receptor' => $receptor,
    'items' => [
        [
            'nombre' => 'Servicio de Desarrollo',
            'cantidad' => 1,
            'precio' => 100000,
        ],
        [
            'nombre' => 'Servicio de Consultoría',
            'cantidad' => 5,
            'precio' => 50000,
        ],
    ],
]);

echo "Invoice created successfully!\n";
echo "Document Type: Factura Afecta (33)\n";
echo "Folio: {$document->getFolio()}\n";
echo "Total: {$document->getTotal()}\n";

Understanding Document Types

LibreDTE Core supports all Chilean tax document types:

Facturas

  • 33: Factura Afecta (with VAT)
  • 34: Factura Exenta (exempt)
  • 110: Factura de Exportación
  • 46: Factura de Compra

Boletas

  • 39: Boleta Afecta (with VAT)
  • 41: Boleta Exenta

Notas

  • 56: Nota de Débito
  • 61: Nota de Crédito
  • 111: Nota de Crédito Exportación
  • 112: Nota de Débito Exportación

Others

  • 52: Guía de Despacho
  • 43: Liquidación Factura

Working with Components

The Billing Package provides several components for different operations:

Trading Parties Component

Manage issuers and recipients:
// Get the trading parties component
$tradingParties = $billing->getTradingPartiesComponent();

// Create an issuer with authorization
$emisor = $tradingParties->getEmisorFactory()->create([
    'rut' => '76192083-9',
    'razon_social' => 'Mi Empresa',
]);

// Set SII authorization
$autorizacion = $tradingParties->createAutorizacionDte([
    'ambiente' => 'certificacion', // or 'produccion'
    'fecha_autorizacion' => '2024-01-01',
]);
$emisor->setAutorizacionDte($autorizacion);

Document Component

Create, validate, and manage documents:
// Get the document component  
$documentComponent = $billing->getDocumentComponent();

// Validate a document before signing
$validator = $documentComponent->getValidator();
$errors = $validator->validate($document);

if (empty($errors)) {
    echo "Document is valid!\n";
} else {
    foreach ($errors as $error) {
        echo "Error: {$error}\n";
    }
}

// Render document as PDF
$renderer = $documentComponent->getRenderer();
$pdf = $renderer->renderPdf($document);
file_put_contents('factura.pdf', $pdf);

Integration Component

Interact with SII webservices:
// Get the integration component
$integration = $billing->getIntegrationComponent();

// Get SII lazy worker for operations
$siiWorker = $integration->getSiiLazyWorker();

// Authenticate with SII
$authResult = $siiWorker->authenticate($certificate, $ambiente);

// Send document to SII
$sendResult = $siiWorker->sendXmlDocument($documentXml, $ambiente);

// Check document status
$status = $siiWorker->checkXmlDocumentSentStatus(
    $emisorRut,
    $documentType,
    $folio,
    $ambiente
);

Environment Configuration

LibreDTE Core supports multiple environments:
// Development environment with debug
$app = Application::getInstance('dev', true);

// Use SII certification environment
$ambiente = 'certificacion';
Always test your implementation in the SII certification environment (certificacion) before switching to production (produccion).

Complete Workflow

A typical electronic invoicing workflow:
1

Create Document

Build the document with issuer, recipient, and line items
$document = $documentComponent->createDocument($data);
2

Validate

Validate the document before signing
$errors = $validator->validate($document);
3

Sign

Digitally sign the document with your certificate
$signedXml = $signer->sign($document, $certificate);
4

Send to SII

Submit the signed document to SII
$result = $siiWorker->sendXmlDocument($signedXml, $ambiente);
5

Check Status

Verify the document was accepted
$status = $siiWorker->checkXmlDocumentSentStatus(
    $rut, $tipo, $folio, $ambiente
);

Next Steps

Document Types

Learn about all supported document types

SII Integration

Deep dive into SII webservice integration

Digital Signatures

Configure and use digital certificates

API Reference

Explore the complete API documentation

Common Patterns

Instead of using singletons, inject services in your application:
class InvoiceService
{
    public function __construct(
        private Application $app
    ) {}
    
    public function createInvoice(array $data)
    {
        $billing = $this->app->getService('libredte.lib.billing');
        // Create invoice...
    }
}
Always wrap SII operations in try-catch blocks:
use libredte\lib\Core\Package\Billing\Exception\BillingException;

try {
    $result = $siiWorker->sendXmlDocument($xml, $ambiente);
} catch (BillingException $e) {
    error_log("SII Error: " . $e->getMessage());
    // Handle error appropriately
}
Process multiple documents efficiently:
$documents = [];

foreach ($invoices as $invoiceData) {
    $doc = $documentComponent->createDocument($invoiceData);
    $documents[] = $doc;
}

// Process batch
$bookComponent = $billing->getBookComponent();
$book = $bookComponent->createSalesBook($documents);

Build docs developers (and LLMs) love