Skip to main content

Installation Guide

This guide covers the complete installation and configuration of the SUNAT Electronic Invoicing API on your server.

System Requirements

Minimum Requirements

PHP

Version 8.2 or higher with required extensions

Database

MySQL 8.0+ or PostgreSQL 12+

Composer

Latest stable version for dependency management

Web Server

Apache 2.4+ or Nginx 1.18+ (optional for production)

Required PHP Extensions

Verify these extensions are installed and enabled:
php -m | grep -E 'openssl|pdo|mbstring|tokenizer|xml|ctype|json|bcmath|curl|fileinfo|zip'
Required extensions:
  • openssl - For certificate handling
  • pdo_mysql or pdo_pgsql - Database connectivity
  • mbstring - Multibyte string handling
  • tokenizer - Laravel requirement
  • xml - XML processing
  • ctype - Character type checking
  • json - JSON handling
  • bcmath - Arbitrary precision mathematics
  • curl - HTTP requests to SUNAT
  • fileinfo - File type detection
  • zip - Handling CDR zip files
If any extensions are missing, install them before proceeding:
# Ubuntu/Debian
sudo apt-get install php8.2-{cli,fpm,mysql,xml,mbstring,curl,zip,bcmath}

# CentOS/RHEL
sudo yum install php82-{cli,fpm,mysqlnd,xml,mbstring,curl,zip,bcmath}

Step 1: Clone the Repository

Clone the project from GitHub:
git clone https://github.com/yorchavez9/Api-de-facturacion-electronica-sunat-Peru.git
cd Api-de-facturacion-electronica-sunat-Peru
Alternatively, download the ZIP file and extract it to your preferred location.

Step 2: Install Dependencies

Install all required PHP packages using Composer:
composer install
This will install:
PackageVersionPurpose
laravel/framework^12.0Core framework
greenter/lite^5.1SUNAT integration
greenter/consulta-cpe*CPE query service
dompdf/dompdf^3.1PDF generation
endroid/qr-code*QR code creation
laravel/sanctum^4.0API authentication
Installation time: Composer installation typically takes 2-5 minutes depending on your internet connection.

Step 3: Environment Configuration

Create your environment configuration file:
cp .env.example .env

Generate Application Key

php artisan key:generate
This generates a secure encryption key for Laravel.

Configure Environment Variables

Edit the .env file with your settings:
# Application Configuration
APP_NAME="API Facturación SUNAT - BETA"
APP_ENV=local
APP_KEY=base64:YOUR_GENERATED_KEY
APP_DEBUG=true
APP_URL=http://localhost:8000

# Locale Configuration
APP_LOCALE=es
APP_FALLBACK_LOCALE=es
APP_FAKER_LOCALE=es_PE

Step 4: Database Setup

Create Database

CREATE DATABASE db_api_sunat CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- Create dedicated user (recommended)
CREATE USER 'sunat_user'@'localhost' IDENTIFIED BY 'secure_password';
GRANT ALL PRIVILEGES ON db_api_sunat.* TO 'sunat_user'@'localhost';
FLUSH PRIVILEGES;

Run Migrations

Execute database migrations to create all required tables:
php artisan migrate
This creates the following tables:
  • users - System users and authentication
  • roles - User roles (super_admin, admin, user)
  • permissions - Granular permissions
  • role_permission - Role-permission mapping
  • personal_access_tokens - API tokens (Sanctum)
  • companies - Issuing companies
  • company_configurations - Per-company settings
  • branches - Branch offices
  • clients - Customers and suppliers
  • correlatives - Document series and numbering
  • invoices - Electronic invoices (Facturas)
  • boletas - Sales receipts
  • credit_notes - Credit notes (future)
  • debit_notes - Debit notes (future)
  • ubi_regiones - Peru regions
  • ubi_provincias - Provinces
  • ubi_distritos - Districts
  • jobs - Queue jobs
  • cache - Application cache
  • sessions - User sessions
Expected output: All migrations should run successfully with no errors

Step 5: Certificate Setup

Understanding SUNAT Certificates

SUNAT requires a digital certificate to sign electronic documents. You’ll receive a .pfx file from your certificate provider.

Convert Certificate to PEM Format

The API uses .pem format certificates. Convert your .pfx file:
# Convert .pfx to .pem (includes both private key and certificate)
openssl pkcs12 -in certificado.pfx -out certificado.pem -nodes
You’ll be prompted for the certificate password. This is the password provided by your certificate authority, not your SOL password.
What this command does:
  • -in certificado.pfx - Input file
  • -out certificado.pem - Output file
  • -nodes - Don’t encrypt the private key

Place Certificate in Correct Location

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

# Copy certificate (maintain strict permissions)
cp certificado.pem storage/app/public/certificado/certificado.pem
chmod 644 storage/app/public/certificado/certificado.pem
For testing: SUNAT provides test certificates for the beta environment. Contact SUNAT or use the credentials from their documentation.

Verify Certificate

Validate your certificate is correctly formatted:
# View certificate details
openssl x509 -in storage/app/public/certificado/certificado.pem -text -noout

# Check private key
openssl rsa -in storage/app/public/certificado/certificado.pem -check
Expected components in the .pem file:
-----BEGIN PRIVATE KEY-----
[Base64 encoded private key]
-----END PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
[Base64 encoded certificate]
-----END CERTIFICATE-----

Step 6: Storage Permissions

Set correct permissions for Laravel storage and cache:
# Set storage permissions
chmod -R 775 storage bootstrap/cache

# Set ownership (if running as www-data)
sudo chown -R www-data:www-data storage bootstrap/cache

# Create SUNAT files directory
mkdir -p storage/app/sunat
chmod -R 775 storage/app/sunat

# Create Greenter cache directory
mkdir -p storage/app/greenter/cache
chmod -R 775 storage/app/greenter/cache
Security Note: Never set permissions to 777. Use 775 for directories and 664 for files, with appropriate ownership.

Step 7: Test the Installation

Start Development Server

php artisan serve
The server will start at http://localhost:8000

Verify API is Running

Test the system info endpoint:
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",
  "app_env": "local",
  "app_debug": true,
  "database_connected": true
}
If database_connected: true, your installation is successful!

Step 8: Optional - Seed Sample Data

Load sample ubigeo (geographic) data:
php artisan db:seed --class=UbigeoSeeder
This populates Peru’s regions, provinces, and districts for address validation.

Production Deployment

Optimization Commands

Before deploying to production:
# Optimize configuration loading
php artisan config:cache

# Optimize route loading
php artisan route:cache

# Optimize view compilation
php artisan view:cache

# Optimize autoloader
composer install --optimize-autoloader --no-dev

Production Environment

Update .env for production:
APP_ENV=production
APP_DEBUG=false
APP_URL=https://yourdomain.com

# Use production SUNAT endpoints
SUNAT_ENVIRONMENT=production

Web Server Configuration

server {
    listen 80;
    server_name yourdomain.com;
    root /var/www/api-sunat/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    index index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

SSL/HTTPS Setup

For production, always use HTTPS:
# Using Certbot (Let's Encrypt)
sudo apt-get install certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com

Queue Configuration (Optional)

For better performance, configure queues:
# Update .env
QUEUE_CONNECTION=database

# Run migrations for jobs table (already included)
php artisan migrate

# Start queue worker
php artisan queue:work --tries=3 --timeout=90
For production, use Supervisor:
[program:sunat-queue]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/api-sunat/artisan queue:work database --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=2
redirect_stderr=true
stdout_logfile=/var/www/api-sunat/storage/logs/worker.log
stopwaitsecs=3600

Troubleshooting

Symptoms: White page or 500 errorSolutions:
  1. Check storage permissions: chmod -R 775 storage
  2. Clear cached config: php artisan config:clear
  3. Check Laravel logs: tail -f storage/logs/laravel.log
  4. Verify .env file exists and APP_KEY is set
Symptoms: SQLSTATE[HY000] [2002] Connection refusedSolutions:
  1. Verify database is running: systemctl status mysql
  2. Check credentials in .env
  3. Test connection: php artisan migrate:status
  4. Verify database exists: SHOW DATABASES;
Symptoms: Archivo de certificado no encontradoSolutions:
  1. Verify path: ls -l storage/app/public/certificado/
  2. Check file exists: certificado.pem
  3. Verify permissions: chmod 644 certificado.pem
  4. Check certificate format with openssl
Symptoms: Fatal error: Allowed memory size exhaustedSolutions:
  1. Increase PHP memory: php -d memory_limit=-1 /usr/bin/composer install
  2. Or update php.ini: memory_limit = 512M
Symptoms: Cannot write to storage/logsSolutions:
# Fix ownership
sudo chown -R $USER:www-data storage bootstrap/cache

# Fix permissions
chmod -R 775 storage bootstrap/cache

# Set default ACL (if available)
setfacl -R -m u:www-data:rwX storage bootstrap/cache
setfacl -dR -m u:www-data:rwX storage bootstrap/cache

Verification Checklist

Before proceeding to create invoices:
1

Database Connected

system/info endpoint returns database_connected: true
2

Migrations Complete

✓ All tables created: php artisan migrate:status
3

Certificate Installed

✓ Certificate exists at storage/app/public/certificado/certificado.pem
4

Storage Writable

✓ Storage directories have correct permissions
5

Environment Configured

.env file has all required settings

Next Steps

Now that installation is complete:

Quickstart Guide

Create your first invoice in 10 minutes

API Reference

Explore all available endpoints

Authentication

Learn about API authentication

Configuration

Advanced configuration options

Getting Help

If you encounter issues during installation:

Build docs developers (and LLMs) love