承接 pedrocasado/nfse-php 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

pedrocasado/nfse-php

Composer 安装命令:

composer require pedrocasado/nfse-php

包简介

Lib to communicate with Sistema Nacional (NFS-e)

README 文档

README

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

composer require pedrocasado/nfse-php

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)

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)

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

  • 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

  • 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

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

  • 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

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

pedrocasado/nfse-php 适用场景与选型建议

pedrocasado/nfse-php 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 532 次下载、GitHub Stars 达 15, 最近一次更新时间为 2020 年 02 月 12 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「nfse」 「nfse-php」 「nota fiscal de servicos eletronica」 「sistema nacional de notas fiscais eletronicas」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 pedrocasado/nfse-php 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 pedrocasado/nfse-php 我们能提供哪些服务?
定制开发 / 二次开发

基于 pedrocasado/nfse-php 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 532
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 16
  • 点击次数: 20
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 15
  • Watchers: 1
  • Forks: 9
  • 开发语言: PHP

其他信息

  • 授权协议: LGPL-3.0-or-later
  • 更新时间: 2020-02-12