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

Lite Laravel Package

greenter/lite

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require greenter/lite
    

    Ensure your Laravel project meets the PHP version requirements (8.0+).

  2. Configuration Publish the config file:

    php artisan vendor:publish --provider="Greenter\Lite\GreenterServiceProvider"
    

    Update .env with your Greenter API credentials (found in the Greenter Dashboard).

  3. First Use Case Generate and send an electronic invoice (comprobante):

    use Greenter\Lite\Facades\Greenter;
    
    $comprobante = Greenter::comprobante()
        ->tipo('01') // Factura
        ->serie('F001')
        ->numero('001')
        ->fecha(new \DateTime())
        ->cliente([
            'ruc' => '1234567890123',
            'nombre' => 'Cliente Ejemplo',
        ])
        ->detalles([
            [
                'codigo' => '001',
                'descripcion' => 'Servicio de desarrollo',
                'cantidad' => 1,
                'precio' => 100.00,
                'impuesto' => 0.16,
            ]
        ])
        ->enviar();
    

    Check the response:

    if ($comprobante->exito()) {
        $url = $comprobante->urlComprobante(); // URL del comprobante firmado
    }
    

Implementation Patterns

Common Workflows

  1. Generating Multiple Comprobantes Use a loop with a service class to batch-process invoices:

    class InvoiceService {
        public function generarComprobantes(array $invoices) {
            foreach ($invoices as $invoice) {
                $comprobante = Greenter::comprobante()
                    ->tipo($invoice['tipo'])
                    ->serie($invoice['serie'])
                    ->numero($invoice['numero'])
                    ->cliente($invoice['cliente'])
                    ->detalles($invoice['detalles'])
                    ->enviar();
    
                if (!$comprobante->exito()) {
                    Log::error("Error en comprobante {$invoice['serie']}-{$invoice['numero']}: " . $comprobante->mensaje());
                }
            }
        }
    }
    
  2. Handling Responses Validate responses with a helper method:

    public function handleResponse($response) {
        if ($response->exito()) {
            return redirect()->route('comprobantes.show', [
                'url' => $response->urlComprobante(),
                'serie' => $response->serie(),
                'numero' => $response->numero()
            ]);
        }
        throw new \RuntimeException($response->mensaje());
    }
    
  3. Integration with Laravel Queues Offload comprobante generation to a queue job:

    use Greenter\Lite\Facades\Greenter;
    
    class SendInvoiceJob implements ShouldQueue {
        protected $invoiceData;
    
        public function __construct(array $invoiceData) {
            $this->invoiceData = $invoiceData;
        }
    
        public function handle() {
            $response = Greenter::comprobante()
                ->tipo($this->invoiceData['tipo'])
                ->serie($this->invoiceData['serie'])
                ->numero($this->invoiceData['numero'])
                ->cliente($this->invoiceData['cliente'])
                ->detalles($this->invoiceData['detalles'])
                ->enviar();
    
            // Store response in DB or notify user
        }
    }
    
  4. Retrieving Comprobantes by ID Fetch a previously generated comprobante:

    $comprobante = Greenter::comprobante()->id('12345')->obtener();
    

Gotchas and Tips

Pitfalls

  1. API Credentials

    • Ensure .env has correct GREENTER_API_KEY and GREENTER_API_SECRET.
    • Never hardcode credentials in the config file; use Laravel's .env.
  2. Validation Errors

    • Greenter’s API returns 4xx/5xx errors with detailed messages. Always check:
      if (!$response->exito()) {
          Log::error($response->mensaje());
          Log::error($response->codigo()); // HTTP status code
      }
      
    • Common issues:
      • Invalid ruc or serie format.
      • Missing required fields (e.g., impuesto in detalles).
      • Date format must be Y-m-d\TH:i:sP (ISO 8601).
  3. Rate Limiting

    • Greenter’s free tier may have request limits. Implement retries with exponential backoff:
      use Illuminate\Support\Facades\Http;
      
      Http::retry(function ($retries) {
          return $retries < 3; // Retry up to 3 times
      }, function ($retries, $response) {
          if ($response->status() === 429) {
              sleep(2 ** $retries); // Exponential delay
          }
      });
      
  4. Timeouts

    • API calls may timeout during peak hours. Increase Laravel’s HTTP timeout:
      $response = Http::timeout(60)->post('...');
      

Debugging Tips

  1. Enable API Logging Add this to config/greenter.php:

    'debug' => env('GREENTER_DEBUG', false),
    

    Logs will appear in storage/logs/greenter.log.

  2. Test with Sandbox Use Greenter’s sandbox environment for testing:

    $response = Greenter::comprobante()
        ->sandbox(true) // Enable sandbox mode
        ->enviar();
    
  3. Validate JSON Payloads Before sending, validate the payload structure:

    $payload = Greenter::comprobante()
        ->tipo('01')
        ->serie('F001')
        ->numero('001')
        ->getPayload(); // Inspect raw JSON
    
    $this->assertArrayHasKey('comprobante', $payload);
    

Extension Points

  1. Custom Comprobante Types Extend the builder for niche use cases (e.g., "Guía de Remisión"):

    namespace App\Services;
    
    use Greenter\Lite\ComprobanteBuilder;
    
    class CustomComprobanteBuilder extends ComprobanteBuilder {
        public function guiaRemision() {
            return $this->tipo('08');
        }
    }
    
  2. Webhook Integration Listen for Greenter’s comprobante status updates (e.g., "validated" or "rejected"):

    Route::post('/greenter/webhook', function (Request $request) {
        $event = $request->input('event');
        $comprobanteId = $request->input('comprobante.id');
    
        // Update your DB or trigger actions
        if ($event === 'validado') {
            // Comprobante approved
        }
    });
    
  3. Local Testing with Mocks Mock the Greenter client for unit tests:

    $mock = Mockery::mock('Greenter\Lite\GreenterClient');
    $mock->shouldReceive('enviarComprobante')
         ->once()
         ->andReturn(['exito' => true, 'url' => 'http://example.com']);
    
    $this->app->instance('Greenter\Lite\GreenterClient', $mock);
    
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.
milito/query-filter
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