Skip to main content

Quickstart Guide

This guide will walk you through creating your first electronic invoice with the SUNAT Electronic Invoicing API. You’ll be up and running in about 10 minutes.
This quickstart assumes you have already completed the installation. If not, please complete the installation first.

Prerequisites

Before you begin, make sure you have:
Completed the installation and database migration
Obtained your SUNAT credentials (RUC, SOL user, SOL password)
A valid SUNAT digital certificate (.pem format)
An API client (Postman, Insomnia, or curl)

Step 1: Initialize the System

First, create the initial super admin user. This is a one-time setup that initializes the roles and permissions.
1

Check system status

Verify the API is running and database is connected:
curl http://localhost:8000/api/system/info
Expected response:
{
  "system_initialized": false,
  "user_count": 0,
  "roles_count": 0,
  "app_name": "API Facturación SUNAT - BETA",
  "database_connected": true
}
2

Create super admin user

Initialize the system with your first admin user:
curl -X POST http://localhost:8000/api/auth/initialize \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Admin User",
    "email": "[email protected]",
    "password": "SecurePassword123"
  }'
Password requirements: Minimum 8 characters, mixed case letters, and numbers
Save the access_token from the response - you’ll need it for all subsequent requests.

Step 2: Authenticate

Login to get an access token:
curl -X POST http://localhost:8000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]",
    "password": "SecurePassword123"
  }'
Response:
{
  "message": "Login exitoso",
  "user": {
    "id": 1,
    "name": "Admin User",
    "email": "[email protected]",
    "role": "Super Administrador",
    "permissions": ["*"]
  },
  "access_token": "1|abcdef123456...",
  "token_type": "Bearer"
}
For all subsequent requests, include the token in the Authorization header:
Authorization: Bearer 1|abcdef123456...

Step 3: Create a Company

Register your company with SUNAT credentials:
curl -X POST http://localhost:8000/api/v1/companies \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "ruc": "20123456789",
    "razon_social": "MI EMPRESA S.A.C.",
    "nombre_comercial": "Mi Empresa",
    "direccion": "AV. EJEMPLO 123",
    "ubigeo": "150101",
    "distrito": "LIMA",
    "provincia": "LIMA",
    "departamento": "LIMA",
    "usuario_sol": "MODDATOS",
    "clave_sol": "MODDATOS",
    "modo_produccion": false
  }'
For testing, use SUNAT’s beta credentials:
  • RUC: 20123456789 (or your test RUC)
  • SOL User: MODDATOS
  • SOL Password: MODDATOS
Never use production credentials in the beta environment!
Save the company_id from the response.

Step 4: Create a Branch

Create a branch (sucursal) for your company:
curl -X POST http://localhost:8000/api/v1/branches \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "company_id": 1,
    "codigo": "0001",
    "nombre": "Oficina Principal",
    "direccion": "AV. EJEMPLO 123",
    "ubigeo": "150101",
    "distrito": "LIMA",
    "provincia": "LIMA",
    "departamento": "LIMA"
  }'
Save the branch_id from the response.

Step 5: Create Document Series

Create a correlative series for invoices:
curl -X POST http://localhost:8000/api/v1/branches/1/correlatives \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "tipo_documento": "01",
    "serie": "F001",
    "correlativo_actual": 0,
    "activo": true
  }'
Document types:
  • 01 = Factura (Invoice)
  • 03 = Boleta de Venta (Sales Receipt)
  • 07 = Nota de Crédito (Credit Note)
  • 08 = Nota de Débito (Debit Note)

Step 6: Upload SUNAT Certificate

Place your certificate in the correct location:
# Convert .pfx to .pem if needed
openssl pkcs12 -in certificado.pfx -out certificado.pem -nodes

# Create certificate directory
mkdir -p storage/app/public/certificado

# Copy certificate
cp certificado.pem storage/app/public/certificado/certificado.pem
The certificate password will be requested during the conversion. The output .pem file includes both the private key and certificate in one file.

Step 7: Create Your First Invoice

Now create an invoice and send it to SUNAT:
curl -X POST http://localhost:8000/api/v1/invoices \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "company_id": 1,
    "branch_id": 1,
    "serie": "F001",
    "fecha_emision": "2026-03-05",
    "moneda": "PEN",
    "forma_pago_tipo": "Contado",
    "client": {
      "tipo_documento": "6",
      "numero_documento": "20987654321",
      "razon_social": "CLIENTE EJEMPLO S.A.C.",
      "direccion": "AV. CLIENTE 456"
    },
    "detalles": [
      {
        "codigo": "PROD001",
        "descripcion": "Producto de Ejemplo",
        "unidad": "NIU",
        "cantidad": 10,
        "mto_valor_unitario": 100.00,
        "porcentaje_igv": 18,
        "tip_afe_igv": "10"
      }
    ]
  }'
{
  "success": true,
  "data": {
    "id": 1,
    "company_id": 1,
    "branch_id": 1,
    "serie": "F001",
    "correlativo": "00000001",
    "fecha_emision": "2026-03-05",
    "estado_sunat": "PENDIENTE",
    "valor_venta": 1000.00,
    "mto_igv": 180.00,
    "mto_imp_venta": 1180.00,
    "company": {...},
    "branch": {...},
    "client": {...}
  },
  "message": "Factura creada correctamente"
}

Step 8: Send to SUNAT

Send the created invoice to SUNAT for validation:
curl -X POST http://localhost:8000/api/v1/invoices/1/send-sunat \
  -H "Authorization: Bearer YOUR_TOKEN"
{
  "success": true,
  "data": {
    "id": 1,
    "estado_sunat": "ACEPTADO",
    "hash": "abc123def456...",
    "xml_path": "storage/app/sunat/20123456789-01-F001-00000001.xml",
    "cdr_path": "storage/app/sunat/R-20123456789-01-F001-00000001.zip",
    "mensaje_sunat": "La Factura numero F001-00000001, ha sido aceptada"
  },
  "message": "Factura enviada correctamente a SUNAT"
}
SUNAT Response Codes:
  • ACEPTADO - Document accepted
  • RECHAZADO - Document rejected (check error code)
  • PENDIENTE - Not yet sent to SUNAT

Step 9: Download Files

Once accepted, you can download the generated files:
curl -X GET http://localhost:8000/api/v1/invoices/1/download-xml \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -o factura.xml

Step 10: Generate PDF

Generate a professional PDF with QR code:
curl -X POST http://localhost:8000/api/v1/invoices/1/generate-pdf \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "format": "a4",
    "orientation": "portrait"
  }'
The PDF will include:
  • Company logo and information
  • Client details
  • Itemized products/services
  • Tax calculations (IGV, etc.)
  • QR code for verification
  • Digital hash

Common Issues

Error: Archivo de certificado no encontradoSolution: Ensure your certificate is placed at:
storage/app/public/certificado/certificado.pem
Verify file permissions:
chmod 644 storage/app/public/certificado/certificado.pem
Error: Credenciales incorrectas or Usuario bloqueadoSolution:
  • Verify SOL credentials are correct
  • Ensure you’re using beta credentials for beta environment
  • Check if user is active in database
Error: Various SUNAT error codesSolution: Check the error code in SUNAT documentation:
  • 2335 - RUC not authorized
  • 2324 - Invalid certificate
  • 1033 - Document already exists
Common fixes:
  • Verify RUC matches certificate
  • Check certificate is not expired
  • Ensure document series is unique
Error: Database connection failedSolution:
  • Check .env database credentials
  • Verify MySQL/PostgreSQL is running
  • Test connection: php artisan migrate:status

Next Steps

API Reference

Explore all available endpoints and parameters

Advanced Features

Learn about credit notes, debit notes, and perceptions

Postman Collection

Download ready-to-use Postman examples

Production Deployment

Prepare for production environment

Testing Checklist

Before moving to production:
1

Test in Beta Environment

Create and send multiple test invoices in SUNAT beta
2

Verify All Document Types

Test invoices, receipts, credit notes, and debit notes
3

Test Error Scenarios

Handle rejections and network errors gracefully
4

Validate Generated Files

Ensure XML, PDF, and CDR files are correct
5

Security Audit

Review authentication, permissions, and data encryption
Production Checklist:
  • Switch to production endpoints in .env
  • Update SOL credentials to production
  • Install valid production certificate
  • Set APP_ENV=production and APP_DEBUG=false
  • Enable SSL/HTTPS
  • Configure database backups
  • Set up monitoring and logging

Build docs developers (and LLMs) love