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

Sped Cte Laravel Package

nfephp-org/sped-cte

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require nfephp-org/sped-cte
    

    Ensure your project uses PHP 8.1+ (check composer.json and php -v).

  2. First Use Case: Generating a Basic CTe

    use NFePHP\CTe\Common\Certificate\CertificateInterface;
    use NFePHP\CTe\Common\Certificate\CertificateFactory;
    use NFePHP\CTe\CTe;
    
    // Load your certificate (PFX format)
    $cert = CertificateFactory::create(
        __DIR__.'/path/to/certificado.pfx',
        'your_password',
        'your_certificate_password'
    );
    
    // Initialize CTe
    $cte = new CTe($cert);
    
    // Set basic data (replace with your values)
    $cte->setRemetente([
        'cnpj' => '12345678901234',
        'xNome' => 'NOME DA EMPRESA',
        'xFantasia' => 'FANTASIA',
        'IE' => '123456789',
        'xMun' => 'CURITIBA',
        'UF' => 'PR',
    ]);
    
    $cte->setDestinatario([
        'cnpj' => '98765432109876',
        'xNome' => 'DESTINATÁRIO',
        'IE' => '987654321',
        'xMun' => 'SAO PAULO',
        'UF' => 'SP',
    ]);
    
    // Generate XML
    $xml = $cte->gerarXml();
    file_put_contents('cte.xml', $xml);
    
  3. Where to Look First

    • Documentation: Check the NFePHP Wiki for CTe-specific guides.
    • Examples: Browse the tests folder for real-world use cases.
    • SEFAZ Sandbox: Test against the SEFAZ Homologação before production.

Implementation Patterns

Workflow: Full CTe Lifecycle

  1. Data Preparation Use CTe methods to populate data:

    $cte->setTransporta([
        'cnpj' => '11122233344455',
        'xNome' => 'TRANSPORTADORA',
        'VEICULO' => [
            'placa' => 'ABC1234',
            'UF' => 'SP',
            'RNTC' => '123456789012345',
        ],
    ]);
    
  2. XML Generation

    $xml = $cte->gerarXml();
    $cte->validarXml(); // Validate before sending
    
  3. SEFAZ Communication Use CTeService for web service calls:

    use NFePHP\CTe\CTeService;
    
    $service = new CTeService($cert, 'https://homologacao.sefaz.com.br');
    $response = $service->autorizar($xml);
    $protocol = $response->getProtocol();
    
  4. Event Handling Listen for lifecycle events (e.g., onAfterAutorizar):

    $cte->on('afterAutorizar', function ($event) {
        // Log or process the protocol
        file_put_contents('protocol.json', json_encode($event->getProtocol()));
    });
    

Integration Tips

  • Queue Jobs for Async Processing Offload CTe generation/authorization to Laravel queues:

    // In a job class
    public function handle() {
        $cte = new CTe($this->cert);
        $cte->setRemetente($this->remetenteData);
        // ... other setters
        $xml = $cte->gerarXml();
        $response = $this->service->autorizar($xml);
        $this->dispatch(new ProcessProtocolJob($response->getProtocol()));
    }
    
  • Laravel Service Provider Bind interfaces for dependency injection:

    // app/Providers/AppServiceProvider.php
    public function register() {
        $this->app->bind(CertificateInterface::class, function () {
            return CertificateFactory::create(
                config('cte.certificate.path'),
                config('cte.certificate.password')
            );
        });
    }
    
  • Validation Use Laravel’s validator for input data:

    $validator = Validator::make($request->all(), [
        'remetente.cnpj' => 'required|cnpj',
        'destinatario.cnpj' => 'required|cnpj',
    ]);
    

Gotchas and Tips

Pitfalls

  1. Certificate Issues

    • Problem: CertificateException on invalid PFX files or passwords.
    • Fix: Verify the certificate path and passwords in config/cte.php:
      'certificate' => [
          'path' => storage_path('certs/cte.pfx'),
          'password' => env('CTE_CERT_PASSWORD'),
          'cert_password' => env('CTE_CERT_CERT_PASSWORD'),
      ],
      
    • Debug: Use openssl pkcs12 -info -in certificado.pfx to validate the PFX file.
  2. SEFAZ Timeouts

    • Problem: ConnectionException due to slow SEFAZ responses.
    • Fix: Increase timeout in CTeService:
      $service = new CTeService($cert, 'https://sefaz.com.br', [
          'timeout' => 30,
      ]);
      
  3. XML Validation Errors

    • Problem: ValidationException with cryptic error messages.
    • Fix: Enable verbose validation:
      $cte->validarXml(true); // Shows detailed errors
      
    • Common Causes:
      • Missing required fields (e.g., xMun or UF).
      • Invalid CNPJ/IE formats (use NFePHP\CTe\Common\Util validators).
  4. UF-Specific Rules

    • Problem: Some states (e.g., SP, RJ) enforce additional rules.
    • Fix: Check SEFAZ manuals for state-specific requirements (e.g., indIEDest for ICMS).

Debugging Tips

  • Log Raw XML
    \Log::info('CTe XML', ['xml' => $cte->gerarXml()]);
    
  • Compare with SEFAZ Samples Use the SEFAZ CTe schema to validate your XML structure.

Extension Points

  1. Custom Protocols Extend NFePHP\CTe\CTeProtocol to handle non-standard responses:

    class CustomProtocol extends CTeProtocol {
        public function getCustomField() {
            return $this->xml->xpath('//ns:customField');
        }
    }
    
  2. Event Customization Override default events in your CTe instance:

    $cte->on('beforeAutorizar', function ($event) {
        $event->setCustomHeader('X-Custom-Header', 'value');
    });
    
  3. Batch Processing Use CTeBatch for multiple CTe documents:

    $batch = new CTeBatch($cert);
    foreach ($ctes as $cteData) {
        $batch->add($cteData);
    }
    $batch->autorizar();
    

Configuration Quirks

  • Environment Variables Ensure .env has:

    CTE_CERT_PATH=storage/certs/cte.pfx
    CTE_CERT_PASSWORD=yourpassword
    CTE_CERT_CERT_PASSWORD=certpassword
    CTE_SEFAZ_URL=https://homologacao.sefaz.com.br
    
  • Caching Cache SEFAZ responses for retries (e.g., using Illuminate\Support\Facades\Cache):

    $response = Cache::remember("cte_protocol_{$cnpj}", now()->addHours(1), function () use ($service, $xml) {
        return $service->autorizar($xml);
    });
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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
spatie/mailcoach-vapor