Fiscalapi 4.0.120

dotnet add package Fiscalapi --version 4.0.120                
NuGet\Install-Package Fiscalapi -Version 4.0.120                
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="Fiscalapi" Version="4.0.120" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Fiscalapi --version 4.0.120                
#r "nuget: Fiscalapi, 4.0.120"                
#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.
// Install Fiscalapi as a Cake Addin
#addin nuget:?package=Fiscalapi&version=4.0.120

// Install Fiscalapi as a Cake Tool
#tool nuget:?package=Fiscalapi&version=4.0.120                

FiscalAPI SDK para .NET

NuGet License

SDK oficial de FiscalAPI para .NET, la API de facturación CFDI y otros servicios fiscales en México. Simplifica la integración con los servicios de facturación electrónica, eliminando las complejidades del SAT y facilitando la generación de facturas, notas de crédito, complementos de pago, nómina, carta porte, y más. ¡Factura sin dolor!

🚀 Características

  • Soporte completo para CFDI 4.0
  • Compatible con múltiples versiones de .NET (desde .NET Framework 4.6.1 hasta .NET 8)
  • Operaciones asíncronas y sincrónicas
  • Dos modos de operación: Por valores o Por referencias
  • Manejo simplificado de errores
  • Búsqueda en catálogos del SAT
  • Documentación completa y ejemplos prácticos

📦 Instalación

NuGet Package Manager:

NuGet\Install-Package Fiscalapi

.NET CLI:

dotnet add package Fiscalapi

⚙️ Configuración

Puedes usar el SDK tanto en aplicaciones sin inyección de dependencias (WinForms, Consolas, WPF, etc.) como en proyectos que usan DI (ASP.NET Core, Blazor, etc.). A continuación se describen ambas formas:

A) Aplicaciones sin Inyección de Dependencias

  1. Crea tu objeto de configuración con tus credenciales:

    var settings = new FiscalApiOptions
    {
        ApiUrl = "https://test.fiscalapi.com", // https://live.fiscalapi.com (producción)
        ApiKey = "<tu_api_key>",
        Tenant = "<tenant>"
    };
    
  2. Crea la instancia del cliente:

    var fiscalApi = FiscalApiClient.Create(settings);
    

Para ejemplos completos, consulta winforms-console.


B) Aplicaciones con Inyección de Dependencias (ASP.NET, Blazor, etc.)

  1. Agrega la sección de configuración en tu appsettings.json:

    {
      "FiscalapiSettings": {
        "ApiUrl": "https://test.fiscalapi.com", // https://live.fiscalapi.com (producción)
        "ApiKey": "<YourApiKeyHere>",
        "Tenant": "<YourTenantHere>"
      }
    }
    
  2. Registra los servicios en el contenedor (por ejemplo, en Program.cs):

    builder.Services.AddFiscalApi();
    

Posteriormente, podrás inyectar IFiscalApiClient donde lo requieras:

public class InvoicesController : Controller
{
    private readonly IFiscalApiClient _fiscalApi;

    public InvoicesController(IFiscalApiClient fiscalApi)
    {
        _fiscalApi = fiscalApi;
    }
    
    // Usa _fiscalApi en tus métodos de controlador...
}

Para más ejemplos, revisa samples-asp-net.

🔄 Modos de Operación

FiscalAPI admite dos modos de operación:

  • Por Referencias: Envía solo IDs de objetos previamente creados en el dashboard de FiscalAPI.
    Ideal para integraciones ligeras.

  • Por Valores: Envía todos los campos requeridos en cada petición, con mayor control sobre los datos.
    No se requiere configuración previa en el dashboard.

📝 Ejemplos de Uso

A continuación se muestran algunos ejemplos básicos para ilustrar cómo utilizar el SDK. Puedes encontrar más ejemplos en la documentación oficial.

1. Crear una Persona (Emisor o Receptor)

var fiscalApi = FiscalApiClient.Create(Settings);

var request = new Person
{
    LegalName = "Persona de Prueba",
    Email = "someone@somewhere.com",
    Password = "YourStrongPassword123!",
};

var apiResponse = await fiscalApi.Persons.CreateAsync(request);

2. Subir Certificados CSD

var fiscalApi = FiscalApiClient.Create(Settings);

var certificadoCsd = new TaxFile
{
    PersonId = "984708c4-fcc0-43bd-9d30-ec017815c20e",
    Base64File = "MIIFsDCCA5igAwIBAgI...==", // Certificado .cer codificado en Base64
    FileType = FileType.CertificateCsd,
    Password = "12345678a",
    Tin = "EKU9003173C9"
};

var clavePrivadaCsd = new TaxFile
{
    PersonId = "984708c4-fcc0-43bd-9d30-ec017815c20e",
    Base64File = "MIIFDjBABgkqhkiG9w0BBQ0...==", // Llave privada .key codificada en Base64
    FileType = FileType.PrivateKeyCsd,
    Password = "12345678a",
    Tin = "EKU9003173C9"
};

var apiResponseCer = await fiscalApi.TaxFiles.CreateAsync(certificadoCsd);
var apiResponseKey = await fiscalApi.TaxFiles.CreateAsync(clavePrivadaCsd);

3. Crear un Producto o Servicio

var fiscalApi = FiscalApiClient.Create(Settings);

var request = new Product
{
    Description = "Servicios contables",
    UnitPrice = 100,
    SatUnitMeasurementId = "E48",
    SatTaxObjectId = "02",
    SatProductCodeId = "84111500"
};

var apiResponse = await fiscalApi.Products.CreateAsync(request);

4. Actualizar Impuestos de un Producto

var fiscalApi = FiscalApiClient.Create(Settings);

var request = new Product
{
    Id = "310301b3-1ae9-441b-b463-51a8f9ca8ba2",
    Description = "Servicios contables",
    UnitPrice = 100, 
    SatUnitMeasurementId = "E48",
    SatTaxObjectId = "02",
    SatProductCodeId = "84111500",
    ProductTaxes = new List<ProductTax>
    {
        new ProductTax { Rate = 0.16m, TaxId = "002", TaxFlagId = "T", TaxTypeId = "Tasa" },  // IVA 16%
        new ProductTax { Rate = 0.10m, TaxId = "001", TaxFlagId = "R", TaxTypeId = "Tasa" },  // ISR 10%
        new ProductTax { Rate = 0.10666666666m, TaxId = "002", TaxFlagId = "R", TaxTypeId = "Tasa" } // IVA 2/3 partes
    }
};

var apiResponse = await fiscalApi.Products.UpdateAsync(request.Id, request);

5. Crear una Factura de Ingreso (Por Referencias)

var fiscalApi = FiscalApiClient.Create(Settings);

var invoice = new Invoice
{
    VersionCode = "4.0",
    Series = "SDK-F",
    Date = DateTime.Now,
    PaymentFormCode = "01",
    CurrencyCode = "MXN",
    TypeCode = "I",
    ExpeditionZipCode = "42501",
    Issuer = new InvoiceIssuer
    {
        Id = "<id-emisor-en-fiscalapi>"
    },
    Recipient = new InvoiceRecipient
    {
        Id = "<id-receptor-en-fiscalapi>"
    },
    Items = new List<InvoiceItem>
    {
        new InvoiceItem
        {
            Id = "<id-producto-en-fiscalapi>",
            Quantity = 1,
            Discount = 10.85m
        }
    },
    PaymentMethodCode = "PUE",
};

var apiResponse = await fiscalApi.Invoices.CreateAsync(invoice);

6. Crear la Misma Factura de Ingreso (Por Valores)

var fiscalApi = FiscalApiClient.Create(settings);

// Agregar sellos CSD, Emisor, Receptor, Items, etc.
var invoice = new Invoice
{
    VersionCode = "4.0",
    Series = "SDK-F",
    Date = DateTime.Now,
    PaymentFormCode = "01",
    CurrencyCode = "MXN",
    TypeCode = "I",
    ExpeditionZipCode = "42501",
    Issuer = new InvoiceIssuer
    {
        Tin = "EKU9003173C9",
        LegalName = "ESCUELA KEMPER URGATE",
        TaxRegimeCode = "601",
        TaxCredentials  = new List<TaxCredential>()
         {
             new TaxCredential
             {
                 Base64File ="certificate_base64...",
                 FileType = FileType.CertificateCsd,
                 Password = "12345678a"
             },
             new TaxCredential
             {
                 Base64File ="private_key_base64...",
                 FileType = FileType.PrivateKeyCsd,
                 Password = "12345678a"
             }
         }
    },
    Recipient = new InvoiceRecipient
    {
        Tin = "EKU9003173C9",
        LegalName = "ESCUELA KEMPER URGATE",
        ZipCode = "42501",
        TaxRegimeCode = "601",
        CfdiUseCode = "G01",
        Email = "someone@somewhere.com"
    },
    Items = new List<InvoiceItem>
    {
        new InvoiceItem
        {
            ItemCode = "01010101",
            Quantity = 9.5m,
            UnitOfMeasurementCode = "E48",
            Description = "Invoicing software as a service",
            UnitPrice = 3587.75m,
            TaxObjectCode = "02",
            Discount = 255.85m,
            ItemTaxes = new List<InvoiceItemTax>
            {
                new InvoiceItemTax
                {
                    TaxCode = "002", // IVA
                    TaxTypeCode = "Tasa",
                    TaxRate = 0.16m,
                    TaxFlagCode = "T"
                }
            }
        }
    },
    PaymentMethodCode = "PUE",
};

var apiResponse = await fiscalApi.Invoices.CreateAsync(invoice);

7. Búsqueda en Catálogos del SAT

// Busca los registros que contengan 'inter' en el catalogo 'SatUnitMeasurements' (pagina 1, tamaño pagina 10)
var apiResponse = await fiscalApi.Catalogs.SearchCatalogAsync("SatUnitMeasurements", "inter", 1, 10);

if (apiResponse.Succeeded)
{
    foreach (var item in apiResponse.Data.Items)
    {
        Console.WriteLine($"Unidad: {item.Description}");
    }
}
else
{
    Console.WriteLine(apiResponse.Message);
}

⏳ Operaciones Asíncronas y Sincrónicas

  • Asíncrono:
    var apiResponse = await fiscalApi.Invoices.GetByIdAsync(<id>);
    
  • Sincrónico (use esto solo en .NET Framework 4.X.X)
    var apiResponse = Task.Run(async () => await fiscalApi.Invoices.GetByIdAsync(<id>)).Result;
    

📋 Operaciones Principales

  • Facturas (CFDI)
    Crear facturas de ingreso, notas de crédito, complementos de pago, cancelaciones, generación de PDF/XML.
  • Personas (Clientes/Emisores)
    Alta y administración de personas, gestión de certificados (CSD).
  • Productos y Servicios
    Administración de catálogos de productos, búsqueda en catálogos SAT.

🤝 Contribuir

  1. Haz un fork del repositorio.
  2. Crea una rama para tu feature: git checkout -b feature/AmazingFeature.
  3. Realiza commits de tus cambios: git commit -m 'Add some AmazingFeature'.
  4. Sube tu rama: git push origin feature/AmazingFeature.
  5. Abre un Pull Request en GitHub.

🐛 Reportar Problemas

  1. Asegúrate de usar la última versión del SDK.
  2. Verifica si el problema ya fue reportado.
  3. Proporciona un ejemplo mínimo reproducible.
  4. Incluye los mensajes de error completos.

📄 Licencia

Este proyecto está licenciado bajo la Licencia MPL. Consulta el archivo LICENSE para más detalles.

🔗 Enlaces Útiles


Desarrollado con ❤️ por Fiscalapi

Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  net6.0 is compatible.  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. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 is compatible. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 is compatible.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 is compatible.  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
4.0.120 47 2/16/2025
4.0.104 61 2/8/2025
4.0.96 67 1/29/2025
4.0.95 76 1/19/2025
4.0.94 62 1/18/2025
4.0.87 69 1/8/2025