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

Laravel Greenter Laravel Package

codersfree/laravel-greenter

Paquete para emitir comprobantes electrónicos en Laravel con Greenter: firma digital, envío a SUNAT (SEE o REST), generación de XML firmados, manejo de CDR y representación impresa en HTML/PDF. Soporta emisión para múltiples empresas y envío de XML existente.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require codersfree/laravel-greenter
    

    Publish the config file:

    php artisan vendor:publish --provider="CodersFree\Greenter\GreenterServiceProvider" --tag="greenter-config"
    
  2. Configuration Update .env with your SUNAT credentials:

    GREENTER_CLIENT_ID=your_client_id
    GREENTER_CLIENT_SECRET=your_client_secret
    GREENTER_ENVIRONMENT=sandbox|production
    
  3. First Use Case: Generate a CFDI

    use CodersFree\Greenter\Facades\Greenter;
    
    $invoice = Greenter::invoice()
        ->setType('01') // Factura Electrónica
        ->setSeries('F001')
        ->setNumber('001-2024')
        ->setDate(new \DateTime())
        ->setSeller([
            'ruc' => '12345678901',
            'name' => 'EMPRESA S.A.',
            'address' => 'Av. Ejemplo 123',
        ])
        ->setBuyer([
            'ruc' => '98765432109',
            'name' => 'CLIENTE S.A.',
        ])
        ->addItem([
            'description' => 'Servicio de desarrollo',
            'quantity' => 1,
            'unitPrice' => 100.00,
            'total' => 100.00,
        ])
        ->generate();
    

Implementation Patterns

Common Workflows

  1. Invoice Generation

    • Chain methods for seller/buyer details, items, and metadata.
    • Use generate() to send to SUNAT and return the XML response.
    • Store the response in the database for compliance:
      $invoice = $invoice->generate();
      Invoice::create([
          'xml' => $invoice->getXml(),
          'sunat_response' => $invoice->getSunatResponse(),
      ]);
      
  2. Credit Notes & Debit Notes

    • Reuse the same builder pattern:
      $creditNote = Greenter::creditNote()
          ->setRelatedInvoice('001-2024')
          ->setReason('Devolución parcial')
          ->addItem([...])
          ->generate();
      
  3. Batch Processing

    • Loop through orders and generate invoices in bulk:
      foreach ($orders as $order) {
          $invoice = Greenter::invoice()
              ->setSeries($order->series)
              ->setNumber($order->number)
              ->setBuyer($order->client)
              ->addItems($order->items)
              ->generate();
          // Store or queue for later
      }
      
  4. Webhook Handling

    • Listen for SUNAT callbacks (e.g., validation results):
      Route::post('/greenter/webhook', [GreenterWebhookController::class, 'handle']);
      
    • Validate signatures and update invoice statuses.

Integration Tips

  • Queue Jobs for Async Processing Use Laravel Queues to avoid timeouts during SUNAT API calls:

    InvoiceGenerateJob::dispatch($order)->onQueue('greenter');
    
  • Local Testing with Sandbox Always test in sandbox mode before switching to production.

  • Error Handling Wrap API calls in try-catch blocks to handle SUNAT rejections gracefully:

    try {
        $invoice = Greenter::invoice()->generate();
    } catch (\CodersFree\Greenter\Exceptions\SunatException $e) {
        \Log::error("SUNAT Error: " . $e->getMessage());
        // Retry or notify admin
    }
    

Gotchas and Tips

Pitfalls

  1. RUC Validation

    • SUNAT enforces strict RUC formats (e.g., 11 digits for companies). Validate client input:
      if (!preg_match('/^\d{11}$/', $ruc)) {
          throw new \InvalidArgumentException("RUC inválido");
      }
      
  2. Timeouts

    • SUNAT API may throttle requests. Implement exponential backoff for retries.
  3. XML Schema Compliance

    • Ensure all required fields are present (e.g., emissionDate, totalAmount). Use the package’s validation:
      $invoice->validate(); // Throws if invalid
      
  4. Environment Mismatches

    • Double-check GREENTER_ENVIRONMENT in .env to avoid production errors.

Debugging Tips

  • Enable Debug Mode Set GREENTER_DEBUG=true in .env to log raw API responses.

  • Inspect XML Output Use dd($invoice->getXml()) to verify structure before sending.

  • SUNAT Test Credentials Use the SUNAT sandbox to test RUCs and scenarios.

Extension Points

  1. Custom Templates Override the XML template by publishing and modifying:

    php artisan vendor:publish --tag="greenter-views"
    
  2. Additional Metadata Extend the builder with custom fields:

    $invoice->setCustomField('custom_field', 'value');
    
  3. Webhook Extensions Subclass GreenterWebhookHandler to add custom logic for SUNAT callbacks.

  4. Localization Translate error messages by extending the package’s language files.

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.
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php
trappistes/laravel-custom-fields
splash/sonata-admin
splash/metadata