Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Xml Laravel Package

greenter/xml

Genera XML UBL 2.0/2.1 para comprobantes electrónicos con Greenter. Ideal para facturas, boletas y otros documentos en formato estándar, listo para integrarse con tus flujos de emisión electrónica. Documentación y soporte en greenter.dev.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require greenter/xml
    

    Ensure your Laravel project has PHP 7.2+ and ext-dom enabled.

  2. First Use Case: Generating a Basic Invoice

    use Greenter\Xml\FacturaElectronica\Factura;
    use Greenter\Xml\FacturaElectronica\Items\Item;
    
    $factura = new Factura();
    $factura->setTipoOperacion('01'); // 01: Venta interna
    $factura->setSerie('F001');
    $factura->setNumero('001-2023');
    $factura->setFechaEmision(new \DateTime('now'));
    $factura->setMoneda('PEN');
    $factura->setTipoMoneda('01'); // 01: Soles
    $factura->setTotal(100.00);
    
    $item = new Item();
    $item->setDescripcion('Producto de prueba');
    $item->setCantidad(1);
    $item->setUnidadMedida('NIU'); // Unidades
    $item->setPrecioUnitario(100.00);
    $factura->addItem($item);
    
    // Generate XML
    $xml = $factura->generate();
    file_put_contents('factura.xml', $xml);
    
  3. Where to Look First

    • Official Documentation for SUNAT-specific rules (e.g., validation, signatures).
    • src/Greenter/Xml/FacturaElectronica/ for core classes (e.g., Factura, Boleta, NotaCredito).
    • src/Greenter/Xml/Common/ for reusable components like Direccion, Emisor, Receptor.

Implementation Patterns

Workflows

  1. Document Generation Pipeline

    // 1. Create document base
    $factura = new Factura();
    $factura->setEmisor(new Emisor('12345678901', 'EMPRESA S.A.', 'Lima'));
    
    // 2. Add metadata
    $factura->setReceptor(new Receptor('98765432109', 'CLIENTE S.A.', 'Lima'));
    $factura->setItems([$item1, $item2]);
    
    // 3. Validate (SUNAT rules)
    if ($factura->validate()) {
        $xml = $factura->generate();
        $factura->sign($privateKey, $certificate); // Optional: Sign XML
        Storage::put('comprobantes/' . $factura->getNumero() . '.xml', $xml);
    }
    
  2. Integration with SUNAT API

    // After generating XML, send to SUNAT for validation/approval
    $response = Http::post('https://e-factura.sunat.gob.pe/ol-sunat/...', [
        'file' => new \Illuminate\Http\File('factura.xml'),
        'ruc' => '12345678901',
    ]);
    
  3. Batch Processing

    // Generate multiple documents in a loop
    foreach ($invoices as $invoice) {
        $factura = new Factura($invoice);
        $xml = $factura->generate();
        // Queue for SUNAT submission or storage
    }
    

Laravel-Specific Patterns

  • Service Provider Binding

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->bind(Factura::class, function ($app) {
            return new Factura(config('sunat.ruc'), config('sunat.razon_social'));
        });
    }
    
  • Form Request Validation

    // app/Http/Requests/GenerateInvoiceRequest.php
    public function rules()
    {
        return [
            'items.*.descripcion' => 'required|string|max:255',
            'items.*.cantidad' => 'required|numeric|min:0',
            // SUNAT-specific rules
            'tipo_operacion' => 'required|in:01,02,03,04,05,06,07,08',
        ];
    }
    
  • Queued Jobs for SUNAT Submission

    // app/Jobs/SendToSunat.php
    public function handle()
    {
        $xml = $this->factura->generate();
        Http::post('https://e-factura.sunat.gob.pe/...', [
            'file' => new File($xml),
        ]);
    }
    

Gotchas and Tips

Pitfalls

  1. SUNAT Schema Validation

    • The package generates valid UBL XML, but SUNAT’s API may reject documents due to:
      • Missing mandatory fields (e.g., Ubigeo in Direccion).
      • Incorrect data types (e.g., FechaEmision must be YYYY-MM-DD).
      • Currency/moneda mismatches (e.g., Moneda="USD" with TipoMoneda="01").
    • Fix: Use $factura->validate() and check SUNAT’s technical guide.
  2. XML Signature Requirements

    • SUNAT requires XML signatures for some document types (e.g., FacturaElectronica).
    • Gotcha: The package supports signing via Factura::sign(), but you must:
      • Provide a valid PFX/PKCS12 certificate (issued by SUNAT-approved CA).
      • Ensure the certificate’s RUC matches the emitter’s RUC.
    • Tip: Use openssl pkcs12 -info -in cert.p12 to verify the certificate.
  3. DateTime Formatting

    • SUNAT expects dates in YYYY-MM-DD format. Laravel’s Carbon may output Y-m-d H:i:s.
    • Fix: Explicitly cast to string:
      $factura->setFechaEmision((new \DateTime())->format('Y-m-d'));
      
  4. Character Encoding

    • SUNAT’s API rejects XML with incorrect encoding (must be UTF-8).
    • Tip: Add this to your generate() call:
      $dom = new \DOMDocument('1.0', 'UTF-8');
      $dom->loadXML($xml);
      $xml = $dom->saveXML();
      
  5. Ubigeo Validation

    • Peru’s Ubigeo (geographic code) must be 9 digits (e.g., 150101 for Lima).
    • Tip: Validate with a regex:
      if (!preg_match('/^\d{9}$/', $ubigeo)) {
          throw new \InvalidArgumentException('Ubigeo inválido');
      }
      

Debugging Tips

  1. Validate XML Against SUNAT Schema

    $schema = new \DOMDocument();
    $schema->load('https://e-factura.sunat.gob.pe/ubr/ schemas/ sunat/pe/niub/2.0/niub.xsd');
    $validator = new \DOMDocument();
    $validator->loadXML($xml);
    $errors = $validator->schemaValidate($schema);
    if (!$errors) {
        // Valid
    }
    
  2. Log Generated XML for Manual Review

    \Log::debug('Generated XML:', [
        'content' => $xml,
        'length' => strlen($xml),
    ]);
    
  3. Common Errors and Fixes

    Error Cause Solution
    Invalid RUC RUC not 11 digits or invalid Use 12345678901 (valid format)
    FechaEmision out of range Date outside allowed period Ensure date is within SUNAT’s valid range
    Signature failed Invalid certificate/key Regenerate PFX from SUNAT portal
    Total mismatch Sum of items ≠ Total Recalculate Total manually

Extension Points

  1. Custom Document Types

    • Extend Greenter\Xml\BaseDocument to support non-SUNAT XML:
      class CustomDocument extends BaseDocument {
          public function generate(): string {
              $this->setRoot('CustomRoot');
              return parent::generate();
          }
      }
      
  2. Dynamic Item Validation

    • Override validateItem() in your document class to add business rules:
      protected function validateItem(Item $item): bool {
          if ($item->getPrecioUnitario() > 10000) {
              throw new \RuntimeException('Precio
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui