Installation
composer require greenter/lite
Ensure your Laravel project meets the PHP version requirements (8.0+).
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).
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
}
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());
}
}
}
}
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());
}
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
}
}
Retrieving Comprobantes by ID Fetch a previously generated comprobante:
$comprobante = Greenter::comprobante()->id('12345')->obtener();
API Credentials
.env has correct GREENTER_API_KEY and GREENTER_API_SECRET..env.Validation Errors
if (!$response->exito()) {
Log::error($response->mensaje());
Log::error($response->codigo()); // HTTP status code
}
ruc or serie format.impuesto in detalles).Y-m-d\TH:i:sP (ISO 8601).Rate Limiting
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
}
});
Timeouts
$response = Http::timeout(60)->post('...');
Enable API Logging
Add this to config/greenter.php:
'debug' => env('GREENTER_DEBUG', false),
Logs will appear in storage/logs/greenter.log.
Test with Sandbox Use Greenter’s sandbox environment for testing:
$response = Greenter::comprobante()
->sandbox(true) // Enable sandbox mode
->enviar();
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);
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');
}
}
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
}
});
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);
How can I help you explore Laravel packages today?