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.
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).
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,
],
];
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();
Preparation Phase
NFeService).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
$attempts = 0;
while ($attempts < 3) {
try {
$response = $nfe->sendToSEFAZ();
break;
} catch (\Exception $e) {
$attempts++;
sleep(2 ** $attempts); // Exponential backoff
}
}
Post-Processing
protocolo, chaveNFe) and store in DB:
$response = json_decode($nfe->getLastResponse(), true);
$protocolo = $response['protocoloNFe']['infProtocolo']['nProtocolo'];
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()]);
});
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.
Certificate Issues
.pfx file is not corrupted and the password is correct.$cert = new Certificate($path, $password);
if (!$cert->isValid()) {
throw new \Exception("Invalid certificate");
}
openssl pkcs12 -info -in certificate.pfx
SEFAZ Timeouts
Log::error("SEFAZ Error: " . $nfe->getLastError());
XML Validation
$validator = new \NFePHP\NFe\Validator\NFeValidator();
$errors = $validator->validate($xml);
if (!empty($errors)) {
throw new \Exception("XML Errors: " . implode(", ", $errors));
}
State-Specific Rules
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
How can I help you explore Laravel packages today?