Installation
composer require nfephp-org/sped-cte
Ensure your project uses PHP 8.1+ (check composer.json and php -v).
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);
Where to Look First
tests folder for real-world use cases.Data Preparation
Use CTe methods to populate data:
$cte->setTransporta([
'cnpj' => '11122233344455',
'xNome' => 'TRANSPORTADORA',
'VEICULO' => [
'placa' => 'ABC1234',
'UF' => 'SP',
'RNTC' => '123456789012345',
],
]);
XML Generation
$xml = $cte->gerarXml();
$cte->validarXml(); // Validate before sending
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();
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()));
});
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',
]);
Certificate Issues
CertificateException on invalid PFX files or passwords.config/cte.php:
'certificate' => [
'path' => storage_path('certs/cte.pfx'),
'password' => env('CTE_CERT_PASSWORD'),
'cert_password' => env('CTE_CERT_CERT_PASSWORD'),
],
openssl pkcs12 -info -in certificado.pfx to validate the PFX file.SEFAZ Timeouts
ConnectionException due to slow SEFAZ responses.CTeService:
$service = new CTeService($cert, 'https://sefaz.com.br', [
'timeout' => 30,
]);
XML Validation Errors
ValidationException with cryptic error messages.$cte->validarXml(true); // Shows detailed errors
xMun or UF).NFePHP\CTe\Common\Util validators).UF-Specific Rules
indIEDest for ICMS).\Log::info('CTe XML', ['xml' => $cte->gerarXml()]);
Custom Protocols
Extend NFePHP\CTe\CTeProtocol to handle non-standard responses:
class CustomProtocol extends CTeProtocol {
public function getCustomField() {
return $this->xml->xpath('//ns:customField');
}
}
Event Customization
Override default events in your CTe instance:
$cte->on('beforeAutorizar', function ($event) {
$event->setCustomHeader('X-Custom-Header', 'value');
});
Batch Processing
Use CTeBatch for multiple CTe documents:
$batch = new CTeBatch($cert);
foreach ($ctes as $cteData) {
$batch->add($cteData);
}
$batch->autorizar();
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);
});
How can I help you explore Laravel packages today?