PHP code example of codersfree / laravel-greenter

1. Go to this page and download the library: Download codersfree/laravel-greenter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

codersfree / laravel-greenter example snippets


'company' => [
    'ruc' => '20000000001',
    'razonSocial' => 'GREEN SAC',
    'nombreComercial' => 'GREEN',
    'address' => [
        'ubigeo' => '150101',
        'departamento' => 'LIMA',
        'provincia' => 'LIMA',
        'distrito' => 'LIMA',
        'direccion' => 'Av. Villa Nueva 221',
    ],
]

'mode' => 'prod',

'company' => [
    'certificate' => public_path('certs/certificate.pem'),
    'clave_sol' => [
        'user' => 'USUARIO_SOL',
        'password' => 'CLAVE_SOL',
    ],
    'credentials' => [
        'client_id' => '...',
        'client_secret' => '...',
    ],
],

$data = [
    "ublVersion" => "2.1",
    "tipoOperacion" => "0101", // Catálogo 51
    "tipoDoc" => "01", // Catálogo 01
    "serie" => "F001",
    "correlativo" => "1",
    "fechaEmision" => now(),
    "formaPago" => [
        'tipo' => 'Contado',
    ],
    "tipoMoneda" => "PEN", // Catálogo 02
    "client" => [
        "tipoDoc" => "6", // Catálogo 06
        "numDoc" => "20000000001",
        "rznSocial" => "EMPRESA X",
    ],
    "mtoOperGravadas" => 100.00,
    "mtoIGV" => 18.00,
    "totalImpuestos" => 18.00,
    "valorVenta" => 100.00,
    "subTotal" => 118.00,
    "mtoImpVenta" => 118.00,
    "details" => [
        [
            "codProducto" => "P001",
            "unidad" => "NIU", // Catálogo 03
            "cantidad" => 2,
            "mtoValorUnitario" => 50.00,
            "descripcion" => "PRODUCTO 1",
            "mtoBaseIgv" => 100,
            "porcentajeIgv" => 18.00,
            "igv" => 18.00,
            "tipAfeIgv" => "10",
            "totalImpuestos" => 18.00,
            "mtoValorVenta" => 100.00,
            "mtoPrecioUnitario" => 59.00,
        ],
    ],
    "legends" => [
        [
            "code" => "1000", // Catálogo 15
            "value" => "SON CIENTO DIECIOCHO CON 00/100 SOLES",
        ],
    ],
];

use CodersFree\LaravelGreenter\Facades\Greenter;
use Illuminate\Support\Facades\Storage;

// Enviar a SUNAT
$response = Greenter::send('invoice', $data); //invoice, note, despatch, etc

// Guardar XML
$xml = $response->getXml();
if($xml)
{
    Storage::put("sunat/xml/{$name}.xml", $response->getXml());
}

//Guardamos CDR
if($response->getSunatResponse()->getSuccess())
{
    $cdrZip = $response->getSunatResponse()->getCdrZip();
    Storage::put("sunat/cdr/R-{$name}.zip", $cdrZip);
}

namespace CodersFree\LaravelGreenter\DTOs;

use Greenter\Model\DocumentInterface;

class SendResultDTO
{
    public function __construct(
        private ?DocumentInterface $document = null,
        private ?string $xml = null,
        private ?string $hash = null,
        private ?SunatResponseDto $sunatResponse = null,
    ) {
    }
}



namespace CodersFree\LaravelGreenter\DTOs;

class SunatResponseDto
{
    public function __construct(
        private ?bool $success = null,
        private ?ErrorDto $error = null,
        private ?string $cdrZip = null,
        private ?CdrResponseDto $cdrResponse = null,
    ) {
    }    
}



namespace CodersFree\LaravelGreenter\DTOs;

class ErrorDto
{
    public function __construct(
        private ?string $code = null,
        private ?string $message = null,
    ) {
    }
}



namespace CodersFree\LaravelGreenter\DTOs;

