paseto/nfse-betha

PHP library for NFSe Betha integration with XML digital signing support using ICP Brasil certificates

dev-main / 1.0.x-dev 2025-07-25 16:33 UTC

This package is auto-updated.

Last update: 2025-07-25 16:38:20 UTC


README

Latest Version on Packagist Total Downloads Software License

A comprehensive PHP library for NFSe Betha integration with XML digital signing support using ICP Brasil certificates.

Features

  • πŸ” Complete XML Digital Signing with ICP Brasil certificates
  • πŸ“‹ Full NFSe Operations: Generation, Cancellation, and Consultation
  • πŸ›‘οΈ XML-DSig Compliance following W3C standards
  • πŸ›οΈ XSD Schema Validation according to nfse_v202.xsd
  • πŸ”„ Automatic SOAP Envelope creation and handling
  • 🌐 Multi-mode Support: SoapClient and cURL fallback
  • πŸ“Š Comprehensive Error Handling and validation
  • πŸ“ Local WSDL Support for reliable offline development
  • πŸš€ Production Ready with extensive testing

Requirements

  • PHP >= 7.4
  • OpenSSL extension
  • DOM extension
  • XML extension
  • cURL extension
  • SOAP extension
  • ICP Brasil certificate in PFX format

Installation

Install via Composer:

composer require paseto/nfse-betha

Quick Start

Basic Usage

<?php

use Paseto\NFSeBetha\NFSeBetha;

// Initialize the API
$nfseAPI = new NFSeBetha($certificatePath, $certificatePassword);

// Generate NFSe
$nfse = $nfseAPI->gerarNfse([
    'rps' => [
        'numero' => '123',
        'serie' => '1',
        'tipo' => '1',
        'data_emissao' => date('Y-m-d'),
        'status' => '1'
    ],
    'competencia' => date('Y-m-d'),
    'servico' => [
        'valores' => [
            'valor_servicos' => '100.00',
            'valor_deducoes' => '0.00',
            'valor_iss' => '3.75',
            'aliquota' => '3.75',
            'desconto_incondicionado' => '0.00',
            'desconto_condicionado' => '0.00'
        ],
        'iss_retido' => '2',
        'item_lista_servico' => '0103',
        'discriminacao' => 'ServiΓ§os de consultoria em tecnologia da informaΓ§Γ£o',
        'codigo_municipio' => '4204608',
        'exigibilidade_iss' => '1'
    ],
    'prestador' => [
        'cnpj' => '20002537000171',
        'inscricao_municipal' => '12345'
    ],
    'tomador' => [
        'identificacao' => [
            'cnpj' => '02509015000105',
            'inscricao_municipal' => '22540'
        ],
        'razao_social' => 'EMPRESA EXEMPLO LTDA',
        'endereco' => [
            'logradouro' => 'RUA EXEMPLO',
            'numero' => '123',
            'bairro' => 'CENTRO',
            'codigo_municipio' => '4204608',
            'uf' => 'SC',
            'cep' => '88000000'
        ]
    ],
    'optante_simples_nacional' => '1',
    'incentivo_fiscal' => '2'
]);

// Check result
if ($nfse !== false) {
    echo "NFSe generated successfully!";
    echo "Number: " . $nfse['ListaNfse']['CompNfse']['Nfse']['InfNfse']['Numero'];
} else {
    echo "Error: " . $nfseAPI->getLastError();
}

Cancel NFSe

// Cancel NFSe
$cancellation = $nfseAPI->cancelarNfse([
    'numero' => '1',
    'prestador' => [
        'cnpj' => '20002537000171',
        'inscricao_municipal' => '12345'
    ],
    'codigo_municipio' => '4204608',
    'codigo_cancelamento' => '1'
]);

if ($cancellation !== false) {
    echo "NFSe cancelled successfully!";
} else {
    echo "Error: " . $nfseAPI->getLastError();
}

Consult NFSe

// Consult NFSe by range
$consultation = $nfseAPI->consultarNfseFaixa([
    'prestador' => [
        'cnpj' => '20002537000171',
        'inscricao_municipal' => '12345'
    ],
    'faixa' => [
        'numero_inicial' => '1',
        'numero_final' => '10'
    ],
    'pagina' => '1'
]);

// Consult NFSe by service provider
$consultation = $nfseAPI->consultarNfseServicoPrestado([
    'prestador' => [
        'cnpj' => '20002537000171',
        'inscricao_municipal' => '12345'
    ],
    'periodo_emissao' => [
        'data_inicial' => '2024-01-01',
        'data_final' => '2024-12-31'
    ],
    'pagina' => '1'
]);

Configuration

Certificate Setup

  1. Obtain your ICP Brasil certificate in PFX format
  2. Store it securely (outside web root)
  3. Set appropriate file permissions (600)
$certificatePath = '/secure/path/to/certificate.pfx';
$certificatePassword = 'your-certificate-password';

Environment Variables

For enhanced security, use environment variables:

$certificatePath = $_ENV['NFSE_CERTIFICATE_PATH'];
$certificatePassword = $_ENV['NFSE_CERTIFICATE_PASSWORD'];

Digital Signing

This library implements complete XML digital signing according to:

  • XML-DSig W3C Standards
  • ICP Brasil Requirements
  • NFSe Betha XSD Schema

Signature Features

  • βœ… Automatic signature placement per XSD schema
  • βœ… Canonical XML (C14N) processing
  • βœ… X509 certificate embedding
  • βœ… SHA1 digest and RSA-SHA1 signature algorithms
  • βœ… Enveloped signature transforms

Available Operations

Operation Method Signing Required
Generate NFSe gerarNfse() βœ… Yes
Cancel NFSe cancelarNfse() βœ… Yes
Consult NFSe Range consultarNfseFaixa() ❌ No
Consult NFSe by Provider consultarNfseServicoPrestado() ❌ No
Send RPS Batch enviarLoteRps() βœ… Yes
Consult RPS Batch consultarLoteRps() ❌ No

Error Handling

try {
    $result = $nfseAPI->gerarNfse($rpsData);
    
    if ($result === false) {
        // Check specific error
        $error = $nfseAPI->getLastError();
        echo "Error: " . $error;
    } else {
        // Success - process result
        echo "Success!";
    }
} catch (Exception $e) {
    // Handle exceptions
    echo "Exception: " . $e->getMessage();
}

Testing

Run the test suite:

composer test

Check code quality:

composer quality

Security

Best Practices

  1. Certificate Security

    • Store certificates outside web root
    • Use environment variables for passwords
    • Set proper file permissions (600)
    • Never commit certificates to version control
  2. Environment Configuration

    • Use .env files for sensitive configuration
    • Validate all input parameters
    • Log errors securely without exposing sensitive data
  3. Production Deployment

    • Use HTTPS in production
    • Implement proper error logging
    • Monitor certificate expiration
    • Regular security updates

Contributing

Contributions are welcome! Please read our Contributing Guide for details.

Development Setup

git clone https://github.com/paseto/nfse-betha.git
cd nfse-betha
composer install

Code Standards

  • PSR-2 coding standards
  • PHPStan level 7 analysis
  • 100% test coverage for critical paths

Changelog

Please see CHANGELOG for recent changes.

License

The MIT License (MIT). Please see License File for more information.

Support