# API keys

An ERP, a warehouse system, an accounting tool or a script works with the shop through its REST API at
`/api/v1`. Each one gets its own key from **Setări → Chei API**. You need *Issues and manages API keys* (only the Owner
and Administrator have it at first).

## Issuing a key

**Cheie nouă**: a name (the system that uses it), the **Drepturi** it needs and nothing more (read, write or both, per
resource), optionally an expiry date and the **Adrese permise** it may call from (IPs or CIDR ranges, one per line).
You can give only the rights you hold yourself in the admin (reading orders needs *Sees orders*, changing them
*Manages orders*, and so on); a key never does more than its holder. The key is shown **once**, right after you create it: copy it into the other system. It looks like
`ss_12_…` and is sent as `Authorization: Bearer ss_12_…`.

A key acts for whoever issued it: stock counts and order changes made through it are recorded in their name. It stops
working, for reads too, as soon as that person can no longer manage API keys or their account is deleted, and each
call is refused as soon as they lose the admin right behind it (the list
shows it as **Fără titular**). Someone else who edits the key takes it over: it then acts for them and gets a new
secret, so the old one stops working. **Generează altă cheie** does the same when a key may have leaked;
**Suspendă** stops it for a while.

## What the API offers today

| Resource | Read | Write |
| --- | --- | --- |
| Produse `/products` | list, one, filters by status, ERP code, SKU | — |
| Variante `/variants` | list, one, filters by product, SKU, barcode, ERP code | the shelf price and ERP code (the price goes into the price history, as in the admin) |
| Stoc `/stock-levels` | stock per variant and location | stocktake (create), `adjust` (add or take units) |
| Comenzi `/orders` | with lines and amounts; filters by state, number, placed since | `status` (the next steps the admin allows) |
| Expedieri `/shipments` | AWB, state, tracking; by order, AWB, state | — |
| Clienți `/customers` | accounts, by e-mail (never the password) | — |
| Companii `/companies` | identity and trading terms, by CUI | — |
| Facturi `/invoices` | invoices and credit notes with their e-Factura state | — |
| Liste de prețuri `/price-lists` | B2B lists: for whom, currency, dates | — |
| Prețuri din liste `/price-list-items` | a list's rules | add or replace a rule (a price or a percentage, from a quantity), delete one |
| Promoții `/promotions` | automatic promotions | — |
| Vouchere `/vouchers` | codes, uses | issue (percent, fixed or free delivery, on the whole cart; a code is generated when none is sent), change, switch off |
| Registrul de profit `/ledger-entries` | every revenue and cost row with its order, product, customer and channel; by day range, type, order | — |
| Costuri lunare `/period-costs` | fixed costs and marketing per month; by kind, month | — |
| Vânzări în magazine `/store-sales` | receipts from the stores' cash registers with their lines; by location, day | through `bulk/store-sales` |

**Bulk updates** take up to 5,000 rows in one call, for ERP syncs: `POST /api/v1/bulk/stock` (a stocktake per row:
`sku` or `variant_id`, `location_id`, `on_hand`), `POST /api/v1/bulk/prices` (`sku` or `variant_id`,
`price_amount`) and `POST /api/v1/bulk/store-sales` (a cash-register receipt per row, see
[In-store sales](store-sales.md)). They run in the background: the answer gives an id, and `GET /api/v1/bulk/{id}` says how far it got
and which rows failed and why. A bad row never stops the others.

Lists are paged (`page`, `per_page` up to 100), sorted (`sort=-updated_at`) and can return only what changed
(`updated_since`), for syncing. Costs and margins are only in the two analytics feeds, for keys whose holder has
*Sees costs, margins and profit*: they are what outside BI tools (Metabase, Power BI) read to build their own
reports. Each key may make 120 calls a minute.

The full reference is generated from the shop itself: **OpenAPI** (`/api/openapi.json`, `?lang=en` for English) and a
**Postman** collection (`/api/postman.json`), both linked from the keys page.

## The call log

**Ultimele apeluri** shows the latest calls: when, which key, what, the response code and how long it took, with the
error message for refused ones. The content of requests and answers is never kept. The log keeps 30 days.

## Webhooks

**Setări → Webhook-uri** sends the shop's events to another system as they happen, instead of it asking the API
every few minutes. Add the address (HTTPS, a public server: addresses in private, local or reserved networks are refused, and each delivery connects to the very address that was checked) and tick the
events it wants:

| Event | When |
| --- | --- |
| `order.created`, `order.status_changed`, `order.paid`, `order.shipped`, `order.cancelled` | an order is placed or moves |
| `return.requested` | a customer asks to return something |
| `shipment.booked` | an AWB is issued |
| `stock.low` | a variant falls to its low-stock threshold in a location |
| `customer.created` | a shopper creates an account |
| `subscription.started`, `.renewed`, `.payment_failed`, `.ended` | a subscription's life |

You can tick only the events you can see in the admin, and an address gets them only while whoever added it may
still see them and manage the API; this is checked again at every send, retries and replays included, and only
someone who may see an event can send it again. Each delivery is a JSON `POST` with the event's ids and a few key fields (the
rest comes from the API), and is signed: the `X-SyncShop-Signature` header reads `t=<time>,v1=<signature>`, the
signature being HMAC-SHA256 with the address's secret over `<time>.<body>`. The secret is shown once; **Alt secret**
replaces it. `X-SyncShop-Delivery` carries the event's id, the same on every retry, so the receiver can drop
duplicates.

An answer other than 2xx is retried after 1, 5 and 30 minutes, then 2, 6 and 24 hours, then the delivery is marked
failed. The address's page lists every delivery with its result; **Retrimite** sends one again and **Trimite un test**
sends a `ping`. Deliveries are kept 30 days.
