# SharkPOS API — guide for coding agents

This guide is for the AI agent (Claude Code, Cursor, Copilot, Codex…) that will integrate SharkPOS API into a
system. Read it in full before writing code. The complete contract, field by field, is at
https://api.sharkpos.cl/docs/openapi.yaml (OpenAPI 3.1) and the documentation for people is at https://api.sharkpos.cl/docs (in Spanish).

SharkPOS API receives JSON and issues Chilean electronic tax documents (DTE, Documentos Tributarios Electrónicos) for the SII (Servicio de Impuestos Internos, the Chilean tax authority): it signs the XML, stamps it with
the CAF (Código de Autorización de Folios, the SII's authorization for a range of document numbers, or folios), sends it to the SII and follows its response. Your system never builds XML, never signs and never connects to the SII.

Chilean terms used in this guide: boleta (receipt), factura (invoice), nota de crédito (credit note), nota de débito (debit note), guía de despacho (dispatch guide), folio (the unique number of a document), RUT (Chilean tax ID), carátula (the cover data of a submission to the SII).

## Rules that are not negotiable

1. **Start in the sandbox.** Base URL `https://sandbox.sharkpos.cl`. It never touches the real SII or consumes folios. The
   test API key is requested at https://api.sharkpos.cl/sandbox (it lasts 2 hours, 6 hours or 24 hours, your choice; it is renewed with the same email and the test company is kept for 30 days). The
   contract is identical to production (`https://api.sharkpos.cl`); only the base URL changes. Do not point at
   production while testing: there every document is real with the SII.
2. **The API key goes only in the backend.** Never in a mobile app, the browser or the repository. Read it from an
   environment variable (for example `SHARKPOS_API_KEY`). It is stored as a hash: if it is lost, another one is issued.
3. **The issuer RUT never goes in the body.** It comes from the API key. Each issuer RUT has its own key.
4. **A stable `Idempotency-Key` per sale** on every issuance (8 to 128 characters, required in production).
   Use the sale identifier in your system (`venta-884`, `mesa-12-cuenta-884`), not a new UUID per attempt.
5. **On a network error, 5xx or 429: retry with the same `Idempotency-Key` and the same body.** Never issue again
   with another key to "fix" a timeout or an error: you would duplicate the sale with the SII. On a 429, wait what the
   `Retry-After` header says.
6. **On a 4xx other than 429: do not retry, fix the request.** The `code` is stable; the `message` names the
   field; many responses carry `solution`, ready to show to the user.
7. **Issuing is synchronous and SII acceptance is asynchronous.** The 201 response already carries folio, signed XML and
   timbre (the SII stamp): hand over the receipt at that moment. The SII result arrives minutes later by webhook or in the
   document status. A `queued` or `sent` document is not issued again: you wait.
8. **A `rejected`, `review_required` or `failed` document is not replaced by issuing another one for the same sale.** Show
   the message and contact support (contacto@sharkpos.cl) with the folio.
9. **Amounts in whole pesos, JSON numbers (not text).** RUT as text with a hyphen (`12345678-5`, with or without dots).
   Dates `YYYY-MM-DD`.
10. **Do not invent fields or endpoints.** If something is not in this guide, look for it in the OpenAPI. If it is not there, it
    does not exist: ask the person.

## Authentication

```
Authorization: Bearer <API_KEY>
Content-Type: application/json
Idempotency-Key: <stable sale id>   # on issuances
```

401 `AUTHENTICATION_REQUIRED` / `INVALID_API_KEY`, 403 `API_KEY_EXPIRED` / `API_ACCESS_DISABLED`,
402 `SUBSCRIPTION_EXPIRED` (access returns on payment) / `SANDBOX_TRIAL_EXPIRED` (request another test key).

## Issuing

| Document | Endpoint |
|---|---|
| Taxed boleta 39 / exempt boleta 41 | `POST /api/v1/dte/boleta/emit/` (`document_type`: 39 or 41) |
| Factura 33 | `POST /api/v1/dte/factura/emit/` |
| Exempt factura 34 | `POST /api/v1/dte/factura-exenta/emit/` |
| Credit note 61 | `POST /api/v1/dte/nota-credito/emit/` |
| Debit note 56 | `POST /api/v1/dte/nota-debito/emit/` |
| Dispatch guide 52 | `POST /api/v1/dte/guia-despacho/emit/` |
| Void a guía 52 (SII Res. Ex. 144) | `POST /api/v1/dte/guia-despacho/{dte_id}/void/` |
| Monthly Libro de Guías de Despacho (dispatch guide ledger) | `GET /api/v1/dte/guia-despacho/libro/?period=YYYY-MM` |
| Guía 52 with a folio distributed to a field team | `POST /api/v1/dte/devices/{device_id}/guias/` (register with `POST /api/v1/dte/devices/`, batch with `POST /api/v1/dte/devices/{device_id}/lot/`, `X-Device-Secret` header) |
| Purchase invoice (factura de compra) 46 | `POST /api/v1/dte/factura-compra/emit/` |
| Liquidación-factura 43 (invoice settlement) | `POST /api/v1/dte/liquidacion-factura/emit/` (`items` = settled documents with `doc_type` and `amount`; `commissions` from 1 to 20 with `type` C or O) |
| Export invoice 110 | `POST /api/v1/dte/exportacion/emit/` |
| Export debit note 111 | `POST /api/v1/dte/nota-debito-exportacion/emit/` |
| Export credit note 112 | `POST /api/v1/dte/nota-credito-exportacion/emit/` |
| Boleta 39 / 41 stamped at the register offline | `POST /api/v1/dte/devices/{device_id}/boletas/` (register with `document_type` 39 or 41 and `branch_id`, batch with `POST /api/v1/dte/devices/{device_id}/lot/`, `X-Device-Secret` header) |

Every issuance accepts an optional `branch_id` (see Branches); without it, the document goes out as the casa matriz (head office).

Minimal boleta (prices include VAT; `amount_total` must equal the sum of the lines):

```json
{
  "document_type": 39,
  "amount_total": 16980,
  "medio_pago": 1,
  "items": [
    {"name": "Ñoquis a la boloñesa", "qty": 1, "price": 8990},
    {"name": "Café cortado", "qty": 2, "price": 3995}
  ]
}
```

Factura, notes and guías are business-to-business documents: they require `receptor_rut`, `receptor_name`, `receptor_giro` (the recipient's line of business),
`receptor_direccion` and `receptor_comuna` (municipality), and reject the final-consumer RUT 66666666-6
(`CONSUMIDOR_FINAL_NOT_ALLOWED`). On the factura, `price` is net unless you send `prices_include_iva: true`.
Credit and debit notes carry the reference to the document they correct: `ref_document_type`, `ref_folio`,
`ref_date`, `ref_code` (1 cancels, 2 corrects text, 3 corrects amounts) and `ref_reason`. A boleta is cancelled with a credit
note.

201 response: `dte_id`, `folio`, `dte_status: "SIGNED"`, `xml_data` (base64), `idempotency_replayed` and `links`
(`status`, `pdf`, `xml`, `ted`, `ted_png`). Factura, notes and guías also carry `pdf_data` (base64); if they carry
`pdf_error`, the document is still valid: download the PDF later from `links.pdf` and never issue it again.

The boleta PDF (`GET /api/v1/dte/boleta/{dte_id}/pdf/?paper_width=58|80`) can carry the business logo and a
message under the total: `PUT /api/v1/dte/boleta/branding/` with `logo` (PNG, JPEG or WebP in base64, up to 1 MB; `null`
removes it) and/or `message` (up to 200 characters and 3 lines). With `"print_receptor_address": true` it also prints,
under the customer's name, the `receptor_direccion` and `receptor_comuna` you send when issuing (if you do not send them, nothing
is printed; it is off by default). Only the fields sent are changed; `GET` shows it and `DELETE` removes it.
Configure it once per RUT, not on every issuance.

Responses when repeating the same `Idempotency-Key`: 200 with the same document (`idempotency_replayed: true`);
202 `processing` if the original is still in progress (wait and repeat); 409 with the failure `code` if the original
failed; 409 `IDEMPOTENCY_CONFLICT` if you changed the body (a logic error in your system).

## Following the SII result

**Webhooks** are recommended. Register the URL once with `POST /api/v1/dte/webhooks/` (a platform with
several RUTs uses `POST /api/v1/partner/webhooks/` and receives those of all of them). The `secret` is shown only once.

- Verify the signature (Standard Webhooks, HMAC-SHA256) over the **raw body**, before parsing the JSON, and
  reject timestamps more than 5 minutes off. Libraries exist: `npm install standardwebhooks`,
  `pip install standardwebhooks`.
- Respond 2xx in under 10 seconds; store the event and process it in the background.
- Deduplicate by the `webhook-id` header (delivery is "at least once") and do not assume order.
- `data.idempotency_key` is the same key you issued with: use it to find the sale.
- `environment` is `production` or `certification` (sandbox): never mix environments.

Main events: `dte.sent`, `dte.accepted`, `dte.accepted_with_repair`, `dte.rejected`,
`dte.review_required`, `dte.failed`, `caf.folios_low`, `caf.folios_exhausted`, `certificate.expiring`,
`certificate.expired`. The current list is at `GET /api/v1/dte/webhooks/event-types/`.

If instead of webhooks you poll `GET /api/v1/dte/documents/<dte_id>/`, do it with increasing waits (30 s, 1 min,
2 min…) and stop when `is_final` is `true`. Build the logic on `public_status`, `is_final` and
`requires_attention`, not on `dte_status`:

| `public_status` | Final | What to do |
|---|---|---|
| `preparing`, `queued`, `sent` | No | Wait. Sending and querying the SII are automatic. |
| `accepted` | Yes | Done. |
| `accepted_with_repair` | Yes | Valid, with SII observations. Show them. |
| `rejected`, `review_required`, `failed` | Yes | Do not issue another for the same sale. Notify and contact support with the folio. |

## Reconciling: list and period totals

`GET /api/v1/dte/documents/` lists the RUT's documents so you can reconcile with your system. Filters: `period`
(`YYYY-MM`) or `from`/`to` (issue dates), `document_type` and `status` (repeatable or comma-separated;
`pending` = preparing, queued and sent), `branch_id` (UUID or `main` for the casa matriz), `folio_from`/`folio_to`,
`updated_after` (incremental sync; orders by `updated_at,id`) and `limit` (1 to 500, default 100).
Cursor pagination: while `has_more` is `true`, request `next` as-is (or repeat with
`cursor=<next_cursor>`); a new document lands at the end and never shifts a page. Each document carries `id`,
`document_type`, `folio`, `issue_date`, `created_at`, `updated_at`, `amounts` (`net`, `exempt`, `iva`, `retained_iva`,
`other_taxes`, `non_billable`, `commissions`, `total`; always `net + exempt + iva + other_taxes - retained_iva + non_billable - commissions = total`, all read from the signed XML:
`retained_iva` is the withheld VAT, all the VAT on the purchase invoice 46 and its notes; `non_billable` is the
non-billable amount of a boleta, items with `ind_exe` 2 or 6; both are 0 on other documents; `other_taxes` are the additional and specific taxes per product, minus the construction-company credit; `commissions` are the commissions of a liquidación-factura 43),
`receptor_rut`, `receptor_name`, `status`, `dte_status`, `sii` (`track_id`, `status`; never the SII XML),
`branch_id` (`null` = casa matriz), `device_id`, `offline` and `links`.

`GET /api/v1/dte/documents/summary/` gives counts and amounts (`count`, `net`, `exempt`, `iva`, `retained_iva`, `non_billable`, `total`) for the period (`period` or `from`+`to` required,
maximum 366 days, same filters) in `totals`, `by_type`, `by_status`, `by_type_and_status` and `by_branch`. Credit
notes (61) add up as positive: subtract them when reconciling sales. Both work with the read-only key and even if the RUT has been deactivated, expired or suspended. Platforms have the same per RUT at
`/api/v1/partner/tenants/{tenant_id}/documents/` and `/api/v1/partner/tenants/{tenant_id}/documents/summary/`.

## Frequent errors

Every error is JSON: `{"status": "error", "code": "...", "message": "...", "solution": "..."}`. The `message` and `solution` texts are in Spanish; the `code` is stable.

| HTTP | `code` | What to do |
|---|---|---|
| 400 | `INVALID_REQUEST`, `INVALID_RECEPTOR_RUT` | Fix the field `message` points to. |
| 400 | `IDEMPOTENCY_KEY_REQUIRED` | Send `Idempotency-Key`. |
| 403 | `EMISSION_NOT_CONTRACTED` | The document type is not enabled for that RUT. Do not retry. |
| 403 | `OFFLINE_NOT_CONTRACTED` | The branch does not have offline mode active (it is enabled in the dashboard, Mis RUT). Do not retry. |
| 403 | `TENANT_SUSPENDED_BY_PARTNER` | The platform suspended the RUT's issuing. Do not retry; querying and downloading still work. |
| 403 | `PLAN_NOT_INCLUDED` | The RUT does not have Herramientas de gestión (management tools: purchase mailbox, RCV and others). Do not retry. |
| 409 | `FOLIO_ALREADY_USED`, `FOLIO_NOT_IN_DEVICE_LOT` | Offline register: repeated folio or one from another register. If it is a retry, use the same key. |
| 422 | `TED_MISMATCH` | The printed timbre does not match the boleta sent: send the same data that was stamped. |
| 409 | `FOLIOS_EXHAUSTED` | No folios. With automatic folios, retry in a few minutes with the same key. |
| 409 | `IDEMPOTENCY_CONFLICT` | Same key with another body: review the sales logic. |
| 429 | `RATE_LIMIT_EXCEEDED`, `EMISSION_RATE_LIMIT_EXCEEDED` | Wait `Retry-After` and repeat with the same key. |
| 500 | `FOLIO_ALLOCATION_FAILED`, `INTERNAL_ERROR` | Repeat with the same key. |
| 503 | `EMISSION_DISABLED` | Retry with increasing waits. |

## Branches, offline mode and purchase mailbox

- **Branches** (each RUT includes one location (its casa matriz or its first branch); each additional active branch costs CLP 2,990 a month, with no limit on branches): `GET/POST /api/v1/dte/branches/`, `GET/PATCH/DELETE
  /api/v1/dte/branches/{branch_id}/` (DELETE deactivates, it does not erase). Fields `name`, `direccion`, `comuna`, `ciudad`,
  `sii_code` (the branch's SII code). `offline_enabled` is read-only.
- **Offline mode** (boletas 39 and 41): the register requests a batch, stores the CAF and key encrypted, stamps the `<TED>` (DD with no
  spaces between tags, ISO-8859-1, SHA1withRSA with the CAF key), prints, queues and when internet returns sends
  to `devices/{device_id}/boletas/` with `folio`, `ted_timestamp` and `ted`, always with the same `Idempotency-Key` per
  sale. Deadline: each boleta reaches the SII immediately, within a maximum of 1 hour; without data coverage that hour runs from when
  the connection returns (SII Res. Ex. No. 74 of 2020), so the queue is sent as soon as internet returns (these submissions do not go
  through the per-minute issuing limit or the RUT's general one: the own limit is 600 per minute per register and 1,800
  per minute across all the RUT's devices; above that, `429 DEVICE_RATE_LIMIT_EXCEEDED`, wait `Retry-After` and
  retry with the same `Idempotency-Key`). Retiring a register: `POST /api/v1/dte/devices/{device_id}/retire/`, only
  with the RUT's API key (without `X-Device-Secret`); `GET /api/v1/dte/devices/` lists the registers to find its
  `device_id`. In the sandbox it is tested without contracting the mode or creating a branch. Full guide:
  https://api.sharkpos.cl/docs#sin-conexion (in Spanish)
- **Purchase mailbox** (requires Herramientas de gestión; the XML can also be uploaded with `POST /api/v1/dte/inbound/upload/`): the address is returned by
  `GET /api/v1/dte/inbound/mailbox/` (for example `76123456-7@sharkpos.cl`); incremental download with `GET /api/v1/dte/inbound/?since_id=...`, detail at
  `GET /api/v1/dte/inbound/{inbound_id}/`, original XML at `GET /api/v1/dte/inbound/{inbound_id}/xml/`, webhook `inbound.received`.
  Each document carries `signature_verified` / `authenticity` (`verified` only if signature, timbre and CAF signed by the SII
  all verify; the reason in `authenticity_reason`). Do not post an unverified one to your books automatically: the official
  source of what was received is the SII's RCV (Registro de Compras y Ventas, the purchase and sales ledger). A later verified copy replaces the unverified one (`inbound.verified`);
  two verified copies with different content are left unverified (`authenticity_reason: verified_conflict`,
  `conflict: true`). Hourly limits: 40 emails per sender, 200 per mailbox and 300 MB per mailbox; whatever arrives above
  the limit, or with Herramientas de gestión off, is stored and processed later (within 30 days).
- **Documents per month**: 20,000 included per RUT; above that issuing is not cut off (the excess is charged in the monthly billing after
  the month closes), so there is no need to stop sales over quota. In the sandbox there is a cap
  (`429 MONTHLY_QUOTA_EXCEEDED`).
- **Switching provider**: does not require certifying again with the SII; the taxpayer updates their software
  provider on sii.cl (Zeiro SpA, RUT 78.453.756-0) with the company's administrator user.

## Platforms with several RUTs (partner)

If the system manages several companies (SaaS, ERP, POS), use the partner API with the **platform key**
(different from each RUT's API key): `POST /api/v1/partner/tenants/register/` registers a RUT with its digital
certificate in one call (multipart) and returns that RUT's API key only once. Store it encrypted, associated with that
company. In the sandbox `company_rut` is enough: the sandbox supplies a test certificate and folios. Each RUT's branches and mailbox:
`/api/v1/partner/tenants/{tenant_id}/branches/` and `/api/v1/partner/tenants/{tenant_id}/inbound/`.

To suspend a RUT's issuing (for example, if that customer stopped paying the platform):
`POST /api/v1/partner/tenants/{tenant_id}/suspend/`; to lift it, `POST /api/v1/partner/tenants/{tenant_id}/resume/`.
Both are idempotent and respond `suspended_by_partner`, `suspended_by_partner_at`, `can_emit` and
`emission_blocked_by`. While it lasts, issuing, registering devices or requesting batches responds
`403 TENANT_SUSPENDED_BY_PARTNER`; querying and downloading documents, receiving what registers already stamped offline,
retrying with the same `Idempotency-Key` for an already-issued document and webhooks keep working.
The RUT is still billed while suspended: to stop paying for it, it is deactivated. Resuming never enables a
deactivated RUT or one with an overdue payment (`can_emit` tells the result).

## Taxes per product, other currency and optional fields

- Additional taxes, specific taxes and withholdings per line: `items[i].taxes` (up to 2 codes). With a fixed rate only the
  code goes (`"taxes": [24]`); specific ones carry an amount (`{"code": 28, "amount": 101000}`). On factura 33 and its notes:
  18 (5%), 19 (12%), 23 and 44 (15%), 24 (31.5%), 25 and 26 (20.5%), 27 (10%), 271 (18%), 45 (50%) and the specific ones 28, 35, 51
  and 52. With a base: 17 (`{"code": 17, "base": ...}`), 14 and 50 (`{"code": 14, "margin": ..., "amount": ...}`). On purchase
  invoice 46: withholdings 30 to 48 and 301 to 481. `retainer` block only together with a 14, 17 or 50 on the same line;
  `construction_credit: true` applies the 65% construction-company credit. They are not combined with `prices_include_iva`, with global
  discounts on the taxed portion or with exempt lines.
- Other currency (33, 34, 56, 61): `other_currency: {"code": "USD", "exchange_rate": 950.12}`. Product codes:
  `items[i].codes` (`{"type": "EAN13", "value": "..."}`, up to 5). Service period: `service_indicator` 1, 2 or 3 (with 1
  or 2, `period_from` and `period_to` are required). Also `items[i].subquantities`, `production_date` and `expiry_date`.

## Verifying with the SII and annulling folios

- `POST /api/v1/dte/verify/`: status of a document with the SII, your own or a supplier's (`document_type`, `folio`,
  `issuer_rut`, `receptor_rut`, `issue_date`, `amount_total`, or the `xml`). `result` is `accepted`, `accepted_modified`,
  `annulled`, `data_mismatch`, `not_found`, `not_authorized`, `issuer_not_authorized` or `unknown`; if the SII does not respond,
  `503 SII_UNAVAILABLE` with `Retry-After`.
- `POST /api/v1/dte/verify/cesion/`: whether a factura 33 or 34 has been assigned (cedida, i.e. factored) (requires Herramientas de gestión).
- `POST /api/v1/dte/folios/annul/` (with `Idempotency-Key`) annuls your own unused folios (up to 500; `reason`
  required); it responds 202 and is queried with `GET /api/v1/dte/folios/annul/` and `GET /api/v1/dte/folios/annul/{annulment_id}/`.
  The three have not yet been tested against the real SII: try them in the sandbox and do not base accounting decisions on them.

## Official clients

Python and Node/TypeScript SDK (package `sharkpos`), a single-file PHP client, a Postman collection and an MCP server for
using the API from AI agents. If the person wants them, they should ask via WhatsApp or at contacto@sharkpos.cl; do not
invent installation commands.

## What the integration must not do

- Ask for or store anyone's SII Clave Tributaria (tax password). SharkPOS works with the digital certificate.
- Build XML, sign or call SII servers directly. The only exception: in offline mode the register
  signs the `<TED>` with the batch key; the DTE is still signed and sent by SharkPOS.
- Reuse an `Idempotency-Key` for another sale, or generate a new one when retrying the same one.
- Show the end user the internal `dte_status` or the XML: use `message` and `solution`.

## End-to-end test before production

In the sandbox: issue a boleta, repeat it with the same key (it must return 200 with the same folio), receive and
verify the `dte.accepted` webhook, download the PDF from `links.pdf`, and trigger a 400 to check that the system
shows `message` without retrying. Only then switch the base URL and the API key to production.
