Skip to content

hetsahk/sdk-afip-arca

Repository files navigation

@arca-sdk/core

TypeScript License: MIT npm version

TypeScript SDK for AFIP/ARCA electronic invoicing in Argentina. Handles WSAA authentication, WSFEv1 domestic invoicing, WSFEXv1 export invoicing, CUIT validation, certificate management, and tax calculations -- all with full type safety and zero configuration pain.


Features

  • WSAA Authentication -- Token management with automatic caching, disk persistence, cooldown enforcement, and mutex-based concurrency control
  • Domestic Invoicing (WSFEv1) -- Create, authorize, and query invoices (Factura A, B, C, M) with auto-numbering and batch support (up to 9998)
  • Export Invoicing (WSFEXv1) -- Factura E, export credit/debit notes, Incoterms validation, shipping permits, multi-currency
  • Tax Calculations -- Precise IVA calculations using Decimal.js, invoice amount reconciliation, perceptions, withholdings
  • CUIT Validation -- Checksum verification, prefix classification (persona fisica/juridica), formatting
  • Certificate Management -- CSR generation, PEM/PKCS#12 loading, certificate expiry monitoring, key pair verification
  • Invoice Validation -- Pre-flight validation of all AFIP fields before network submission (RG 5616 compliant)
  • Fluent Builders -- InvoiceBuilder and ExportInvoiceBuilder with automatic amount calculation and reconciliation
  • Parameter Queries -- Invoice types, currency rates, IVA rates, countries, incoterms, and more -- fetched live from AFIP
  • CLI Tool -- Interactive command-line interface for configuration, invoicing, and queries
  • REST API -- Ready-to-deploy HTTP server with API key authentication, CORS, and full CRUD operations

Quick Start

Installation

# npm
npm install @arca-sdk/core

# bun
bun add @arca-sdk/core

# pnpm
pnpm add @arca-sdk/core

Validate a CUIT

import { validate_cuit } from "@arca-sdk/core";

const result = validate_cuit("20-40937847-2");

if (result.valid) {
  console.log(result.data.formatted); // "20-40937847-2"
  console.log(result.data.type);      // "persona_fisica_m"
} else {
  console.error(result.errors);       // [{ code, field, message }]
}

Authenticate with WSAA

import { WSAA } from "@arca-sdk/core";

const wsaa = new WSAA({
  cert: "./certs/certificate.crt",    // PEM string or file path
  key: "./certs/private.key",         // PEM string or file path
  cuit: "20409378472",
  environment: "homologacion",        // "homologacion" | "production"
  tokenCachePath: "./.arca-tokens.json", // optional disk persistence
});

// Get auth credentials for WSFEv1 (cached automatically)
const auth = await wsaa.getAuthCredentials("wsfe");
// { Token: "...", Sign: "...", Cuit: "20409378472" }

Create and Authorize a Domestic Invoice

import { WSAA, InvoicingService, InvoiceBuilder } from "@arca-sdk/core";

const wsaa = new WSAA({
  cert: "./cert.crt",
  key: "./private.key",
  cuit: "20409378472",
  environment: "homologacion",
});

const invoicing = new InvoicingService({
  cuit: "20409378472",
  environment: "homologacion",
  getAuth: () => wsaa.getAuthCredentials("wsfe"),
});

const detail = new InvoiceBuilder()
  .setConcept(1)                        // 1=Products, 2=Services, 3=Both
  .setRecipient(80, 30712345678, 1)     // DocTipo=CUIT, DocNro, CondIVA=RI
  .setDates("20260307")
  .setCurrency("PES", 1)
  .setInvoiceNumber(0, 0)              // 0 = auto-number
  .addItem({
    description: "Software development",
    quantity: 1,
    unitPrice: 100000,
    ivaRateId: 5,                       // 5 = 21% IVA
  })
  .calculateAmounts()                   // auto-compute IVA and totals
  .build();

const result = await invoicing.createInvoice(1, 6, detail); // PtoVta=1, CbteTipo=6 (Factura B)

if (result.success) {
  console.log("CAE:", result.cae);
  console.log("Vto CAE:", result.caeExpiration);
  console.log("Invoice #:", result.invoiceNumber);
}

Modules

Module Import Path Description
Validation @arca-sdk/core/validation CUIT validation, invoice field validation, date utilities
Cert @arca-sdk/core/cert CSR generation, certificate/key loading, PKCS#12, expiry monitoring
Auth @arca-sdk/core/auth WSAA authentication, token caching, TRA/CMS signing
Tax @arca-sdk/core/tax IVA calculations, invoice amounts, perceptions, withholdings
Invoicing @arca-sdk/core/invoicing WSFEv1 domestic invoicing (Factura A/B/C/M)
Export @arca-sdk/core/export WSFEXv1 export invoicing (Factura E)

Each module can be imported individually for tree-shaking:

import { validate_cuit } from "@arca-sdk/core/validation";
import { WSAA } from "@arca-sdk/core/auth";
import { calculateIVA } from "@arca-sdk/core/tax";
import { InvoicingService, InvoiceBuilder } from "@arca-sdk/core/invoicing";
import { ExportService, ExportInvoiceBuilder } from "@arca-sdk/core/export";

Or import everything from the root:

import { WSAA, InvoiceBuilder, InvoicingService, validate_cuit, calculateIVA } from "@arca-sdk/core";

CLI

The SDK includes an interactive CLI tool for common operations.

# Configure CUIT, certificate, and environment (creates .arcarc file)
arca init

# Check configuration and AFIP service health
arca status

# Create and authorize an invoice (interactive wizard)
arca factura

# Query invoices
arca consultar ultimo          # Last authorized invoice number
arca consultar comprobante     # Look up a specific invoice

# Validate a CUIT
arca validar-cuit 20409378472

Run directly with Bun:

bun run src/cli/index.ts init
bun run src/cli/index.ts factura
bun run src/cli/index.ts validar-cuit 20409378472

REST API

The SDK provides a ready-to-deploy HTTP server built on Bun.serve().

Start the server

export ARCA_CUIT="20409378472"
export ARCA_CERT_PATH="./cert.crt"
export ARCA_KEY_PATH="./private.key"
export ARCA_ENV="homo"            # "homo" or "prod"
export ARCA_API_KEY="your-secret" # optional, secures all endpoints except /health
export ARCA_PORT="3000"           # default: 3000

bun run src/api/server.ts

Available endpoints

Method Path Description
GET /health Health check (no auth required)
POST /auth/login Get WSAA authentication token
POST /facturas Create domestic invoice
GET /facturas/ultima Last authorized invoice number
GET /facturas/:tipo/:puntoVenta/:numero Query specific invoice
POST /facturas/exportacion Create export invoice
GET /facturas/exportacion/ultima Last export invoice number
GET /parametros/monedas List currencies
GET /parametros/tipos-comprobante List invoice types
GET /parametros/tipos-documento List document types
GET /parametros/alicuotas-iva List IVA rates
GET /validar-cuit/:cuit Validate a CUIT

See REST API Reference for complete documentation with request/response examples and curl commands.


Requirements

  • Runtime: Node.js 18+ or Bun 1.0+
  • TypeScript: 5.9+
  • AFIP Certificate: You need a valid certificate issued by AFIP. See the AFIP Setup Guide for step-by-step instructions.

Documentation


Error Handling

Every module has its own typed error class and error code enum:

Module Error Class Code Enum
cert CertError CERT_ERROR_CODE
auth WSAAError WSAA_ERROR_CODE
invoicing InvoicingError INVOICING_ERROR_CODE
export ExportError EXPORT_ERROR_CODE
tax TaxError TAX_ERROR_CODE
import { InvoicingError, INVOICING_ERROR_CODE } from "@arca-sdk/core";

try {
  await invoicing.createInvoice(1, 1, detail);
} catch (err) {
  if (err instanceof InvoicingError) {
    console.error(err.code, err.message);
    // err.code is a value from INVOICING_ERROR_CODE
  }
}

Environments

Value WSAA WSFEv1 WSFEXv1
"homologacion" wsaahomo.afip.gov.ar wswhomo.afip.gov.ar wswhomo.afip.gov.ar
"production" wsaa.afip.gov.ar servicios1.afip.gov.ar servicios1.afip.gov.ar

Certificates issued for homologacion do NOT work against production endpoints and vice versa.


Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feat/my-feature
  3. Make your changes with tests
  4. Run the test suite: bun run test
  5. Run type checking: bun run typecheck
  6. Commit using conventional commits: git commit -m "feat: add new feature"
  7. Push and open a Pull Request

License

MIT

About

SDK TypeScript para facturación electrónica AFIP/ARCA (Argentina). CLI + REST API + npm package. Zero dependencies on Java or Python.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors