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

Ws Laravel Package

greenter/ws

Cliente PHP para conectar con los Web Services de SUNAT y enviar comprobantes electrónicos. Parte del ecosistema Greenter, con documentación oficial y soporte vía issues/pull requests en el repositorio principal.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require greenter/ws
    

    Ensure your Laravel project meets the package’s PHP version requirements (tested on PHP 7.2+).

  2. Configuration Publish the config file:

    php artisan vendor:publish --provider="Greenter\Ws\WsServiceProvider"
    

    Update .env with your SUNAT credentials (e.g., SUNAT_USERNAME, SUNAT_PASSWORD, SUNAT_RUC).

  3. First Use Case: Sending a Test Invoice Use the WsClient facade to send a test invoice via SUNAT’s sandbox:

    use Greenter\Ws\Facades\WsClient;
    
    $response = WsClient::sendTestInvoice([
        'ruc' => '12345678901',
        'serie' => 'F001',
        'numero' => '001-2023',
        'fecha' => now()->format('Y-m-d'),
        'monto' => 100.00,
        'tipo' => '01', // Factura Electrónica
    ]);
    
    dd($response->success(), $response->message());
    

Where to Look First

  • Official Documentation for API reference and SUNAT-specific requirements.
  • config/ws.php for default settings (e.g., sandbox/production endpoints, timeout values).
  • Greenter\Ws\Contracts\WsResponse for response handling patterns.

Implementation Patterns

Core Workflows

  1. Sending Comprobantes (Invoices, Credit Notes, etc.) Use the WsClient facade to dispatch requests to SUNAT’s API:

    $response = WsClient::sendInvoice($comprobanteData, [
        'test' => env('SUNAT_SANDBOX', false), // Use sandbox
        'timeout' => 30,
    ]);
    
    • Data Structure: Follow SUNAT’s XML schema (see SUNAT’s technical guide).
    • Validation: The package validates basic fields (e.g., ruc, serie, numero), but ensure your data matches SUNAT’s requirements.
  2. Consulting Status Check the status of a sent comprobante:

    $status = WsClient::consultStatus('12345678901', 'F001', '001-2023');
    
  3. Handling Responses Always check the response object:

    if ($response->success()) {
        // Process successful response (e.g., save to DB)
        $this->saveComprobante($response->data());
    } else {
        $this->handleError($response->message(), $response->code());
    }
    

Integration Tips

  • Laravel Queues: Offload SUNAT requests to a queue (e.g., SendComprobanteJob) to avoid timeouts:
    SendComprobanteJob::dispatch($comprobanteData)->onQueue('sunat');
    
  • Logging: Log all SUNAT interactions for debugging:
    \Log::info('SUNAT Response', ['data' => $response->toArray()]);
    
  • Events: Trigger custom events (e.g., ComprobanteSent) after successful API calls:
    event(new ComprobanteSent($response->data()));
    

Advanced Patterns

  • Custom XML Generation: Extend Greenter\Ws\XmlBuilder to customize XML payloads:
    class CustomXmlBuilder extends \Greenter\Ws\XmlBuilder {
        public function buildCustomTag() { ... }
    }
    
  • Retry Logic: Implement exponential backoff for failed requests using Laravel’s Retryable interface.

Gotchas and Tips

Pitfalls

  1. Deprecated Package

    • Last release: 2019-07-10. Verify SUNAT’s API compatibility (e.g., SUNAT’s latest specs).
    • Mitigation: Fork the repo or use a maintained alternative like lempa/sunat.
  2. Sandbox vs. Production

    • Always test in SUNAT’s sandbox (test: true) before going live.
    • Error: Forgetting to switch environments may cause production failures.
  3. XML Schema Validation

    • SUNAT rejects malformed XML. Use tools like XMLLint to validate payloads before sending.
    • Tip: Enable Laravel’s debugbar to inspect XML structure:
      \Debugbar::info('XML Payload', $this->xmlBuilder->render());
      
  4. Rate Limiting

    • SUNAT may throttle requests. Implement delays between calls:
      sleep(2); // Add delay between API calls
      
  5. Certificate Issues

    • SUNAT requires valid SSL certificates. If you encounter SSL errors:
      // Temporarily disable SSL verification (not recommended for production)
      $client = new \Greenter\Ws\WsClient(['verify' => false]);
      

Debugging Tips

  • Enable Verbose Logging:
    config(['ws.log.enabled' => true]);
    
  • Check SUNAT’s Test Environment:
  • Inspect Raw Responses:
    \Log::debug('Raw Response', $response->rawContent());
    

Extension Points

  1. Custom Response Handlers Override Greenter\Ws\Handlers\ResponseHandler to add business logic:

    class CustomResponseHandler extends \Greenter\Ws\Handlers\ResponseHandler {
        public function handle($response) {
            if ($response->code() === '01') {
                // Custom logic for SUNAT code 01
            }
        }
    }
    
  2. Add New Comprobante Types Extend the WsClient to support additional SUNAT comprobantes (e.g., Guías de Remisión):

    public function sendGuiaRemision(array $data) {
        return $this->send('guia_remision', $data);
    }
    
  3. Mock SUNAT for Testing Use Laravel’s Mockery to simulate SUNAT responses in unit tests:

    $mock = Mockery::mock('Greenter\Ws\Contracts\WsClient');
    $mock->shouldReceive('sendInvoice')->andReturn(new WsResponse(true, 'OK'));
    
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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky