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

Xmldsig Laravel Package

greenter/xmldsig

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Purpose Alignment: The package is highly specialized for SUNAT (Peruvian tax authority) electronic invoicing compliance, leveraging XML-DSig (XML Digital Signatures) standards. This makes it a perfect fit for Laravel-based applications handling Peruvian e-invoicing (Factura Electrónica) or related fiscal documents.
  • Laravel Integration: The package is PHP-native and Composer-compatible, ensuring seamless integration with Laravel’s dependency management. No major architectural conflicts expected.
  • XML Processing: The package abstracts complex XML signature generation, reducing boilerplate for developers while enforcing SUNAT’s strict validation rules.

Integration Feasibility

  • Low Coupling: The package operates on raw XML strings/files, making it agnostic to Laravel’s ORM/routing layers. Can be used in:
    • API responses (e.g., generating signed invoices for clients).
    • Background jobs (e.g., signing invoices post-creation).
    • Middleware (e.g., validating/signing requests/responses).
  • Dependency Risks: Relies on XMLSecLibs (a PHP XML security library), which may introduce versioning constraints if not actively maintained. Check for Laravel-specific conflicts (e.g., PHP version compatibility).

Technical Risk

  • Certification Handling:
    • PFX → PEM conversion is mandatory (documented in CONVERT.md). Risk of misconfiguration if developers overlook this step.
    • Private key exposure: Storing .pem files securely (e.g., Laravel’s storage/ or encrypted secrets) is critical.
  • XML Schema Validation:
    • SUNAT’s schema evolves; the package may lag behind updates (last release: 2020). Risk of compliance failures if SUNAT changes requirements.
    • No built-in schema validation—developers must ensure input XML conforms to SUNAT’s standards.
  • Performance:
    • XML signing is CPU-intensive. Test with large payloads (e.g., invoices with 100+ line items) to avoid timeouts.
    • No async/queue-optimized methods; may need Laravel Queues for batch processing.

Key Questions

  1. Compliance:
    • Does SUNAT’s current schema match the package’s capabilities? (Audit against SUNAT’s latest specs).
    • Are there additional SUNAT-specific validations (e.g., hash algorithms, timestamping) not covered by this package?
  2. Security:
    • How will .pem files be stored? (Avoid hardcoding; use Laravel’s config/ or encrypted env variables.)
    • Is key rotation supported? (Manual process required.)
  3. Maintenance:
    • Who will handle updates if SUNAT changes requirements? (Package is unmaintained post-2020.)
    • Are there alternatives (e.g., PHP-XMLSecurity) with active support?
  4. Error Handling:
    • How will signature failures (e.g., invalid XML, expired certs) be logged/retried? (Package lacks built-in retry logic.)
  5. Testing:
    • Are there mock SUNAT validators for unit testing? (May need custom assertions.)

Integration Approach

Stack Fit

  • Laravel Compatibility:
    • PHP 7.4+: Verify compatibility with Laravel’s supported PHP versions (current: 8.0+).
    • No Framework Lock-in: Pure PHP class; integrates with Laravel’s Service Container, Events, or Console Commands.
  • Recommended Use Cases:
    1. Invoice Generation Service:
      • Use in a Laravel Command (php artisan invoice:sign) or API endpoint (/api/invoices/{id}/sign).
      • Example:
        use Greenter\XMLSecLibs\Sunat\SignedXml;
        use Illuminate\Support\Facades\Storage;
        
        class SignInvoiceCommand extends Command {
            protected $signature = 'invoice:sign {invoiceId}';
            public function handle() {
                $xml = Invoice::find($invoiceId)->toXml();
                $pem = Storage::disk('certs')->get('invoice.pem');
                $signer = new SignedXml();
                $signer->setCertificate($pem);
                $signedXml = $signer->signXml($xml);
                Storage::put("public/invoices/signed_{$invoiceId}.xml", $signedXml);
            }
        }
        
    2. Middleware for Signed Responses:
      • Sign XML responses before sending to SUNAT’s API.
      • Example:
        public function handle($request, Closure $next) {
            $response = $next($request);
            if ($response->isXml()) {
                $signed = (new SignedXml())->signXml($response->getContent());
                $response->setContent($signed);
            }
            return $response;
        }
        
    3. Event Listeners:
      • Trigger signing after InvoiceCreated event.
      • Example:
        public function handle(InvoiceCreated $event) {
            $signer = new SignedXml();
            $signer->setCertificate(config('sunat.certificate.pem'));
            $event->invoice->xml = $signer->signXml($event->invoice->toXml());
            $event->invoice->save();
        }
        

Migration Path

  1. Phase 1: Proof of Concept (PoC)
  2. Phase 2: Integration
    • Step 1: Add to composer.json:
      "require": {
          "greenter/xmldsig": "^1.0"
      }
      
    • Step 2: Implement certificate management (e.g., encrypted storage, rotation workflow).
    • Step 3: Build a wrapper service to abstract signing logic (e.g., app/Services/SunatSigner.php).
  3. Phase 3: Compliance Testing
    • Test against SUNAT’s sandbox environment before production.
    • Automate signature validation in CI (e.g., GitHub Actions).

Compatibility

  • XML Libraries: No conflicts with Laravel’s DOMDocument or SimpleXML (used internally by the package).
  • PHP Extensions: Requires OpenSSL (for PEM handling) and LibXML (for XML processing)—both enabled by default in Laravel.
  • Laravel Features:
    • Filesystem: Use Laravel’s Storage facade for .pem files.
    • Queues: Offload signing to queues for large payloads:
      SignInvoiceJob::dispatch($invoiceId)->onQueue('high');
      

Sequencing

  1. Pre-requisites:
    • Obtain SUNAT-approved PFX certificate and convert to PEM.
    • Set up secure storage for .pem files (e.g., encrypted storage/app/certs/).
  2. Development:
    • Implement signing service (e.g., SunatSigner class).
    • Add error handling (e.g., log failures to laravel.log).
  3. Deployment:
    • Test in staging with SUNAT’s sandbox.
    • Monitor performance (CPU/memory usage during signing).
  4. Post-Launch:
    • Set up alerts for failed signatures (e.g., Sentry).
    • Plan for certificate renewal (SUNAT certificates expire annually).

Operational Impact

Maintenance

  • Certificate Management:
    • Rotation: Manual process (track SUNAT’s certificate expiry dates).
    • Backup: Store .pem backups in a secure vault (e.g., AWS KMS).
  • Package Updates:
    • No active maintenance: Monitor for forks (e.g., php-xmlsecurity) or SUNAT schema changes.
    • Fallback Plan: If the package becomes obsolete, consider:
      • Custom implementation using XMLSecLibs directly.
      • Third-party APIs (e.g., SUNAT’s official SDK if available).
  • Logging:
    • Log signing attempts, failures, and certificate metadata (e.g., expiry date).
    • Example:
      try {
          $signedXml = $signer->signXml($xml);
          Log::info('Invoice signed successfully', ['invoice_id' => $id]);
      } catch (\Exception $e) {
          Log::error('Signature failed', ['error' => $e->getMessage()]);
          throw $e;
      }
      

Support

  • Troubleshooting:
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.
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
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium