NFSeNacionalSdk 0.2.0-preview.2

This is a prerelease version of NFSeNacionalSdk.
dotnet add package NFSeNacionalSdk --version 0.2.0-preview.2
                    
NuGet\Install-Package NFSeNacionalSdk -Version 0.2.0-preview.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="NFSeNacionalSdk" Version="0.2.0-preview.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="NFSeNacionalSdk" Version="0.2.0-preview.2" />
                    
Directory.Packages.props
<PackageReference Include="NFSeNacionalSdk" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add NFSeNacionalSdk --version 0.2.0-preview.2
                    
#r "nuget: NFSeNacionalSdk, 0.2.0-preview.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package NFSeNacionalSdk@0.2.0-preview.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=NFSeNacionalSdk&version=0.2.0-preview.2&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=NFSeNacionalSdk&version=0.2.0-preview.2&prerelease
                    
Install as a Cake Tool

NFSe Nacional SDK for .NET

SDK .NET para integracao com o ambiente nacional da NFS-e, incluindo consulta de NFS-e, emissao sincronica de DPS, consulta de DPS, parametrizacao municipal, assinatura XML, validacao XSD e parse estruturado do XML retornado.

Status: 0.2.0-preview.1

A emissao e a consulta ja foram validadas em Producao Restrita. O registro de evento de cancelamento foi implementado conforme schema v1.01 e endpoint oficial, mas deve ser validado com cautela em Producao Restrita antes de uso real.

Features

  • Ambientes de Producao Restrita e Producao
  • Cliente HTTP com certificado A1
  • Consulta de NFS-e por chave de acesso
  • Retorno do XML bruto e de um NFSeDocument estruturado
  • Emissao sincronica de DPS e geracao de NFS-e
  • Assinatura XML da DPS
  • Validacao XML contra schemas v1.01
  • Consulta de DPS por id
  • Verificacao de DPS por HEAD
  • Consulta de convenio municipal
  • Consulta de aliquota municipal por servico
  • Evento de cancelamento de NFS-e
  • Normalizacao base de respostas com Success, StatusCode, Messages, RawXml e RawJson
  • Factory oficial para uso direto da DLL
  • Extensoes oficiais para dependency injection

Target Frameworks

  • netstandard2.0
  • net8.0
  • net10.0

O target netstandard2.0 permite consumir o SDK em projetos .NET Framework, incluindo .NET Framework 4.6.2. Quando for possivel escolher, .NET Framework 4.7.2 ou superior tende a reduzir problemas de dependencias transitivas e binding redirects, mas o pacote tambem publica assets compativeis com 4.6.2.

Pacotes

O pacote principal e:

dotnet add package NFSeNacionalSdk --prerelease

Os projetos internos tambem sao empacotados, pois o pacote principal depende deles:

  • NFSeNacionalSdk.Core
  • NFSeNacionalSdk.Contracts
  • NFSeNacionalSdk.Serialization.Xml
  • NFSeNacionalSdk.Transport.Http

Ao publicar uma versao, publique todos os pacotes gerados com a mesma versao.

Uso Basico

Criar o cliente com factory

using NFSeNacionalSdk;
using NFSeNacionalSdk.Core.Enums;
using NFSeNacionalSdk.Core.Options;

using var client = NFSeClientFactory.Create(options =>
{
    options.Environment = NFSeEnvironment.ProductionRestricted;
    options.CertificateFile = new NFSeCertificateFileOptions
    {
        Path = "certificado.pfx",
        Password = "senha-do-certificado"
    };
});

Tambem e possivel informar um X509Certificate2 ja carregado:

using System.Security.Cryptography.X509Certificates;
using NFSeNacionalSdk;
using NFSeNacionalSdk.Core.Enums;
using NFSeNacionalSdk.Core.Options;

using var certificate = NFSeCertificateLoader.LoadFromPfxFile(
    "certificado.pfx",
    "senha-do-certificado",
    X509KeyStorageFlags.UserKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

using var client = NFSeClientFactory.Create(
    new NFSeSdkOptions
    {
        Environment = NFSeEnvironment.ProductionRestricted
    },
    certificate);

Usar com dependency injection

using Microsoft.Extensions.DependencyInjection;
using NFSeNacionalSdk;
using NFSeNacionalSdk.Contracts.Clients;
using NFSeNacionalSdk.Core.Enums;
using NFSeNacionalSdk.Core.Options;

var services = new ServiceCollection();

services.AddNFSeNacionalSdk(options =>
{
    options.Environment = NFSeEnvironment.ProductionRestricted;
    options.CertificateFile = new NFSeCertificateFileOptions
    {
        Path = "certificado.pfx",
        Password = "senha-do-certificado"
    };
});

using var provider = services.BuildServiceProvider();
var client = provider.GetRequiredService<INFSeClient>();

Usar em VB.NET / .NET Framework 4.6.2

Em projetos legados, instale o pacote NuGet NFSeNacionalSdk no projeto .NET Framework. O NuGet deve restaurar tambem os pacotes transitivos necessarios para netstandard2.0. Se o projeto usar packages.config, habilite ou gere binding redirects quando o Visual Studio solicitar.

Exemplo em VB.NET:

Imports NFSeNacionalSdk
Imports NFSeNacionalSdk.Contracts.Requests
Imports NFSeNacionalSdk.Core.Enums
Imports NFSeNacionalSdk.Core.Options

Dim client = NFSeClientFactory.Create(
    Sub(options)
        options.Environment = NFSeEnvironment.ProductionRestricted
        options.CertificateFile = New NFSeCertificateFileOptions With {
            .Path = "C:\certificados\certificado.pfx",
            .Password = "senha-do-certificado"
        }
    End Sub)

Dim request = New GetNfseByAccessKeyRequest With {
    .AccessKey = "<CHAVE_ACESSO_NFSE>"
}

Dim result = client.GetNfseByAccessKeyAsync(request).GetAwaiter().GetResult()

If result.Success AndAlso result.Document IsNot Nothing Then
    Console.WriteLine(result.Document.Number)
    Console.WriteLine(result.RawXml)
End If

client.Dispose()

Para emissao, DateOnly tambem fica disponivel no target netstandard2.0 pelo proprio pacote de contratos:

Dim emissao = New EmitDpsRequest With {
    .Series = "1",
    .Number = "1",
    .CompetenceDate = New DateOnly(2026, 4, 29),
    .IssuedAt = DateTimeOffset.Now,
    .MunicipalityCode = "3201506"
}

Consultar NFS-e por chave

using NFSeNacionalSdk.Contracts.Requests;

var result = await client.GetNfseByAccessKeyAsync(new GetNfseByAccessKeyRequest
{
    AccessKey = "<CHAVE_ACESSO_NFSE>"
}, cancellationToken);

if (result.Success && result.Document is not null)
{
    var rawXml = result.RawXml;
    var document = result.Document;

    Console.WriteLine(document.Number);
    Console.WriteLine(document.IssuedAt);
    Console.WriteLine(document.Issuer?.Name);
    Console.WriteLine(document.Service?.ServiceCode);
    Console.WriteLine(document.Values?.NetAmount);
    Console.WriteLine(document.Taxation?.Municipal?.IssTaxationType);
}

RawXml preserva o XML original retornado pelo ambiente nacional. Document contem os dados principais ja estruturados para uso no sistema consumidor.

Emitir DPS e gerar NFS-e

using NFSeNacionalSdk.Contracts.Requests;
using NFSeNacionalSdk.Core.Enums;

var result = await client.EmitDpsAsync(new EmitDpsRequest
{
    Series = "1",
    Number = "1",
    CompetenceDate = DateOnly.FromDateTime(DateTime.Today),
    IssuedAt = DateTimeOffset.Now,
    MunicipalityCode = "3201506",
    Provider = new EmitDpsProvider
    {
        TaxId = "<CNPJ_PRESTADOR>",
        SimplesNationalOption = NFSeSimplesNationalOption.MicroOrSmallBusiness,
        SimplifiedNationalTaxRegime = NFSeSimplifiedNationalTaxRegime.FederalAndMunicipalTaxesInSimplesNational,
        SpecialTaxRegime = NFSeSpecialTaxRegime.None
    },
    Recipient = new EmitDpsRecipient
    {
        TaxId = "<CNPJ_TOMADOR>",
        Name = "TOMADOR EXEMPLO LTDA"
    },
    Service = new EmitDpsService
    {
        NationalTaxationCode = "010201",
        Description = "PROGRAMACAO DE SISTEMAS",
        Amount = 1.00m
    },
    Taxation = new EmitDpsTaxation
    {
        IssTaxationType = NFSeIssTaxationType.TaxableOperation,
        IssWithholdingType = NFSeIssWithholdingType.NotWithheld,
        IssRate = null,
        TotalTaxIndicator = null,
        SimplesNationalTotalTaxRate = 2.00m
    }
}, cancellationToken);

Console.WriteLine(result.Success);
Console.WriteLine(result.AccessKey);
Console.WriteLine(result.Document?.Number);
Console.WriteLine(result.SubmittedDpsXml);
Console.WriteLine(result.RawXml);

Para ME/EPP com opSimpNac = 3, regApTribSN = 1 e ISSQN nao retido, informe IssRate = null. Para esse mesmo caso, use TotalTaxIndicator = null e informe SimplesNationalTotalTaxRate.

Cancelar NFS-e por evento

O cancelamento registra um evento oficial para a chave informada. Teste primeiro em Producao Restrita e confirme as regras do municipio/prestador antes de usar em producao.

using NFSeNacionalSdk.Contracts.Requests;
using NFSeNacionalSdk.Core.Enums;

var result = await client.CancelNfseAsync(new CancelNfseRequest
{
    AccessKey = "<CHAVE_ACESSO_NFSE>",
    AuthorTaxId = "<CNPJ_OU_CPF_AUTOR>",
    ReasonCode = NFSeCancellationReasonCode.ServiceNotProvided,
    Reason = "Servico nao prestado ao tomador conforme acordado."
}, cancellationToken);

Console.WriteLine(result.Success);
Console.WriteLine(result.StatusCode);
Console.WriteLine(result.EventId);
Console.WriteLine(result.SubmittedEventXml);
Console.WriteLine(result.RawXml);
Console.WriteLine(result.Event?.Description);

Respostas padronizadas

As respostas principais implementam INFSeResponse e expoem:

  • Success: resultado normalizado da operacao
  • StatusCode: status HTTP retornado pela API
  • Messages: erros, alertas ou mensagens de negocio
  • RawXml: XML bruto quando a API retornar XML compactado em base64
  • RawJson: JSON bruto retornado pela API

Consultas e emissoes que retornam documento tambem disponibilizam objeto estruturado em Document. Eventos de cancelamento retornam dados estruturados em Event.

Sample Console

O projeto samples/NFSeNacionalSdk.Samples.Console permite testar os fluxos principais por menu.

$env:NFSE_ENVIRONMENT="ProductionRestricted"
$env:NFSE_CERTIFICATE_PATH="C:\caminho\certificado.pfx"
$env:NFSE_CERTIFICATE_PASSWORD="senha-do-certificado"

dotnet run --project "samples\NFSeNacionalSdk.Samples.Console\NFSeNacionalSdk.Samples.Console.csproj" --configuration Release

O menu possui opcao para emissao por JSON. O template fica em:

samples/NFSeNacionalSdk.Samples.Console/emit-dps.request.template.json

Parametrizacao Municipal

Antes de emitir, consulte:

  • convenio municipal: GetMunicipalConventionAsync
  • aliquota por municipio/servico/competencia: GetMunicipalServiceParametersAsync

Essas consultas ajudam a identificar casos em que o municipio nao esta ativo no ambiente nacional ou em que a aliquota deve ser omitida/informada conforme parametrizacao.

Empacotamento

Gerar pacotes locais:

dotnet clean
dotnet restore
dotnet build --configuration Release
dotnet test --configuration Release --no-build
dotnet pack --configuration Release --no-build --output artifacts/packages

Publicar no NuGet:

dotnet nuget push "artifacts/packages/*.nupkg" --source https://api.nuget.org/v3/index.json --api-key <NUGET_API_KEY>

Para sobrescrever a versao no pack:

dotnet pack --configuration Release --no-build --output artifacts/packages -p:Version=0.2.0

Para a preview 0.2.0:

dotnet pack --configuration Release --no-build --output artifacts/packages -p:Version=0.2.0-preview.1

Release pelo GitHub Actions

O workflow .github/workflows/release.yml publica os pacotes no NuGet usando Trusted Publishing.

Configuracao necessaria no GitHub:

  • Environment: release
  • Environment variable: NUGET_USER com o username do perfil no nuget.org, nao o e-mail
  • Secrets: nenhum, quando Trusted Publishing estiver configurado
  • Deployment branches and tags: selecione tags v* para releases por tag; adicione tambem a branch main apenas se quiser permitir publicacao manual pelo botao do GitHub Actions
  • Required reviewers: recomendado para evitar publicacao acidental

Configuracao necessaria no nuget.org:

  • Trusted Publishing apontando para este repositorio
  • Workflow file: release.yml
  • Environment: release

Publicar por tag:

git tag v0.2.0-preview.1
git push origin v0.2.0-preview.1

Ou execute manualmente o workflow Release NuGet no GitHub e informe a versao, por exemplo 0.2.0-preview.1. Para esse modo manual, a branch usada na execucao precisa estar permitida nas regras do Environment.

Estrutura

src/
  NFSeNacionalSdk.Core
  NFSeNacionalSdk.Contracts
  NFSeNacionalSdk.Serialization.Xml
  NFSeNacionalSdk.Transport.Http
  NFSeNacionalSdk

tests/
  NFSeNacionalSdk.Tests

samples/
  NFSeNacionalSdk.Samples.Console

Referencias Tecnicas

Contribuicao

Leia CONTRIBUTING.md antes de abrir issues ou pull requests.

Commits

Use Conventional Commits:

  • feat: add nfse cancellation events
  • fix: parse nfse taxation values
  • docs: update release instructions
  • build: add nuget package metadata
  • test: cover municipal parameter lookup

Licenca

MIT.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.2.0-preview.2 249 5/11/2026
0.2.0-preview.1 75 5/6/2026
0.1.0-preview.1 72 4/29/2026

Preview with netstandard2.0 compatibility for .NET Framework consumers, direct SDK factories, dependency injection registration, certificate file options, standardized response metadata, structured NFS-e parsing, and NFS-e cancellation event registration.