class CdrResponseDto
{
    /**
     * @param string[]|null $notes
     */
    public function __construct(
        private ?bool $accepted = null,
        private ?string $id = null,
        private ?string $code = null,
        private ?string $description = null,
        private ?array $notes = null,
    ) {}
}

// --- SendResultDTO ---
$response->getXml();           // string: XML firmado
$response->getHash();          // string: Hash del XML
$response->getDocument();      // DocumentInterface: Objeto del documento (Invoice, Note, etc)
$sunatResponse = $response->getSunatResponse(); // SunatResponseDto

// --- SunatResponseDto ---
$sunatResponse->getSuccess();          // bool: Indica si hubo respuesta de SUNAT (true incluso si fue rechazada con CDR)
$sunatResponse->getCdrZip();           // string|null: Contenido del ZIP del CDR (binario)
$sunatResponse->getError();            // ErrorDto|null: Objeto de error si falló la conexión/validación
$cdrResponse = $sunatResponse->getCdrResponse(); // CdrResponseDto|null: Objeto con datos del CDR

// --- CdrResponseDto ---
if ($cdrResponse) {
    $cdrResponse->getAccepted();        // bool: true si el estado es aceptado
    $cdrResponse->getCode();           // string: '0' = Aceptado
    $cdrResponse->getDescription();    // string: Mensaje de respuesta de SUNAT
    $cdrResponse->getNotes();          // array: Observaciones
}

// --- ErrorDto ---
$error = $sunat->getError();
if ($error) {
    $error->getCode();         // string: Código de error
    $error->getMessage();      // string: Descripción del error
}

return response()->json($response->toArray());

// Configuración dinámica
config([
    // Cambiar empresa emisora
    'greenter.company.ruc' => '20999999999',
    'greenter.company.razonSocial' => 'OTRA EMPRESA SAC',
    'greenter.company.clave_sol.user' => 'MODDATOS',
    'greenter.company.clave_sol.password' => 'MODDATOS',
    'greenter.company.certificate' => storage_path('certs/otro_cert.pem'),

    // Personalizar reporte
    'greenter.report.system.logo' => public_path('images/otro_logo.png'),
    'greenter.report.user.header' => 'Teléfono: 999-999-999',
]);

// Ahora emite el comprobante con la nueva configuración
$result = Greenter::send('invoice', $data);

use CodersFree\LaravelGreenter\Facades\GreenterXml;

$xmlSigned = GreenterXml::generateXml('invoice', $data); // Retorna string

// Retorna el mismo SendResultDTO explicado arriba
$result = Greenter::sendXml('invoice', $xmlSigned);

use CodersFree\LaravelGreenter\Facades\GreenterReport;

$result = Greenter::send('invoice', $data);
$document = $result->getDocument();

if($document)
{
    $html = GreenterReport::generateHtml($document);
}

'report' => [
    'bin_path' => '/usr/local/bin/wkhtmltopdf',
],

use CodersFree\LaravelGreenter\Facades\GreenterReport;

$result = Greenter::send('invoice', $data);
$document = $result->getDocument();

if($document)
{
    $name = $document->getName();

    // Generar PDF
    $pdf = GreenterReport::generatePdf($document);
    Storage::put("sunat/pdf/{$name}.pdf", $pdf);
}

use CodersFree\LaravelGreenter\Builders\InvoiceBuilder;
use CodersFree\LaravelGreenter\Facades\GreenterReport;

$data = [ ... ]; // Tus datos

// 1. Construir el documento manualmente
// Usa InvoiceBuilder, NoteBuilder, DespatchBuilder, etc. según corresponda
$document = (new InvoiceBuilder())->build($data);
$name = $document->getName();

// 2. Generar el reporte
$pdf = GreenterReport::generatePdf($document);
Storage::put("sunat/pdf/{$name}.pdf", $pdf);

'report' => [
    'template' => resource_path('templates/laravel-greenter'),
],
bash
php artisan vendor:publish --tag=greenter-laravel
bash
php artisan vendor:publish --tag=greenter-templates