// Documentos electrónicos
Crear factura
Emite una factura electrónica de venta. La API valida, calcula los totales, numera, firma y la envía a la DIAN.
/api/v1/invoicesEn esta página
Antes de empezar
Necesitas el billing_account_id de la cuenta que emite y el establishment_id de su sede: los obtienes en Tu organización y cuentas. Si eres un software con muchos clientes, el billing_account_id es el del cliente a cuyo nombre sale la factura.
La API calcula todos los totales (subtotal, descuentos, impuestos, retenciones y total) a partir de cantidades, precios y tarifas. Si tu sistema calcula distinto por centavos, manda la diferencia en rounding_amount.
Headers
| Header | Obligatorio | Valor |
|---|---|---|
nestfac-api-key |
Sí | Tu API key. Ver Autenticación. |
nestfac-idempotency-key |
Sí | Un valor único por factura, por ejemplo el id de tu venta. Ver Idempotencia. |
Content-Type |
Sí | application/json |
Ejemplo
Factura de contado a una empresa: dos gaseosas y un servicio con 10 % de descuento, todo con IVA del 19 %.
curl -X POST "https://api-sandbox.nestfac.co/api/v1/invoices" \
-H "nestfac-api-key: $NESTFAC_API_KEY" \
-H "nestfac-idempotency-key: ORD-1042-factura" \
-H "Content-Type: application/json" \
-d '{
"billing_account_id": "3f6c2a9e-5b1d-4c7e-9a2f-8d1e0b4c6a71",
"establishment_id": "a2d4f6b8-1c3e-4a5b-9d7f-0e2c4b6a8d10",
"operation_type": "10",
"invoice_type_code": "01",
"currency_code": "COP",
"reference": "ORD-1042",
"note": "Pedido web ORD-1042",
"customer": {
"document_identity_type_code": "31",
"document_identification_number": "900123456",
"dv": "8",
"legal_name": "Cliente de Prueba S.A.S.",
"email": "facturacion@cliente-prueba.co",
"phone": "3001234567",
"legal_organization_type_code": "1",
"tax_regime_code": "48",
"responsibilities": [
"O-13"
],
"address": {
"country_code": "CO",
"line_1": "Calle 10 # 5-20",
"municipality_code": "41001"
}
},
"payments": [
{
"payment_form_code": "1",
"payment_method_code": "10"
}
],
"items": [
{
"code_reference": "GAS-350-UVA",
"name": "Gaseosa uva 350 ml",
"quantity": 2,
"unit_measure_code": "94",
"unit_price": 3500,
"standard_code": {
"id": "7702004003508",
"scheme": "010"
},
"taxes": [
{
"tax_code": "01",
"percent": 19
}
]
},
{
"code_reference": "SRV-INST",
"name": "Servicio de instalación",
"quantity": 1,
"unit_measure_code": "94",
"unit_price": 12000,
"discount_percent": 10,
"taxes": [
{
"tax_code": "01",
"percent": 19
}
]
}
]
}'// Node.js 18+ (fetch nativo). Corre en TU servidor: la API key nunca va al navegador.
const body = {
"billing_account_id": "3f6c2a9e-5b1d-4c7e-9a2f-8d1e0b4c6a71",
"establishment_id": "a2d4f6b8-1c3e-4a5b-9d7f-0e2c4b6a8d10",
"operation_type": "10",
"invoice_type_code": "01",
"currency_code": "COP",
"reference": "ORD-1042",
"note": "Pedido web ORD-1042",
"customer": {
"document_identity_type_code": "31",
"document_identification_number": "900123456",
"dv": "8",
"legal_name": "Cliente de Prueba S.A.S.",
"email": "facturacion@cliente-prueba.co",
"phone": "3001234567",
"legal_organization_type_code": "1",
"tax_regime_code": "48",
"responsibilities": [
"O-13"
],
"address": {
"country_code": "CO",
"line_1": "Calle 10 # 5-20",
"municipality_code": "41001"
}
},
"payments": [
{
"payment_form_code": "1",
"payment_method_code": "10"
}
],
"items": [
{
"code_reference": "GAS-350-UVA",
"name": "Gaseosa uva 350 ml",
"quantity": 2,
"unit_measure_code": "94",
"unit_price": 3500,
"standard_code": {
"id": "7702004003508",
"scheme": "010"
},
"taxes": [
{
"tax_code": "01",
"percent": 19
}
]
},
{
"code_reference": "SRV-INST",
"name": "Servicio de instalación",
"quantity": 1,
"unit_measure_code": "94",
"unit_price": 12000,
"discount_percent": 10,
"taxes": [
{
"tax_code": "01",
"percent": 19
}
]
}
]
};
const res = await fetch("https://api-sandbox.nestfac.co/api/v1/invoices", {
method: "POST",
headers: {
"nestfac-api-key": process.env.NESTFAC_API_KEY,
"nestfac-idempotency-key": "ORD-1042-factura",
"Content-Type": "application/json",
},
body: JSON.stringify(body),
});
const json = await res.json();
if (!res.ok) throw new Error(`${json.code ?? res.status}: ${json.message ?? JSON.stringify(json.errors)}`);
console.log(json.data);import os
import requests
payload = {
"billing_account_id": "3f6c2a9e-5b1d-4c7e-9a2f-8d1e0b4c6a71",
"establishment_id": "a2d4f6b8-1c3e-4a5b-9d7f-0e2c4b6a8d10",
"operation_type": "10",
"invoice_type_code": "01",
"currency_code": "COP",
"reference": "ORD-1042",
"note": "Pedido web ORD-1042",
"customer": {
"document_identity_type_code": "31",
"document_identification_number": "900123456",
"dv": "8",
"legal_name": "Cliente de Prueba S.A.S.",
"email": "facturacion@cliente-prueba.co",
"phone": "3001234567",
"legal_organization_type_code": "1",
"tax_regime_code": "48",
"responsibilities": ["O-13"],
"address": {
"country_code": "CO",
"line_1": "Calle 10 # 5-20",
"municipality_code": "41001",
},
},
"payments": [
{
"payment_form_code": "1",
"payment_method_code": "10",
},
],
"items": [
{
"code_reference": "GAS-350-UVA",
"name": "Gaseosa uva 350 ml",
"quantity": 2,
"unit_measure_code": "94",
"unit_price": 3500,
"standard_code": {
"id": "7702004003508",
"scheme": "010",
},
"taxes": [
{
"tax_code": "01",
"percent": 19,
},
],
},
{
"code_reference": "SRV-INST",
"name": "Servicio de instalación",
"quantity": 1,
"unit_measure_code": "94",
"unit_price": 12000,
"discount_percent": 10,
"taxes": [
{
"tax_code": "01",
"percent": 19,
},
],
},
],
}
res = requests.post(
"https://api-sandbox.nestfac.co/api/v1/invoices",
headers={
"nestfac-api-key": os.environ["NESTFAC_API_KEY"],
"nestfac-idempotency-key": "ORD-1042-factura",
},
json=payload,
timeout=30,
)
data = res.json()
if not res.ok:
raise RuntimeError(f"{data.get('code', res.status_code)}: {data.get('message') or data.get('errors')}")
print(data["data"])<?php
$payload = [
'billing_account_id' => '3f6c2a9e-5b1d-4c7e-9a2f-8d1e0b4c6a71',
'establishment_id' => 'a2d4f6b8-1c3e-4a5b-9d7f-0e2c4b6a8d10',
'operation_type' => '10',
'invoice_type_code' => '01',
'currency_code' => 'COP',
'reference' => 'ORD-1042',
'note' => 'Pedido web ORD-1042',
'customer' => [
'document_identity_type_code' => '31',
'document_identification_number' => '900123456',
'dv' => '8',
'legal_name' => 'Cliente de Prueba S.A.S.',
'email' => 'facturacion@cliente-prueba.co',
'phone' => '3001234567',
'legal_organization_type_code' => '1',
'tax_regime_code' => '48',
'responsibilities' => ['O-13'],
'address' => [
'country_code' => 'CO',
'line_1' => 'Calle 10 # 5-20',
'municipality_code' => '41001',
],
],
'payments' => [
[
'payment_form_code' => '1',
'payment_method_code' => '10',
],
],
'items' => [
[
'code_reference' => 'GAS-350-UVA',
'name' => 'Gaseosa uva 350 ml',
'quantity' => 2,
'unit_measure_code' => '94',
'unit_price' => 3500,
'standard_code' => [
'id' => '7702004003508',
'scheme' => '010',
],
'taxes' => [
[
'tax_code' => '01',
'percent' => 19,
],
],
],
[
'code_reference' => 'SRV-INST',
'name' => 'Servicio de instalación',
'quantity' => 1,
'unit_measure_code' => '94',
'unit_price' => 12000,
'discount_percent' => 10,
'taxes' => [
[
'tax_code' => '01',
'percent' => 19,
],
],
],
],
];
$ch = curl_init('https://api-sandbox.nestfac.co/api/v1/invoices');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => [
'nestfac-api-key: ' . getenv('NESTFAC_API_KEY'),
'nestfac-idempotency-key: ORD-1042-factura',
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE),
]);
$response = json_decode(curl_exec($ch), true);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status >= 400) {
throw new RuntimeException(($response['code'] ?? $status) . ': ' . ($response['message'] ?? json_encode($response['errors'] ?? null)));
}
print_r($response['data']);// .NET 7+
using System.Net.Http;
using System.Text;
using var http = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://api-sandbox.nestfac.co/api/v1/invoices");
request.Headers.Add("nestfac-api-key", Environment.GetEnvironmentVariable("NESTFAC_API_KEY"));
request.Headers.Add("nestfac-idempotency-key", "ORD-1042-factura");
var json = """
{
"billing_account_id": "3f6c2a9e-5b1d-4c7e-9a2f-8d1e0b4c6a71",
"establishment_id": "a2d4f6b8-1c3e-4a5b-9d7f-0e2c4b6a8d10",
"operation_type": "10",
"invoice_type_code": "01",
"currency_code": "COP",
"reference": "ORD-1042",
"note": "Pedido web ORD-1042",
"customer": {
"document_identity_type_code": "31",
"document_identification_number": "900123456",
"dv": "8",
"legal_name": "Cliente de Prueba S.A.S.",
"email": "facturacion@cliente-prueba.co",
"phone": "3001234567",
"legal_organization_type_code": "1",
"tax_regime_code": "48",
"responsibilities": [
"O-13"
],
"address": {
"country_code": "CO",
"line_1": "Calle 10 # 5-20",
"municipality_code": "41001"
}
},
"payments": [
{
"payment_form_code": "1",
"payment_method_code": "10"
}
],
"items": [
{
"code_reference": "GAS-350-UVA",
"name": "Gaseosa uva 350 ml",
"quantity": 2,
"unit_measure_code": "94",
"unit_price": 3500,
"standard_code": {
"id": "7702004003508",
"scheme": "010"
},
"taxes": [
{
"tax_code": "01",
"percent": 19
}
]
},
{
"code_reference": "SRV-INST",
"name": "Servicio de instalación",
"quantity": 1,
"unit_measure_code": "94",
"unit_price": 12000,
"discount_percent": 10,
"taxes": [
{
"tax_code": "01",
"percent": 19
}
]
}
]
}
""";
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await http.SendAsync(request);
var result = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode) throw new Exception($"{(int)response.StatusCode}: {result}");
Console.WriteLine(result);// Java 15+ (java.net.http)
import java.net.URI;
import java.net.http.*;
String json = """
{
"billing_account_id": "3f6c2a9e-5b1d-4c7e-9a2f-8d1e0b4c6a71",
"establishment_id": "a2d4f6b8-1c3e-4a5b-9d7f-0e2c4b6a8d10",
"operation_type": "10",
"invoice_type_code": "01",
"currency_code": "COP",
"reference": "ORD-1042",
"note": "Pedido web ORD-1042",
"customer": {
"document_identity_type_code": "31",
"document_identification_number": "900123456",
"dv": "8",
"legal_name": "Cliente de Prueba S.A.S.",
"email": "facturacion@cliente-prueba.co",
"phone": "3001234567",
"legal_organization_type_code": "1",
"tax_regime_code": "48",
"responsibilities": [
"O-13"
],
"address": {
"country_code": "CO",
"line_1": "Calle 10 # 5-20",
"municipality_code": "41001"
}
},
"payments": [
{
"payment_form_code": "1",
"payment_method_code": "10"
}
],
"items": [
{
"code_reference": "GAS-350-UVA",
"name": "Gaseosa uva 350 ml",
"quantity": 2,
"unit_measure_code": "94",
"unit_price": 3500,
"standard_code": {
"id": "7702004003508",
"scheme": "010"
},
"taxes": [
{
"tax_code": "01",
"percent": 19
}
]
},
{
"code_reference": "SRV-INST",
"name": "Servicio de instalación",
"quantity": 1,
"unit_measure_code": "94",
"unit_price": 12000,
"discount_percent": 10,
"taxes": [
{
"tax_code": "01",
"percent": 19
}
]
}
]
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api-sandbox.nestfac.co/api/v1/invoices"))
.header("nestfac-api-key", System.getenv("NESTFAC_API_KEY"))
.header("nestfac-idempotency-key", "ORD-1042-factura")
.header("Content-Type", "application/json")
.method("POST", HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 400) throw new RuntimeException(response.body());
System.out.println(response.body());package main
import (
"fmt"
"io"
"net/http"
"os"
"strings"
)
func main() {
body := `{
"billing_account_id": "3f6c2a9e-5b1d-4c7e-9a2f-8d1e0b4c6a71",
"establishment_id": "a2d4f6b8-1c3e-4a5b-9d7f-0e2c4b6a8d10",
"operation_type": "10",
"invoice_type_code": "01",
"currency_code": "COP",
"reference": "ORD-1042",
"note": "Pedido web ORD-1042",
"customer": {
"document_identity_type_code": "31",
"document_identification_number": "900123456",
"dv": "8",
"legal_name": "Cliente de Prueba S.A.S.",
"email": "facturacion@cliente-prueba.co",
"phone": "3001234567",
"legal_organization_type_code": "1",
"tax_regime_code": "48",
"responsibilities": [
"O-13"
],
"address": {
"country_code": "CO",
"line_1": "Calle 10 # 5-20",
"municipality_code": "41001"
}
},
"payments": [
{
"payment_form_code": "1",
"payment_method_code": "10"
}
],
"items": [
{
"code_reference": "GAS-350-UVA",
"name": "Gaseosa uva 350 ml",
"quantity": 2,
"unit_measure_code": "94",
"unit_price": 3500,
"standard_code": {
"id": "7702004003508",
"scheme": "010"
},
"taxes": [
{
"tax_code": "01",
"percent": 19
}
]
},
{
"code_reference": "SRV-INST",
"name": "Servicio de instalación",
"quantity": 1,
"unit_measure_code": "94",
"unit_price": 12000,
"discount_percent": 10,
"taxes": [
{
"tax_code": "01",
"percent": 19
}
]
}
]
}`
req, _ := http.NewRequest("POST", "https://api-sandbox.nestfac.co/api/v1/invoices", strings.NewReader(body))
req.Header.Set("nestfac-api-key", os.Getenv("NESTFAC_API_KEY"))
req.Header.Set("nestfac-idempotency-key", "ORD-1042-factura")
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer res.Body.Close()
out, _ := io.ReadAll(res.Body)
fmt.Println(res.StatusCode, string(out))
}// La API key NUNCA va en el navegador. React llama a TU backend,
// que agrega la key y la llave de idempotencia (pestaña Node.js).
async function enviar(datos) {
const res = await fetch("/api/nestfac/invoices", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(datos),
});
const json = await res.json();
if (!res.ok) throw new Error(json.message ?? json.code);
return json.data;
}
// const resultado = await enviar(datosDeLaVenta);Respuesta
La API responde 202 Accepted cuando la factura quedó validada, numerada y en cola para la DIAN:
{
"success": true,
"message": "Invoice received",
"data": {
"invoice_id": "627eecb4-365d-4ee6-a7eb-ebf742c27389",
"status": "PENDING"
}
}202 no significa que la DIAN la aceptó. Guarda el invoice_id y consulta la factura: en segundos pasa a ACCEPTED o REJECTED. Ver Ciclo de vida.
Cada respuesta trae el header X-Request-Id. Inclúyelo cuando escribas a soporte.
Campos del documento
Body
- billing_account_idstring (uuid)obligatorio
La cuenta (NIT) que emite. Con una key global puede ser cualquier cuenta de tu organización; con una key de cuenta, solo la suya.
- establishment_idstring (uuid)obligatorio si no envías numbering_range_id
Establecimiento que emite. De él se toma la numeración. Envía este o
numbering_range_id.- numbering_range_idstring (uuid)
Rango de numeración específico, si el establecimiento tiene varios.
- operation_typestringobligatorio
Tipo de operación (tabla DIAN 13.1.5). La mayoría de las ventas son
10.10 Estándar09 AIU11 Mandatos12 Transporte- invoice_type_codestringobligatorio
Tipo de factura (tabla DIAN 13.1.3).
01 Venta02 Exportación03 Contingencia- currency_codestringobligatoriopor defecto
COP Moneda ISO 4217. Para otra moneda, envía también
foreign_payment.- referencestring
Tu referencia (número de pedido, id de venta). Sirve para buscar la factura después.
- notestring
Nota general del documento (aparece en el PDF).
- rounding_amountnumberpor defecto
0 Ajuste de redondeo al total, con signo. Úsalo solo si tu total difiere por centavos del calculado.
Cliente
customer
- document_identity_type_codestringobligatorio
Tipo de documento (tabla DIAN 13.2.1).
13 Cédula31 NIT22 Cédula de extranjería12 Tarjeta de identidad41 Pasaporte42 Doc. extranjero50 NIT de otro país- document_identification_numberstringobligatorio
Número de documento. Con NIT, solo dígitos y sin DV: si lo envías con puntos o guion, la API los limpia.
- dvstring
Dígito de verificación del NIT. Si no lo envías, la API lo calcula; si lo envías y no corresponde, responde
CUSTOMER_DV_DOES_NOT_MATCH_NIT.- legal_namestringobligatorio
Razón social o nombre completo, como aparece en el RUT.
- trade_namestring
- Nombre comercial.
- emailstring
Correo donde el cliente recibe la factura. Muy recomendado.
- phonestring
- Teléfono.
- legal_organization_type_codestring
Tipo de persona.
1 Persona jurídica2 Persona natural- tax_regime_codestring
Régimen de IVA del cliente.
48 Responsable de IVA49 No responsable de IVA- responsibilitiesstring[]
Responsabilidades fiscales del RUT (casilla 53). Si no tiene ninguna,
["R-99-PN"].O-13O-15O-23O-47R-99-PN- addressobject
Dirección del cliente.
- country_codestringobligatorio
- País ISO 3166 (
CO,US,EC…). - municipality_codestringobligatorio si el país es CO y no es consumidor final
Código DANE de 5 dígitos del municipio (
41001= Neiva). La DIAN saca de aquí la ciudad y el departamento.- line_1stringobligatorio si el país no es CO
- Dirección.
- postal_codestring
- Código postal.
Consumidor final
Cuando el comprador no pide la factura a su nombre, factúrale a consumidor final: cédula 222222222222, persona natural, no responsable de IVA, y la dirección solo con country_code. Este es el body mínimo completo:
{
"billing_account_id": "3f6c2a9e-5b1d-4c7e-9a2f-8d1e0b4c6a71",
"establishment_id": "a2d4f6b8-1c3e-4a5b-9d7f-0e2c4b6a8d10",
"operation_type": "10",
"invoice_type_code": "01",
"currency_code": "COP",
"customer": {
"document_identity_type_code": "13",
"document_identification_number": "222222222222",
"legal_name": "Consumidor final",
"legal_organization_type_code": "2",
"tax_regime_code": "49",
"responsibilities": ["R-99-PN"],
"address": { "country_code": "CO" }
},
"payments": [
{ "payment_form_code": "1", "payment_method_code": "10" }
],
"items": [
{
"code_reference": "ITEM-001",
"name": "Gaseosa de uva",
"quantity": 1,
"unit_measure_code": "94",
"unit_price": 4500,
"taxes": [{ "tax_code": "01", "percent": 19 }]
},
{
"code_reference": "ITEM-002",
"name": "Pan tajado",
"quantity": 1,
"unit_measure_code": "94",
"unit_price": 14200,
"taxes": [{ "tax_code": "01", "percent": 19 }]
}
]
}Pagos
payments[]
- payment_form_codestringobligatorio
Forma de pago.
1 Contado2 Crédito- payment_method_codestringobligatorio
Medio de pago. Lista completa en Medios y formas de pago.
10 Efectivo20 Cheque31 Transferencia débito42 Consignación45 Transferencia crédito47 Transferencia débito bancaria48 Tarjeta crédito49 Tarjeta débitoZZZ Otro- amountnumber
No hace falta enviarlo. Un pago sin
allocationssiempre se registra por el total a pagar de la factura (el total menos los anticipos), así que tu sistema no tiene que calcularlo.- due_daysnumberobligatorio a crédito
Plazo en días. La API calcula la fecha de vencimiento desde la emisión.
- referencestring
- Referencia del pago (voucher, transferencia, consignación).
- allocationsarray
Para pagar de contado con varios medios (parte en efectivo y parte con tarjeta). Cada uno con
payment_method_code,amountyreferenceopcional. La suma debe ser igual al total a pagar. Un pago a crédito no puede llevarallocations.
A crédito
"payments": [
{
"payment_form_code": "2",
"payment_method_code": "45",
"due_days": 30
}
]Varios medios de pago
"payments": [
{
"payment_form_code": "1",
"payment_method_code": "10",
"allocations": [
{ "payment_method_code": "10", "amount": 10000 },
{ "payment_method_code": "48", "amount": 11182, "reference": "VOUCHER-8812" }
]
}
]Ítems
items[]
- namestringobligatoriomáx. 300
Nombre del producto o servicio. Es la descripción principal en la factura.
- code_referencestringmáx. 50
Tu código interno (SKU). También se acepta como
sku.- descriptionstringmáx. 300
Detalle adicional (segunda descripción en la factura).
- quantitynumberobligatoriomayor a 0 · máx. 4 decimales
Cantidad, en la unidad de
unit_measure_code.- unit_measure_codestringpor defecto
94 Unidad de medida de la tabla DIAN:
94unidad,KGMkilogramo,LTRlitro,HURhora,PKpaquete,BXcaja… Ver Unidades de medida.- unit_pricenumberobligatoriomáx. 4 decimales
Precio unitario antes de impuestos.
- discount_percentnumber0 a 100
Descuento de la línea, en porcentaje.
- taxesarray
Impuestos de la línea, cada uno con
tax_codeypercent:01IVA (0,5,19),04INC (8). Un producto excluido de IVA va contaxes: []; uno exento va con IVA0.- withholding_taxesarray
Retenciones que te practica el cliente, con
tax_codeypercent:05ReteIVA,06ReteRenta,07ReteICA.- standard_codeobject
Código estándar del artículo, con
idyscheme. Esquemas:010código de barras GTIN (se valida el dígito de control),001UNSPSC (8 dígitos),020partida arancelaria (10 dígitos),999código propio.- pack_sizenumber
- Unidades por empaque (un six-pack = 6).
- propertiesarraymáx. 20
Características del artículo:
nameyvalue(lote, vencimiento, talla, color, placa…).- notestring
- Nota de la línea.
- brand_namestringobligatorio en exportación (02)máx. 100
- Marca.
- model_namestringobligatorio en exportación (02)máx. 100
- Modelo.
- aiu_componentstringobligatorio en AIU (09)
- Ver AIU.
- transportobjectobligatorio en transporte (12)
- Ver Transporte de carga.
{
"code_reference": "MAN-PK6",
"name": "Gaseosa manzana x6",
"description": "Botella retornable",
"quantity": 1,
"unit_measure_code": "94",
"unit_price": 35500,
"discount_percent": 10,
"standard_code": { "id": "7701234000011", "scheme": "010" },
"pack_size": 6,
"properties": [
{ "name": "Lote", "value": "L-2291" },
{ "name": "Vence", "value": "2027-03-01" }
],
"note": "Producto de temporada",
"brand_name": "Marca Ejemplo",
"taxes": [{ "tax_code": "01", "percent": 19 }],
"withholding_taxes": [{ "tax_code": "06", "percent": 2.5 }]
}Operaciones especiales
En estos ejemplos se omiten billing_account_id, establishment_id, currency_code y customer: van igual que en una factura normal.
AIU (09)
Contratos de obra o servicios con Administración, Imprevistos y Utilidad. Envía operation_type: "09", el objeto aiu y el componente de cada ítem.
aiu.concept: objeto del contrato (máx. 300).aiu.regime: sobre qué se cobra el IVA.PROFIT_BASE: IVA solo sobre la utilidad. Los demás componentes van contaxes: [].AIU_BASE: IVA sobre administración, imprevistos y utilidad. El costo directo va sin IVA.
- Debe haber al menos un
COST, unaADMINISTRATIONy unaPROFIT.UNFORESEEN(imprevistos) es opcional, máximo uno.
{
"operation_type": "09",
"invoice_type_code": "01",
"aiu": {
"concept": "Construcción de muro de contención en bodega",
"regime": "PROFIT_BASE"
},
"payments": [
{ "payment_form_code": "1", "payment_method_code": "10" }
],
"items": [
{ "code_reference": "AIU-COSTO", "name": "Costo directo", "quantity": 1, "unit_price": 10000000,
"aiu_component": "COST", "taxes": [] },
{ "code_reference": "AIU-ADM", "name": "Administración 10 %", "quantity": 1, "unit_price": 1000000,
"aiu_component": "ADMINISTRATION", "taxes": [] },
{ "code_reference": "AIU-IMP", "name": "Imprevistos 5 %", "quantity": 1, "unit_price": 500000,
"aiu_component": "UNFORESEEN", "taxes": [] },
{ "code_reference": "AIU-UTIL", "name": "Utilidad 5 %", "quantity": 1, "unit_price": 500000,
"aiu_component": "PROFIT", "taxes": [{ "tax_code": "01", "percent": 19 }] }
]
}{
"operation_type": "09",
"invoice_type_code": "01",
"aiu": {
"concept": "Construcción de muro de contención bodega 3",
"regime": "AIU_BASE"
},
"payments": [
{ "payment_form_code": "1", "payment_method_code": "42",
"reference": "Consignación N-1289" }
],
"items": [
{ "code_reference": "AIU-COSTO", "name": "Costo directo", "quantity": 1, "unit_price": 10000000,
"aiu_component": "COST", "taxes": [] },
{ "code_reference": "AIU-ADM", "name": "Administración 10 %", "quantity": 1, "unit_price": 1000000,
"aiu_component": "ADMINISTRATION", "taxes": [{ "tax_code": "01", "percent": 19 }] },
{ "code_reference": "AIU-IMP", "name": "Imprevistos 5 %", "quantity": 1, "unit_price": 500000,
"aiu_component": "UNFORESEEN", "taxes": [{ "tax_code": "01", "percent": 19 }] },
{ "code_reference": "AIU-UTIL", "name": "Utilidad 5 %", "quantity": 1, "unit_price": 500000,
"aiu_component": "PROFIT", "taxes": [{ "tax_code": "01", "percent": 19 }] }
]
}Mandatos (11)
Cuando facturas a nombre de un tercero (el mandante). Envía operation_type: "11" y en cada ítem el objeto mandate con el documento del mandante. Con NIT (31), mandate_dv es opcional: si no lo envías, la API lo calcula.
{
"operation_type": "11",
"invoice_type_code": "01",
"payments": [
{ "payment_form_code": "1", "payment_method_code": "10" }
],
"items": [
{
"code_reference": "ITEM-001",
"name": "Gaseosa cola 350 ml",
"quantity": 2,
"unit_measure_code": "94",
"unit_price": 3200,
"taxes": [{ "tax_code": "01", "percent": 19 }],
"mandate": {
"mandate_identity_type_code": "31",
"mandate_id": "860025900",
"mandate_dv": "2"
}
}
]
}Transporte de carga (12)
Fletes del transporte de carga por carretera. Envía operation_type: "12" y en cada ítem el objeto transport. Cada línea es una remesa registrada en el RNDC o un servicio adicional que no está incluido en el flete (cargue, descargue, bodegaje…).
- Remesa (
registration_code: "1"): llevarndc_filing_number(radicado del RNDC, solo números, de 1 a 100.000 millones),remittance_number(número de la remesa, hasta 15 letras o números),quantity(cantidad transportada, entera) yunit(KGMkilogramos oGLLgalones). El valor del flete sale del subtotal de la línea; para fijarlo aparte, envíafreight_value(entero, sin decimales). - Servicio adicional (
registration_code: "0"): no lleva datos de remesa.
El transporte de carga nacional suele ir excluido de IVA (taxes: []); un servicio adicional sí puede causarlo. Las properties del ítem no se usan aquí: la DIAN reserva esas tres propiedades para los datos de la remesa.
{
"operation_type": "12",
"invoice_type_code": "01",
"payments": [
{ "payment_form_code": "1", "payment_method_code": "10" }
],
"items": [
{
"code_reference": "FLETE-001",
"name": "Flete Bogotá – Neiva, carga seca",
"quantity": 1,
"unit_measure_code": "94",
"unit_price": 2500000,
"taxes": [],
"transport": {
"registration_code": "1",
"rndc_filing_number": "6589568",
"remittance_number": "REM01212",
"quantity": 24350,
"unit": "KGM"
}
},
{
"code_reference": "ADIC-001",
"name": "Cargue y descargue de mercancía",
"quantity": 1,
"unit_measure_code": "94",
"unit_price": 250000,
"taxes": [{ "tax_code": "01", "percent": 19 }],
"transport": { "registration_code": "0" }
}
]
}Exportación (02)
Con invoice_type_code: "02", cada ítem debe llevar brand_name y model_name. Si facturas en otra moneda, envía currency_code y foreign_payment.
"items": [
{
"name": "Café verde excelso",
"quantity": 70,
"unit_measure_code": "KGM",
"unit_price": 38.5,
"brand_name": "Finca El Mirador",
"model_name": "Excelso EP 15"
}
]Contingencia (03)
Para facturas que emitiste en papel cuando no pudiste facturar electrónicamente. Cada documento en references.additional_references debe llevar su issue_date.
Campos opcionales
- adjustmentsarray
Descuentos o cargos sobre el total (no por línea):
type_code,is_charge,reasonypercentoamount.01es siempre descuento (is_charge: false) y03siempre cargo (is_charge: true).- prepaymentsarray
Anticipos ya recibidos:
paid_amountyreceived_date(AAAA-MM-DD). Se descuentan del valor a pagar.- foreign_paymentobject
Factura en moneda extranjera:
currency_code,total_for_currency,exchange_rate(TRM) yexchange_rate_date. Los valores van como texto decimal sin comas:"3425.95".- referencesobject
Documentos relacionados:
order_reference(orden de compra),despatch_references(remisiones),receipt_references(actas de recibo) yadditional_references. Losidadmiten máx. 20 caracteres y las fechas van en AAAA-MM-DD.- invoice_periodobject
Periodo facturado, para servicios recurrentes:
start_dateyend_date.- deliveryobject
Entrega y transportador: fecha, dirección de entrega y datos fiscales del transportador.
- delivery_termsobject
Condiciones de entrega (Incoterms):
loss_risk_responsibility_code(FOB,CIF…) yspecial_terms.- extensionsobject
Datos adicionales:
observation(observación en el PDF),seller_code(vendedor) ytax_representative(persona autorizada).- integrationobject
Trazabilidad de tu sistema:
source,terminal_id,session_id,request_id,correlation_id,device_id,operator_id. No se envía a la DIAN.
Errores frecuentes
| Código | Causa |
|---|---|
ESTABLISHMENT_ID_OR_NUMBERING_RANGE_ID_IS_REQUIRED |
No indicaste el establecimiento. |
INVALID_OPERATION_TYPE |
operation_type no está en la tabla DIAN. |
CUSTOMER_DV_DOES_NOT_MATCH_NIT |
El DV no corresponde al NIT. Omítelo y la API lo calcula. |
PAYMENTS[0].INVALID_PAYMENT_METHOD_CODE |
Medio de pago fuera de la tabla DIAN. |
CREDIT_PAYMENT_REQUIRES_DUE_DAYS |
Pago a crédito sin due_days. |
PAYMENT_ALLOCATIONS_TOTAL_INVALID |
La suma de allocations no es igual al total a pagar. |
CREDIT_PAYMENT_CANNOT_HAVE_ALLOCATIONS |
Un pago a crédito con allocations. |
ITEMS[0].QUANTITY_MAX_4_DECIMALS |
Más de 4 decimales en la cantidad (lo mismo aplica al precio). |
ITEMS[0].BRAND_NAME_IS_REQUIRED_FOR_EXPORT |
Exportación sin marca o modelo. |
AIU_ADMINISTRATION_ITEM_IS_REQUIRED |
Factura AIU sin ítem de administración. |
La lista completa y el formato de error están en Errores.
// Revisado contra la API el 24 de octubre de 2026.