PHPackages                             pedrocasado/nfse-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. pedrocasado/nfse-php

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

pedrocasado/nfse-php
====================

Lib to communicate with Sistema Nacional (NFS-e)

v3.2.0(1mo ago)13510—0%8LGPL-3.0-or-laterPHPPHP ^8.1

Since Feb 12Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/pedrocasado/nfse-php)[ Packagist](https://packagist.org/packages/pedrocasado/nfse-php)[ RSS](/packages/pedrocasado-nfse-php/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (7)Versions (23)Used By (0)

NFSePHP
=======

[](#nfsephp)

Library to communicate with the **Sistema Nacional da NFS-e** (Sefin Nacional): create and cancel NFS-e via the national REST API.

**Version 3** is a complete refactor from v2. It targets the Sefin Nacional environment only (no Nota Carioca or other SOAP providers). DPS and evento XML follow the official XSDs; certificate-based signing and optional PSR-3 logging are built in.

---

Install
-------

[](#install)

```
composer require pedrocasado/nfse-php
```

---

Certificate
-----------

[](#certificate)

Use a PFX (PKCS#12) certificate issued for your company. The library needs the **PFX binary content** and password (e.g. read from file or env).

```
use NFSePHP\Certificate;

$pfxContent = file_get_contents('/path/to/certificate.pfx');
$certificate = new Certificate(pfxContent: $pfxContent, pfxPassword: 'your-pfx-password');
```

---

Create NFS-e (DPS)
------------------

[](#create-nfs-e-dps)

Build an `InfDpsDTO` (prestador, tomador, serviço, valores, competência, etc.), then call `createNFSe`. The service builds the DPS XML, signs it, optionally validates against the XSD, then sends it gzip+base64 to the Sefin endpoint. Environment (homolog/prod) is taken from `InfDpsDTO->tpAmb` (1 = production, 2 = homologation) unless you override the base URL.

```
use NFSePHP\Certificate;
use NFSePHP\NFSeService;
use NFSePHP\DTO\InfDpsDTO;
use NFSePHP\DTO\PrestadorDTO;
use NFSePHP\DTO\TomadorDTO;
use NFSePHP\DTO\ServicoDTO;
use NFSePHP\DTO\ValoresServicoDTO;

$certificate = new Certificate(pfxContent: $pfxContent, pfxPassword: $pfxPassword);
$service = new NFSeService(certificate: $certificate);

$dto = new InfDpsDTO(
    tpAmb: '2',
    versao: '1.01',
    prest: new PrestadorDTO(cnpj: '...', inscricaoMunicipal: '...', razaoSocial: '...', /* ... */),
    tomador: new TomadorDTO(/* ... */),
    servico: new ServicoDTO(/* ... */),
    valores: new ValoresServicoDTO(/* ... */),
    dCompet: '...',
    cLocEmi: '...',
    serie: '1',
    nDPS: '1',
    // ...
);

$response = $service->createNFSe(infDpsDTO: $dto);

if ($response->isHttpSuccess() && $response->hasParsedResponse()) {
    $body = $response->response;
    if ($body->isSuccess()) {
        $chave = $body->chaveAcesso;
        $xml = $body->getNfseXml(); // decoded gzip+base64
    } else {
        foreach ($body->getErros() as $erro) {
            // $erro->codigo, $erro->descricao
        }
    }
} else {
    $statusCode = $response->statusCode;
    $rawBody = $response->rawBody;
}
```

---

Cancel NFS-e (Evento)
---------------------

[](#cancel-nfs-e-evento)

Use `EventoCancelamentoDTO` with the NFS-e key, author (CNPJ or CPF), reason code and description, then call `cancelNFSe`. The service builds the evento XML (pedRegEvento layout per schema 1.00), signs `infPedReg`, sends it gzip+base64 to `/{chave}/eventos`.

```
use NFSePHP\DTO\EventoCancelamentoDTO;
use NFSePHP\DTO\EventoResponse;

$evento = new EventoCancelamentoDTO(
    tpAmb: '2',
    dhEvento: '2026-02-27T19:00:00-03:00',
    chNFSe: '33045572238744743000149000000000001026029316934590',
    cMotivo: '2',
    xMotivo: 'Cancelamento de teste com motivo adequado',
    cnpjAutor: '38744743000149',
);

$response = $service->cancelNFSe(evento: $evento);

if ($response->isHttpSuccess() && $response->hasParsedResponse()) {
    $body = $response->response;
    $xml = $body->getEventoXml();
} else {
    $statusCode = $response->statusCode;
    $rawBody = $response->rawBody;
}
```

---

Configuration
-------------

[](#configuration)

- **Endpoint**
    By default the base URL is chosen from `tpAmb` (1 → production, 2 → homologation). You can override it when constructing `DpsService`:

    ```
    $service = new NFSeService(certificate: $certificate, endpointUrl: 'https://custom.sefin.gov.br/nfse');
    ```
- **Logger (PSR-3)**
    Pass a `Psr\Log\LoggerInterface` to send debug output (XML dumps, validation errors, request URLs) to your app logger:

    ```
    $service = new NFSeService(certificate: $certificate, logger: $logger);
    ```
- **Debug flag**
    If you don’t inject a logger but set `$debug = true`, the same information is written to stderr.
- **DTO validation**
    `createNFSe(infDpsDTO: $dto, validateDTOs: true)` runs Symfony Validator on `InfDpsDTO` (and nested DTOs). Use `validateDTOs: false` to skip.
- **XSD validation**
    When enabled (e.g. in debug), the signed DPS and evento XML are validated against the bundled XSDs. On failure an `InvalidXSDException` is thrown (or only logged, depending on flow).

---

Response parsing
----------------

[](#response-parsing)

- **DPS**
    `DpsResponse` holds `statusCode`, `rawBody`, and optional `response` (`SefinNacionalResponse`). Use `response->isSuccess()` / `response->isError()`, `response->getErros()`, `response->getNfseXml()`.
- **Evento**
    `EventoResponse` holds `statusCode`, `rawBody`, and optional `response` (`EventoCancelamentoResponseDTO`). Use `response->getEventoXml()` to decode the returned gzip+base64 evento XML.

The Sefin API can return errors in `erro` or `erros`, with `codigo`/`Codigo` and `descricao`/`Descricao`; the library normalizes these when parsing.

---

Tests
-----

[](#tests)

```
composer test
```

Tests cover DTOs (including validation), response parsing (Sefin and Evento), and response helpers. See `tests/README.md` for details and ideas for XML-building tests.

---

Changelog / v2 → v3
-------------------

[](#changelog--v2--v3)

- **Target**: Sefin Nacional (REST, JSON body, gzip+base64 XML). No Nota Carioca or SOAP.
- **DPS**: Build from `InfDpsDTO`, sign `infDPS`, POST to Sefin; response parsed into `SefinNacionalResponse`.
- **Cancelamento**: Evento de cancelamento (e101101) with `pedRegEvento`/`infPedReg` layout (schema 1.00), sign `infPedReg`, POST to `/{chave}/eventos`.
- **Certificate**: PFX content + password; PEM paths used for HTTP client mTLS.
- **Logging**: Optional PSR-3 logger or `$debug` stderr fallback.
- **Validation**: Symfony Validator on DTOs; optional XSD validation for signed XML.

---

License
-------

[](#license)

LGPL-3.0-or-later / GPL-3.0-or-later / MIT.

###  Health Score

55

—

FairBetter than 98% of packages

Maintenance90

Actively maintained with recent releases

Popularity25

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity75

Established project with proven stability

 Bus Factor1

Top contributor holds 95.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~106 days

Total

22

Last Release

52d ago

Major Versions

v1.2.1 → v2.0.02020-06-17

v2.0.11 → v3.0.02026-03-02

PHP version history (3 changes)v1.0.0PHP &gt;= 7.1

v2.0.10PHP ^7.1 | ^8.0

v3.0.0PHP ^8.1

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/354624?v=4)[Pedro Casado](/maintainers/pedrocasado)[@pedrocasado](https://github.com/pedrocasado)

---

Top Contributors

[![pedrocasado](https://avatars.githubusercontent.com/u/354624?v=4)](https://github.com/pedrocasado "pedrocasado (43 commits)")[![fgracalepsus](https://avatars.githubusercontent.com/u/7882648?v=4)](https://github.com/fgracalepsus "fgracalepsus (1 commits)")[![marcosandrade22](https://avatars.githubusercontent.com/u/4664235?v=4)](https://github.com/marcosandrade22 "marcosandrade22 (1 commits)")

---

Tags

nfsenfse-phpnota fiscal de servicos eletronicasistema nacional de notas fiscais eletronicas

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/pedrocasado-nfse-php/health.svg)

```
[![Health](https://phpackages.com/badges/pedrocasado-nfse-php/health.svg)](https://phpackages.com/packages/pedrocasado-nfse-php)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M648](/packages/sylius-sylius)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[phpro/soap-client

A general purpose SoapClient library

8885.6M46](/packages/phpro-soap-client)[kimai/kimai

Kimai - Time Tracking

4.6k7.4k1](/packages/kimai-kimai)[cognesy/instructor-php

The complete AI toolkit for PHP: unified LLM API, structured outputs, agents, and coding agent control

310107.9k1](/packages/cognesy-instructor-php)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
