> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cufea.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Quickstart

> From nothing to a signed, accepted sandbox invoice and a verified webhook.

From nothing to a signed, accepted sandbox invoice and a verified webhook. Everything here runs
against the **sandbox**: Cufea's simulated DIAN. It needs no certificate, no RUT and no DIAN
habilitación, and nothing reaches a real DIAN endpoint.

You will:

1. get a sandbox API key from the developer console;
2. register a webhook endpoint;
3. create and send an invoice;
4. follow its status, by polling or by webhook;
5. verify the webhook signature.

Every endpoint is in the [API reference](https://docs.cufea.com/en/api-reference/introduction.md), generated from the
same OpenAPI document the API serves at `https://api.cufea.com/openapi.json`.

## Before you start

You need nothing installed but `curl`. The commands below use these two variables:

```sh theme={null}
export CUFEA=https://api.cufea.com        # the API base URL
export CUFEA_KEY=cufea_sandbox_...        # your sandbox key, from step 1
```

## 1. Get a sandbox key

Open the developer console at [app.cufea.com/signup](https://app.cufea.com/signup) and sign
up with an email and a password. You get a sandbox tenant, and the console asks you to verify
your email before anything else: open the link it emails you, then log in again.

Once verified, choose **Create your sandbox API key** on the dashboard to get a first
`cufea_sandbox_` key. **The key is shown once**: copy it into `CUFEA_KEY` now. More keys can
be issued, and revoked, on the console's **Keys** page.

Check it. `/v1/tenant` answers for any valid key:

```sh theme={null}
curl -s "$CUFEA/v1/tenant" -H "Authorization: Bearer $CUFEA_KEY"
```

```json theme={null}
{"tenant_id":"4b976379-cf1e-4679-a56a-c5be3d4436f1","stage":"sandbox","dian_environment":"test"}
```

A missing or wrong key answers `401`; every error is `application/problem+json`:

```json theme={null}
{"type":"urn:cufea:problem:unauthorized","title":"Unauthorized","status":401,
 "code":"unauthorized","detail":"Missing or invalid API key.",
 "request_id":"3668a7374b1e4314b2f932a5620da1f1"}
```

The sandbox is configured for you (a generated certificate and a numbering range with series
`SBX`); `GET /v1/tenant/configuration` shows `"ready_to_invoice":true`.

## 2. Register a webhook endpoint

Webhooks tell you when the DIAN answered, so you do not have to poll. The endpoint must be an
`https` URL on a public host name: `localhost` and private addresses are refused. To receive
on your machine, expose it through an HTTPS tunnel of your choice.

```sh theme={null}
export WEBHOOK_URL=https://hooks.example.com/cufea
curl -s -X POST "$CUFEA/v1/tenant/webhooks" \
  -H "Authorization: Bearer $CUFEA_KEY" -H "Content-Type: application/json" \
  -d "{\"url\":\"$WEBHOOK_URL\",\"event_types\":[]}"
```

```json theme={null}
{"id":"1526a4ef-0812-424c-b413-cc645415a617","url":"https://hooks.example.com/cufea",
 "event_types":[],"active":true,"created_at":"2026-11-15T01:37:52.317407Z",
 "secret":"..."}
```

An empty `event_types` subscribes to every type: `invoice.accepted`, `invoice.rejected`,
`note.accepted`, `note.rejected` and `event.registered`. **`secret` is shown once**; keep it
where your receiver can read it, for step 5. The console's **Webhooks** page does the same and
lists the latest deliveries.

## 3. Create and send an invoice

One request creates the invoice, signs it, stores it and, with `"send": true`, queues it for the
DIAN. This one is a cash sale of one service with 19% IVA to a company customer:

```sh theme={null}
curl -si -X POST "$CUFEA/v1/invoices" \
  -H "Authorization: Bearer $CUFEA_KEY" -H "Content-Type: application/json" \
  -H "Idempotency-Key: order-1001" \
  -d '{
    "customer": {"organization_type": "1", "id_type": "31", "id_number": "800197268",
      "check_digit": "4", "registration_name": "Acme S.A.S.", "tax_scheme": "01",
      "fiscal_responsibilities": ["O-13"],
      "address": {"line": "Cra 7 # 1-10", "city_code": "11001", "city_name": "Bogota, D.C.",
                  "department_code": "11", "department_name": "Bogota"}},
    "lines": [{"description": "Service", "quantity": "1", "unit_price": "100000",
               "taxes": [{"scheme": "01", "percent": "19"}]}],
    "payments": [{"form": "1", "method_code": "10"}],
    "reference": "ORDER-1001",
    "send": true}'
```

The answer is `201 Created` with a `Location: /v1/invoices/SBX1` header:

```json theme={null}
{"kind":"invoice","document_id":"SBX1","reference":"ORDER-1001","number":1,"prefix":"SBX",
 "cufe":"0b7bb53e...","issue_datetime":"2026-11-14T20:37:52.369143-05:00",
 "state":"prepared","dian_status_code":null,"dian_status_description":null,
 "dian_errors":[],"sent_at":null,
 "totals":{"line_extension":"100000.00","tax_exclusive":"100000.00",
           "tax_inclusive":"119000.00","allowance_total":"0.00","charge_total":"0.00",
           "payable":"119000.00","rounding":"0.00"},
 "taxes":[{"scheme":"01","name":"IVA","percent":"19.00","taxable_amount":"100000.00",
           "tax_amount":"19000.00","is_excluded":false}],
 "withholdings":[],
 "lines":[{"line_id":1,"description":"Service","item_code":null,"quantity":"1",
           "unit_code":"94","unit_price":"100000.00","gross_amount":"100000.00",
           "discount_rate":"0.00","discount_amount":"0.00","net_amount":"100000.00",
           "taxes":[{"scheme":"01","name":"IVA","percent":"19.00",
                     "taxable_amount":"100000.00","tax_amount":"19000.00",
                     "is_excluded":false}],"is_excluded":false}],
 "qr":{"content":"https://catalogo-vpfe-hab.dian.gov.co/document/searchqr?documentkey=0b7bb53e...",
       "url":null},
 "payments":[{"form":"1","method_code":"10","due_date":null,"amount":null}],
 "xml_base64":"PD94bWwg...","send":"queued"}
```

* `document_id` is the series and the number: `SBX1` for a new tenant's first invoice.
* `totals`, `taxes`, `withholdings`, `lines` and `qr` are what the signed XML says, read from
  it: print your receipt from them. `qr.content` is the value to encode in the printed QR.
* `payments` lists one entry per means of payment, in order: a sale paid with cash and a card
  sends two (see [Payments](https://docs.cufea.com/en/guides/payments.md)).
* `xml_base64` is the signed UBL XML, yours to keep.
* `send: queued` means a worker will send it; the state stays `prepared` until then.
* **`Idempotency-Key` makes retries safe.** If the answer is lost, repeat the exact request:
  you get the stored answer (with `Idempotent-Replayed: true`) and no second number is taken.
  Reusing a key with a different body answers `422` (`idempotency_key_reused`).
  `GET /v1/documents?kind=invoice&reference=ORDER-1001` also tells you whether an invoice with
  your `reference` exists.

### Line taxes: taxed, exempt and excluded

Each line lists its taxes. A retail catalog usually needs these five:

| Item | `taxes` |
| - | - |
| IVA 19% | `[{"scheme": "01", "percent": "19"}]` |
| IVA 5% | `[{"scheme": "01", "percent": "5"}]` |
| IVA exento (exempt) | `[{"scheme": "01", "percent": "0"}]` |
| Excluido de IVA | `[{"is_excluded": true}]` |
| INC 8% | `[{"scheme": "04", "percent": "8"}]` |

An exempt item is IVA at 0%: the XML informs IVA with `0.00`, and its value counts in the
taxable base (`TaxExclusiveAmount`). An excluded item takes no scheme and no rate: the XML
informs no IVA for that line (Anexo 1.9, FAX01 and FAX05) and its value stays out of the
taxable base (FAU04). An excluded entry may sit next to another tax such as INC, but not next
to an IVA entry, and it never carries `scheme` or `percent`; those requests answer `422`.
A line with an empty `taxes` list produces the same XML as an excluded one.

```json theme={null}
"lines": [
  {"description": "Arroz", "quantity": "2", "unit_price": "3000",
   "taxes": [{"is_excluded": true}]},
  {"description": "Huevos", "quantity": "10", "unit_price": "500",
   "taxes": [{"scheme": "01", "percent": "0"}]}
]
```

### Customers without full fiscal data

Only the identification and the name of an identified buyer are required. Without
`fiscal_responsibilities` the buyer gets `["R-99-PN"]`, without `tax_scheme` it gets `ZZ`,
and without `address` the XML leaves out the buyer's `PhysicalLocation` and
`RegistrationAddress` (both optional in the Anexo 1.9, FAK07 and FAK28). Send the address
when the sale happens outside your premises: FAK07 requires it then.

```json theme={null}
{"organization_type": "2", "id_type": "13", "id_number": "1020304050",
 "registration_name": "Ana Perez", "email": "ana@example.com"}
```

For an anonymous buyer send `"kind": "final_consumer"` and nothing else (an `email` and an
`address` are optional). Cufea fills the consumidor final party the Anexo prescribes:
natural person, id type `13`, id `222222222222`, name `consumidor final`, `R-99-PN` and `ZZ`.

```json theme={null}
{"kind": "final_consumer"}
```

### Line discounts

A line takes an optional discount, as a percentage (`discount_rate`) or an amount
(`discount_amount`): decimal strings with at most two decimals, one or the other, never both
(`422 validation_error`). The amount cannot exceed `quantity` x `unit_price` and the rate
cannot exceed `100` (`422 invoice_invalid`). The line value is `quantity` x `unit_price` minus
the discount, and its taxes apply to that discounted value. The XML carries the discount as a
line `AllowanceCharge` (Anexo 1.9, FBE01-FBE09); `AllowanceTotalAmount` stays `0.00`, since it
only sums document-level discounts. Note lines accept the same fields.

```json theme={null}
{"lines": [
  {"description": "Laptop", "quantity": "2", "unit_price": "100000", "discount_rate": "10",
   "taxes": [{"scheme": "01", "percent": "19"}]},
  {"description": "Mouse", "quantity": "1", "unit_price": "50000", "discount_amount": "5000.00",
   "taxes": [{"scheme": "01", "percent": "19"}]}]}
```

The laptop line is worth `180000.00` with `34200.00` of IVA; the mouse line is worth
`45000.00` with `8550.00` of IVA.

Without `"send": true`, send it later with `POST /v1/invoices/SBX1/send`, which answers `202`.
A body that is not valid answers `422` with the offending fields and never echoes your values:

```json theme={null}
{"type":"urn:cufea:problem:validation_error","title":"Request validation failed","status":422,
 "code":"validation_error","detail":"The request is not valid; see `errors` for the offending fields.",
 "request_id":"88272d6eb903438690d3193e3113270a",
 "errors":[{"loc":["body","customer"],"msg":"Field required"}]}
```

## 4. Follow the status

Read the invoice back until `state` is final (`accepted` or `rejected`). The sandbox usually
answers within a few seconds:

```sh theme={null}
curl -s "$CUFEA/v1/invoices/SBX1" -H "Authorization: Bearer $CUFEA_KEY"
```

```json theme={null}
{"kind":"invoice","document_id":"SBX1","reference":"ORDER-1001","number":1,"prefix":"SBX",
 "cufe":"0b7bb53e...","issue_datetime":"2026-11-14T20:37:52.369143-05:00",
 "state":"accepted","dian_status_code":"00","dian_status_description":"Procesado Correctamente.",
 "dian_errors":[],"sent_at":"2026-11-15T01:37:55.748083Z",
 "totals":{...},"taxes":[...],"withholdings":[],"lines":[...],
 "qr":{"content":"https://catalogo-vpfe-hab.dian.gov.co/document/searchqr?documentkey=0b7bb53e...",
       "url":"https://catalogo-vpfe-hab.dian.gov.co/document/searchqr?documentkey=0b7bb53e..."},
 "notes":[],
 "delivery":{"status":"skipped","reason":"stage_not_production","recipient":null,"attempts":0,
             "manual":false,"updated_at":"2026-11-15T01:37:56.002144Z"}}
```

`dian_status_code` `00` is the DIAN's "processed correctly", and `qr.url` now links the
document in the DIAN catalog.

`delivery` is the email of the invoice to its buyer. In production Cufea sends it after the
DIAN accepts the invoice; the sandbox never emails anyone, so here it is `skipped`. Download
the PDF with `GET /v1/invoices/SBX1/pdf`, or the email's subject and ZIP with
`GET /v1/invoices/SBX1/email-content`.

A rejection lists the DIAN rules in `dian_errors`. Or let the webhook tell you: when the
state becomes final your endpoint receives

```http theme={null}
POST /cufea HTTP/1.1
Content-Type: application/json
User-Agent: Cufea/1.0
X-Cufea-Event: invoice.accepted
X-Cufea-Delivery: 1d546e53-b150-487c-87a7-689e5c6a17b9
X-Cufea-Signature: t=1794706676,v1=5d0c...

{"created_at":"2026-11-15T01:37:55.751253+00:00","data":{"dian_status_code":"00","document_id":"SBX1","kind":"invoice","reference":"ORDER-1001","stage":"sandbox","state":"accepted"},"id":"94643dee-9c5e-42b3-847a-fe531ab1ff2a","type":"invoice.accepted"}
```

The payload carries ids and DIAN codes only, never customer data: read the invoice back for the
rest. Answer any `2xx` within 10 seconds. No answer, `408`, `429` or `5xx` is retried after 1
min, 5 min, 30 min, 2 h and 6 h; any other status fails the delivery at once. A delivery can
arrive more than once, so deduplicate on the body's `id`.

## 5. Verify the webhook signature

`X-Cufea-Signature` is `t=<unix seconds>,v1=<hex>`. `t` is when this attempt was sent (a retry
is signed again with a fresh `t`), and `v1` is the hex HMAC-SHA256 of `t`, a `.` and the **raw
request body**, keyed with the endpoint's secret. Check it before trusting the body:

* compute it over the bytes exactly as received, before any JSON parsing (re-serializing the
  JSON changes the bytes, and the signature no longer matches);
* compare in constant time;
* reject a `t` more than 300 seconds away from your clock, in either direction: a captured
  request replayed later then fails;
* accept the request when any `v1=` entry matches (several appear while a secret is rotated),
  and ignore keys you do not know.

Python (standard library only):

```python theme={null}
import hashlib
import hmac
import time

TOLERANCE = 300  # seconds


def verify(secret: str, body: bytes, header: str, *, now: float | None = None) -> bool:
    """True when `header` (X-Cufea-Signature) signs the raw `body` and is fresh."""
    timestamp, signatures = None, []
    for item in header.split(","):
        key, _, value = item.strip().partition("=")
        if key == "t" and value.isascii() and value.isdigit():
            timestamp = int(value)
        elif key == "v1":
            signatures.append(value)
    if timestamp is None or not signatures:
        return False
    if abs((time.time() if now is None else now) - timestamp) > TOLERANCE:
        return False
    signed = f"{timestamp}.".encode() + body
    expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(expected, s) for s in signatures)
```

Node.js (no dependencies):

```js theme={null}
const crypto = require("node:crypto");

const TOLERANCE = 300; // seconds

// `body` is the raw request body as a Buffer, `header` the X-Cufea-Signature header.
function verify(secret, body, header, { now = Date.now() / 1000 } = {}) {
  let timestamp = null;
  const signatures = [];
  for (const item of (header ?? "").split(",")) {
    const [key, value = ""] = item.trim().split(/=(.*)/s);
    if (key === "t" && /^\d+$/.test(value)) timestamp = Number(value);
    else if (key === "v1") signatures.push(value);
  }
  if (timestamp === null || signatures.length === 0) return false;
  if (Math.abs(now - timestamp) > TOLERANCE) return false;
  const expected = Buffer.from(
    crypto
      .createHmac("sha256", secret)
      .update(`${timestamp}.`)
      .update(body)
      .digest("hex"),
  );
  return signatures.some((s) => {
    const candidate = Buffer.from(s);
    return (
      candidate.length === expected.length &&
      crypto.timingSafeEqual(candidate, expected)
    );
  });
}
```

Read the raw body in your framework: `await request.body()` in FastAPI or Starlette,
`request.get_data()` in Flask, `express.raw({ type: "application/json" })` in Express. Answer
`401` when `verify` is false.

## Next

* The guides cover what a production client must decide: [customers and DANE
  codes](https://docs.cufea.com/en/guides/customers.md), [series](https://docs.cufea.com/en/guides/numbering.md), [idempotency after 24
  hours](https://docs.cufea.com/en/idempotency.md), [rate limits](https://docs.cufea.com/en/rate-limits.md), [webhook ordering](https://docs.cufea.com/en/webhooks.md),
  [`closed` documents](https://docs.cufea.com/en/guides/closed-documents), [payments](https://docs.cufea.com/en/guides/payments.md) and
  [rounding](https://docs.cufea.com/en/guides/totals.md).
* The TypeScript SDK, [`@cufea/sdk`](https://docs.cufea.com/en/sdk), wraps these steps: typed requests, automatic
  `Idempotency-Key`s, typed errors and `webhooks.verify`.
* The MCP server, [`@cufea/mcp`](https://docs.cufea.com/en/mcp), gives AI agents (Claude Code, Cursor, Codex) these
  steps as tools, against the sandbox.
* `GET /v1/invoices/SBX1/xml` downloads the signed XML, and `POST /v1/notes` issues a
  [credit or debit note](https://docs.cufea.com/en/guides/notes.md) on an accepted invoice. RADIAN events
  (`POST /v1/invoices/{id}/events`) need the buyer to be the issuer itself.
* [From test to production](https://docs.cufea.com/en/production.md) goes from the sandbox to the DIAN test
  environment with your own certificate, and then to production.
* Every request carries an `X-Request-ID` response header, also in each error's `request_id`:
  quote it when something looks wrong (see [Errors](https://docs.cufea.com/en/errors.md)).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.