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 Nfe Laravel Package

nfephp-org/sped-nfe

Biblioteca PHP para gerar, assinar e comunicar NF-e (55) e NFC-e (65) com as SEFAZ. Suporta todos os estados, emissão com eCPF (com exceções), envio síncrono e atualizações conforme notas técnicas e schemas recentes do SPED NF-e.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require nfephp-org/sped-nfe
    

    Ensure your project uses PHP 7.2+ (last release was in 2020, but the package supports modern PHP).

  2. Basic Configuration Create a config file (e.g., config/nfe.php) and define your SEFAZ credentials:

    return [
        'certificate' => [
            'path' => storage_path('app/certificates/certificado.pfx'),
            'password' => env('NFE_CERT_PASSWORD'),
        ],
        'company' => [
            'cnpj' => env('NFE_CNPJ'),
            'state' => env('NFE_STATE'), // e.g., 'SP', 'RJ'
        ],
        'sefa' => [
            'url' => env('NFE_SEFAZ_URL'), // e.g., 'https://nfe.sefa.sp.gov.br'
            'timeout' => 30,
        ],
    ];
    
  3. First Use Case: Generate a Simple NFe Use the NFe facade or instantiate the class directly:

    use NFePHP\NFe\Common\Certificate;
    use NFePHP\NFe\NFe;
    
    $cert = new Certificate(config('nfe.certificate.path'), config('nfe.certificate.password'));
    $nfe = new NFe($cert, config('nfe.company.cnpj'), config('nfe.company.state'));
    
    // Create a basic NFe object
    $nfe->setId('35150436000100000100550010000000010000000069');
    $nfe->setEmit(config('nfe.company.cnpj'), 'Emitente Ltda');
    $nfe->setDest('12345678901', 'Destinatário');
    
    // Add an item
    $nfe->addItem('0001', 'Serviço de Consultoria', 100.00, 10.00, 110.00);
    
    // Generate XML
    $xml = $nfe->getXml();
    file_put_contents(storage_path('app/nfe.xml'), $xml);
    
    // Send to SEFAZ
    $response = $nfe->sendToSEFAZ();
    

Implementation Patterns

1. Workflow for Daily NFe Processing

  • Preparation Phase

    • Use a Service Class to encapsulate NFe logic (e.g., NFeService).
    • Validate input data (e.g., CNPJ, IE, products) before generating XML.
    • Example:
      class NFeService {
          public function generateNFe(array $data) {
              $nfe = new NFe($this->cert, $data['cnpj'], $data['state']);
              $nfe->setId($this->generateId()); // Custom ID logic
              $nfe->setEmit($data['cnpj'], $data['company_name']);
              // ... populate other fields
              return $nfe->getXml();
          }
      }
      
  • SEFAZ Communication

    • Handle retries for timeouts or SEFAZ unavailability:
      $attempts = 0;
      while ($attempts < 3) {
          try {
              $response = $nfe->sendToSEFAZ();
              break;
          } catch (\Exception $e) {
              $attempts++;
              sleep(2 ** $attempts); // Exponential backoff
          }
      }
      
  • Post-Processing

    • Parse SEFAZ responses (e.g., protocolo, chaveNFe) and store in DB:
      $response = json_decode($nfe->getLastResponse(), true);
      $protocolo = $response['protocoloNFe']['infProtocolo']['nProtocolo'];
      

2. Integration with Laravel

  • Artisan Commands Create a command to generate/validate NFe in bulk:

    php artisan nfe:generate --file=orders.csv
    

    Example command:

    class GenerateNFeCommand extends Command {
        protected $signature = 'nfe:generate {file}';
        public function handle() {
            $orders = collect(Csv::get($this->argument('file')));
            foreach ($orders as $order) {
                $nfe = (new NFeService())->generateNFe($order);
                // Save to DB or send to SEFAZ
            }
        }
    }
    
  • Events & Observers Trigger NFe generation after order creation:

    class OrderObserver {
        public function created(Order $order) {
            if ($order->is_taxable) {
                $nfe = (new NFeService())->generateNFe($order->toArray());
                $order->nfe_protocol = $nfe->getProtocol();
                $order->save();
            }
        }
    }
    
  • API Endpoints Expose NFe generation as an API:

    Route::post('/nfe/generate', function (Request $request) {
        $nfe = (new NFeService())->generateNFe($request->validated());
        return response()->json(['xml' => $nfe->getXml()]);
    });
    

3. Handling Common NFe Types

  • NFe 4.0+ Compliance The package supports NFe 4.0 (last release). For newer versions, check SEFAZ’s manual. Example for NF-e Simplificada (without items):

    $nfe->setId('35150436000100000100550010000000010000000069');
    $nfe->setEmit($cnpj, 'Emitente');
    $nfe->setDest($cpf, 'Destinatário');
    $nfe->setTotal(100.00, 10.00, 110.00); // Total, BC, ICMS
    $nfe->setICMS(10.00, 18.00); // BC, Aliquota
    
  • CT-e (Transport) Integration If you also need CT-e, consider pairing with sped-cte.


Gotchas and Tips

1. Common Pitfalls

  • Certificate Issues

    • Ensure the .pfx file is not corrupted and the password is correct.
    • Test with:
      $cert = new Certificate($path, $password);
      if (!$cert->isValid()) {
          throw new \Exception("Invalid certificate");
      }
      
    • Tip: Use OpenSSL to verify:
      openssl pkcs12 -info -in certificate.pfx
      
  • SEFAZ Timeouts

    • SEFAZ servers may throttle requests. Use exponential backoff (as shown above).
    • Monitor response times and log failures:
      Log::error("SEFAZ Error: " . $nfe->getLastError());
      
  • XML Validation

    • Always validate the generated XML against SEFAZ’s schema:
      $validator = new \NFePHP\NFe\Validator\NFeValidator();
      $errors = $validator->validate($xml);
      if (!empty($errors)) {
          throw new \Exception("XML Errors: " . implode(", ", $errors));
      }
      
  • State-Specific Rules

    • Some states (e.g., SP, RJ, MG) have unique requirements. Check:
    • Example: SP requires tpAmb=2 (production) and RJ may need indFinal=1 for final NFe.

2. Debugging Tips

  • Enable Verbose Logging Configure the package to log raw requests/responses:

    $nfe->setDebug(true);
    $nfe->sendToSEFAZ();
    // Check logs for raw XML/HTTP details
    
  • Test with Homologação (Sandbox) Use SEFAZ’s homologation environment for testing:

    $nfe->setSEFAZUrl('https://homologacao.nfe.fazenda.gov.br');
    
  • Compare with SEFAZ’s Examples Download sample XMLs from [NFe 4.0 Manual](https://www.nfe.fazenda.gov.br/portal/exibirArquivo.aspx?con

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.
graham-campbell/flysystem
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
directorytree/opensearch-client
directorytree/opensearch-adapter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin