Vuoi provare l'API sul tuo negozio? L'accesso apre in ordine di lista: entra nella lista d'attesa

Documentazione API

Il riferimento OpenAPI 3.1 verificato contro il codice che serve, le guide per chi integra e gli esempi provati.

Versione 1.0.0

36 operazioni · 12 ambiti · 5 eventi

Indirizzo dell'API

https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api

In questa pagina

API di GroceryAI · per cominciare (5 passi)

Dal nulla a un catalogo caricato e a un ordine ricevuto, nell'ambiente di prova (test). I dati di prova sono separati da quelli veri: niente di ciò che si fa qui arriva a un cliente vero.

Indirizzo di base (ogni percorso qui sotto si aggiunge in coda):

https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api

Il riferimento completo è il documento OpenAPI 3.1, leggibile senza chiave: GET /v1/openapi.json (in inglese, la lingua di chi integra). Ogni operazione ha un esempio di richiesta e di risposta provato contro l'ambiente di prova.

1. Una chiave di prova

Nel portale di GroceryAI: Sviluppatori → Chiavi API → Crea chiave. Ambiente test e solo gli ambiti che servono, per esempio catalog:read e catalog:write (un ambito non ne contiene un altro). La chiave ha la forma gai_test_ab12cd34_… e si vede una volta sola: va in un gestore di segreti o in una variabile d'ambiente, mai nel codice.

export GROCERYAI_API_KEY='gai_test_…'          # la tua chiave; mai in un commit
export GROCERYAI_BASE='https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api'

2. Il contratto, senza chiave

curl -s "$GROCERYAI_BASE/v1/openapi.json" -o openapi.json

Da qui si genera un client, o lo si dà al proprio agente di programmazione. La risposta porta un ETag: rimandato in If-None-Match, dà 304 se non è cambiato niente.

3. La prima chiamata

curl -s "$GROCERYAI_BASE/v1/products?limit=1" \
  -H "Authorization: Bearer $GROCERYAI_API_KEY"

Un 200 con {"data": [...], "next_cursor": ..., "request_id": "..."} vuol dire che la chiave funziona (ogni negozio nuovo ha accanto il suo negozio di prova con i prodotti d'esempio: crea lì la chiave test; i prodotti d'esempio non vanno mai in vendita). Un 401 o un 403 portano error.code ed error.doc_url: la pagina dice che cosa non va e come correggerlo.

Le scritture vanno a lotti di al più 500 elementi e portano sempre un'Idempotency-Key (un UUID nuovo per ogni operazione; la stessa solo per ritentare la stessa identica richiesta).

curl -s -X PUT "$GROCERYAI_BASE/v1/products" \
  -H "Authorization: Bearer $GROCERYAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{"products":[{"sku":"EXAMPLE-SPAGHETTI-500","title":"Spaghetti 500 g","price":1.29,"stock_qty":140}]}'

La risposta dice quanti elementi sono arrivati (received), scritti (written) e rifiutati (rejected). Un elemento rifiutato non fa cadere il lotto: è in errors[] con index, code e message. Poi prezzi e giacenze si tengono freschi con PUT /v1/inventory (cambia solo ciò che si manda).

5. Gli ordini

Due vie, gli stessi dati. Se ne sceglie una:

  • Ritiro (pull), senza un endpoint in ingresso: GET /v1/orders?status=new rende gli ordini confermati; salvato l'ordine nel proprio sistema, lo si conferma con POST /v1/orders/{order_id}/ack (con Idempotency-Key) e non torna più.
  • Webhook: si registra un endpoint nel portale (Sviluppatori → Webhook), si verifica ogni consegna con la libreria ufficiale di Standard Webhooks (standardwebhooks su npm e PyPI; esempi in docs/api/examples/), si risponde 2xx entro 15 secondi e si scartano i doppioni per webhook-id.

Consegnato l'ordine, si dice com'è andata: POST /v1/orders/{order_id}/status con delivered, substituted, not_delivered o returned.

In produzione

Una chiave gai_live_… con gli stessi ambiti, e nient'altro da cambiare: percorsi, corpi ed errori sono identici. I due ambienti non vedono i dati l'uno dell'altro, chiavi d'idempotenza comprese.

Quando qualcosa non va

  • Si programma su error.code, mai su message (il testo può cambiare).
  • Si segue error.doc_url (o GET /v1/errors/{code}): la pagina dice che cosa è successo, come correggerlo e se ripetere la stessa richiesta può bastare (retryable).
  • 429 LIMITE_RICHIESTE: si aspettano i secondi di Retry-After. 5xx: si ritenta con la stessa Idempotency-Key, non si applica mai due volte.
  • Se ci si scrive, si manda il request_id.

Altro: la guida completa (docs/api/guida.it.md), le regole per gli agenti di programmazione (docs/api/AGENTS.md) e un prompt pronto per Claude Code, Codex o Cursor (docs/api/agent-prompt.md).

Per gli agenti AI

Per far integrare GroceryAI a un agente di programmazione (Claude Code, Codex, Cursor o un altro) nel tuo repository: il prompt da incollare, il file AGENTS.md da tenere nel repository e i codici d'errore con la pagina di ciascuno. Tutto è pubblico; l'unico segreto è la chiave di prova che metti nell'ambiente.

Questi tre testi sono in inglese: sono quelli che l'agente legge.

Il prompt d'integrazione

Paste the block below into Claude Code, Codex, Cursor or any coding agent working in your repository. Replace the two lines marked <…>. The agent needs nothing else from GroceryAI: the contract, the examples and the error pages are public, and the only secret is the test key you put in the environment.


You are integrating this repository with the GroceryAI Platform API.

Goal: <describe what to build, e.g. "push our product catalog every night and pull confirmed orders into our order table">.
Our stack: <language, framework, where config and secrets live>.

Sources of truth (fetch them, do not answer from memory):
- OpenAPI 3.1 contract, no key needed: https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/openapi.json
  Every operation has a tested request and response example; response schemas are closed, never invent fields.
- Error catalog, no key needed: GET /v1/errors and GET /v1/errors/{code} on the same base URL. Every error response
  carries error.doc_url pointing to its page: read it when a call fails, it says how to fix the request.

Credentials:
- The API key is in the environment variable GROCERYAI_API_KEY. It is a test key (gai_test_...): it only sees test
  data. Never print, log, commit or hard-code the key, and never send it anywhere except the GroceryAI base URL.
  Do not switch to a live key (gai_live_...); that is a human decision.

Working steps:
1. Download the contract and list the operations and scopes the goal needs.
2. Make the first call before writing any code: GET /v1/products?limit=1 with "Authorization: Bearer $GROCERYAI_API_KEY".
   A 200 proves the key; a 401/403 tells you why in error.code and error.doc_url. If the key lacks a scope, stop and
   tell me which scope to add; do not work around it.
3. Implement against the contract, applying the rules that concern the operations your goal uses:
   - every write carries a fresh Idempotency-Key (UUID v4) per logical operation, reused only to retry the same body;
   - batch writes take at most 500 items; always check errors[] and warnings[] in the 200 response;
   - paginate with next_cursor -> cursor until it is null (it is present only when there really is another page, so
     the last page, even a full one, needs no extra request);
   - branch on error.code (never on message); on 429 wait Retry-After; on 5xx retry with the same Idempotency-Key;
   - log the request_id of every failed call;
   - error.code, error.type and values such as stato are stable Italian identifiers; error.message is Italian free
     text for humans: never parse it.
4. Prove it against the test environment: run the integration end to end, show me the real responses (status, counts,
   errors[]), and add automated tests that use the documented examples as fixtures.
5. Report: the operations used, the scopes required, what you ran and what it returned, and anything you could not
   verify. Do not claim success without a real response from the API.


Why each line is there: the public contract and error pages let the agent work without our help; the test key keeps every experiment away from real customers; idempotency, batch checks and error.code branching are the rules that otherwise get guessed wrong; the last step stops an agent from declaring "done" on code it never ran.

The same rules, as a file to keep in your repository: AGENTS.md. The five steps for a person: quickstart.md.

AGENTS.md

Copy this file into the repository that integrates with GroceryAI (as AGENTS.md, or merge it into yours, or into CLAUDE.md). It tells a coding agent (Claude Code, Codex, Cursor, Copilot or any other) the rules that hold for every call, so it does not have to guess.

Source of truth

  • Contract: https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/openapi.json (OpenAPI 3.1, no key needed, ETag + Cache-Control). Fetch it; do not rely on memory. Every operation has a tested request and response example.
  • Error catalog: GET /v1/errors and GET /v1/errors/{code} (no key needed). Every error response carries error.doc_url pointing to its page.
  • Service status: GET /v1/status (no key needed): per component operational, degraded, outage or unknown. Before blaming your code for a 5xx, check it; unknown means not measured, never «up».
  • Schemas are closed (additionalProperties: false on responses): never invent fields, read them from the document.

Configuration

  • Base URL: https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api. Keep it in configuration, not scattered in code.
  • Key: read it from the environment (GROCERYAI_API_KEY). Never hard-code it, never print or log it, never commit it, never send it to a third party. Logs may show the public prefix (gai_test_ab12cd34) only.
  • Environments: develop and test with a gai_test_… key only. Switching to gai_live_… is a human decision; the code does not change.
  • Recommended header for lower latency from outside Europe: x-region: eu-central-1.

Rules for every call

  1. Authorization: Bearer <key> on every operation except GET /v1/openapi.json, GET /v1/errors and GET /v1/status.
  2. Every write (PUT, POST, DELETE with Idempotency-Key in the document) carries a fresh Idempotency-Key (UUID v4) per logical operation. On retry, reuse the same key and the same body. A different body with a used key is 409 IDEMPOTENCY_KEY_RIUSATA.
  3. Batch writes (PUT /v1/products, PUT /v1/inventory, PUT /v1/customers, PUT /v1/order_history) take at most 500 items. Always inspect errors[] (rejected items, with index and code) and warnings[] of the response: a 200 does not mean every item was written.
  4. Pagination is by cursor: pass next_cursor as cursor until it is null. It is present only when there really is another page, so the last page (even a full one) ends the loop with no extra request.
  5. Branch on error.code, never on error.message. Use error.param to locate the field. Codes, error.type and values such as stato are stable Italian identifiers; error.message is Italian free text and may change.
  6. Rate limit: it comes from the store's plan (guide §4: from 5 requests per second on trial to 100 on enterprise live, with a burst absorbed by a bucket). Every keyed response carries RateLimit: "key";r=<left now>;t=<seconds> (and RateLimit-Policy: "key";q=<per second>;w=1;burst=<burst>; a key with its own per-minute cap adds a "key-minute" item to both lists); when r gets low in any item, spread the remaining requests over its t seconds instead of running into the 429. Retries: 429 → wait Retry-After seconds (equal to t); 5xx → exponential backoff with the same Idempotency-Key; codes whose page says retryable: false → do not retry unchanged, fix the request.
  7. Log the request_id of every failed call; it is what GroceryAI support asks for.
  8. If your key is an agent key, operations that remove or cancel something (DELETE /v1/products/{sku}, a snapshot commit without dry_run, an order status not_delivered or returned) answer 202 with an approval and change nothing. Do not work around it and do not retry in a loop: tell the human that a person must approve it in the portal (Developers → Approvals), poll GET /v1/approvals/{approval_id} at most once a minute, and when status is approved send the same request again with GroceryAI-Approval-Id: <id>. APPROVAZIONE_RIFIUTATA is final.
  9. A 401 CHIAVE_SOMMA_ERRATA means the key in your configuration is truncated or mistyped (its last six characters are a checksum): ask the human for the key again, do not try variations. A 403 IP_NON_AMMESSO means the key is restricted to other addresses: ask the human, do not switch keys.

Catalog

  • PUT /v1/products is an upsert by sku that MERGES: only the fields you send change. PUT /v1/inventory changes only prices, stock and offers of existing products.
  • To declare "this is the whole catalog" use a snapshot: POST /v1/products/snapshots, the batches with its snapshot_id, then POST /v1/products/snapshots/{snapshot_id}/commit first with {"dry_run": true}, then with {"expected_off": <to_switch_off>}. Never withdraw products one by one to emulate a full sync.
  • For the whole catalog in one call use POST /v1/catalog/imports (up to 50,000 products, or the url of a file): it answers 202 with Location; poll GET /v1/catalog/imports/{import_id} at most every 30 seconds until status is succeeded, partial or failed, then read GET /v1/catalog/imports/{import_id}/errors. Do not split a whole catalog into hundreds of PUT /v1/products calls.
  • gtin is optional; if present it must have a valid check digit. Prices are in the shop currency, never converted.

Orders

  • Pull: GET /v1/orders?status=new, store the order, then POST /v1/orders/{order_id}/ack. Make your storage idempotent by order_id (an order can be read again before the ack).
  • Webhooks follow Standard Webhooks (https://www.standardwebhooks.com): verify with the official library (standardwebhooks on npm and PyPI: new Webhook(secret).verify(rawBody, headers)), with the endpoint secret exactly as shown (whsec_<base64>); it checks webhook-id, webhook-timestamp (300 seconds tolerance) and webhook-signature (v1,<base64>, two signatures during a secret rotation). Answer 2xx within 15 seconds and process asynchronously; deduplicate by webhook-id; 410 Gone deactivates the endpoint. Verify against the raw body bytes, before parsing.
  • Report the outcome after delivery: POST /v1/orders/{order_id}/status. The same call reports progress before it (preparing, ready, out_for_delivery, delayed, rescheduled, with eta, reason, tracking_url); after an outcome progress answers 409 TRANSIZIONE_NON_AMMESSA. Guide, section 7-bis.

Definition of done for an integration change

  • The calls it adds are in the OpenAPI document, with the scopes the key really has.
  • It ran against the test environment and the responses were checked (status, errors[], schema).
  • Failures are handled per error.code and logged with request_id; no key appears in code, logs or commits.

I codici d'errore

Every code the GroceryAI API can return. Program against error.code (never against message, which may change). Each error response also carries error.doc_url, the live JSON version of the page below, readable without a key.

codewhat happenedretry unchanged?
AMBIENTE_DEL_NEGOZIOThe key's environment does not match the shop's environment for this setting.no
AMBITO_MANCANTEThe key is valid but does not have the scope this operation requires.no
APPROVAZIONE_DIVERSAThe request is not the one that was approved.no
APPROVAZIONE_GIA_USATAThis approval already executed its operation.no
APPROVAZIONE_IN_ATTESAThe approval is still waiting for a person to decide.yes
APPROVAZIONE_RIFIUTATAA person at the shop rejected this operation.no
APPROVAZIONE_SCADUTAThe approval expired before it was used (72 hours).no
APPROVAZIONE_SCONOSCIUTANo approval with this id exists for this key.no
APPROVAZIONI_ASSENTIApprovals for agent keys are not in service on this instance yet.yes
ATTESO_NON_VALIDOexpected_off is missing or is not a whole number.no
BIC_NON_VALIDOThe BIC/SWIFT code is not valid.no
BOOLEANO_NON_VALIDOA yes/no field is not a boolean.no
CADENZA_NON_VALIDAevery_hours is outside the allowed range.no
CAMPO_IN_DUE_POSTIThe same field is both on the item and inside attributes, with two different values.no
CAMPO_NON_PER_PUNTO_VENDITAWith store_code, the item carries a field that applies to the whole shop.no
CAMPO_OBBLIGATORIOA required field is missing.no
CAMPO_SCONOSCIUTOThe body has a field this operation does not know.no
CHIAVE_ASSENTEThe request has no API key.no
CHIAVE_INCOERENTEThe visible prefix of the key does not match its secret part.no
CHIAVE_MALFORMATAThe value after Bearer is not shaped like a GroceryAI key.no
CHIAVE_REVOCATAThis key has been revoked.no
CHIAVE_SCADUTAThis key has passed its expiry date.no
CHIAVE_SCONOSCIUTAThe key is well formed but does not exist.no
CHIAVE_SOMMA_ERRATAThe key has the current GroceryAI format, but its last six characters (the checksum) do not match the rest: it was truncated, mistyped or altered.no
CLIENTE_SCONOSCIUTONo customer with this reference exists for this shop and environment.no
CODICE_AMICO_NON_VALIDOThe friend-code settings are not valid.no
CODICE_ERRORE_SCONOSCIUTOThis API never returns the error code in the path.no
CONTEGGIO_CAMBIATOThe number of products to withdraw changed since your dry run: nothing was withdrawn.yes
COORDINATE_BANCARIE_ASSENTIbank_transfer is enabled but the shop has no bank details.no
CORPO_NON_JSONThe request body is not valid JSON.no
CORPO_NON_VALIDOThe JSON body does not have the shape this operation expects.no
CORPO_TROPPO_GRANDEThe request body is larger than this operation accepts: 1 MiB, or 16 MiB for POST /v1/catalog/imports.no
CUSTOMER_REF_NON_VALIDOcustomer_ref is missing or malformed.no
DATA_NON_VALIDAA date is missing, malformed or not plausible.no
DATE_INVERTITEThe offer ends before it starts.no
DB_URL_ASSENTEThis API instance is not fully configured.yes
DIPENDENZA_NON_DISPONIBILEA service this operation depends on is temporarily unavailable.yes
DISPONIBILITA_NON_VALIDAavailable is not a boolean.no
DURATA_NON_VALIDAexpires_in is not a whole number of seconds between 30 and 600.no
ELEMENTO_NON_OGGETTOA batch item is not a JSON object.no
EMAIL_NON_VALIDAThe email is not an email address.no
ENERGIA_NON_COERENTEWarning: energy_kj and energy_kcal do not match (1 kcal = 4.184 kJ).no
ERRORE_INTERNOSomething failed on our side.yes
ETA_MANCANTErescheduled needs the new delivery window in eta.no
ETA_NON_AMMESSAeta is not allowed with this status.no
EXTERNAL_REF_MANCANTEThe customer has no external_ref.no
EXTERNAL_REF_TROPPO_LUNGOThe external_ref is longer than 128 characters.no
EXTRA_SENZA_CRITERIOA heavy-goods extra has no criterion saying when it applies.no
FEED_NON_CONFIGURATONo catalog feed is configured for this environment.no
FEED_URL_NON_AMMESSOThe feed URL is not allowed.no
FORMATO_NON_AMMESSOThe feed format is not one of those supported.no
FRASE_NON_MODIFICABILEThis phrase cannot be customised.no
GIACENZA_NON_VALIDAstock_qty is not a non-negative number.no
GIORNI_NON_VALIDIA number of days is outside its allowed range.no
GRADINI_NON_IN_ORDINEDiscount tiers are not in increasing order.no
GTIN_NON_VALIDOThe gtin is not a valid GTIN/GS1 barcode.no
IBAN_NON_VALIDOThe IBAN is not valid.no
IDEMPOTENCY_KEY_MANCANTEThis operation writes data and needs an Idempotency-Key header.no
IDEMPOTENCY_KEY_RIUSATAThis Idempotency-Key was already used for a different request.no
IDEMPOTENCY_KEY_TROPPO_LUNGAThe Idempotency-Key is longer than 255 characters.no
IDENTITA_DI_UN_ALTRO_AMBIENTEChat session: the identity token belongs to the other environment (test vs live).no
IDENTITA_FUORI_DAL_NEGOZIOChat session: the identity token belongs to another shop.no
IDENTITA_GIA_USATAChat session: the identity token was already used.no
IDENTITA_MALFORMATAChat session: the identity_token is not shaped like a GroceryAI identity token.no
IDENTITA_NON_IN_SERVIZIOChat identity is not in service on this instance yet.yes
IDENTITA_SCADUTAChat session: the identity token expired.no
IDENTITA_SCONOSCIUTAChat session: the identity token does not exist.no
IDENTITA_SOLO_NEGOZI_NATIVIThis shop does not use GroceryAI for customer identity: the website chat stays anonymous.no
IMPORTAZIONE_SCONOSCIUTANo catalog import with this import_id exists for this account and environment.no
IMPORTAZIONI_IN_CORSOThere are already 5 unfinished catalog imports in this environment.yes
IMPORTO_INCOERENTEdelivered_amount contradicts the status.no
IMPORTO_MANCANTEdelivered_amount is required for this status.no
IMPORTO_NON_VALIDOAn amount is not a valid non-negative number.no
INFORMAZIONI_ALIMENTARI_INCOERENTITwo food-information fields of the item contradict each other.no
IP_NON_AMMESSOThis key has an IP allowlist, and the request does not come from an address on it.no
ISTANTANEA_CHIUSAThe snapshot is already committed and accepts no more batches.no
ISTANTANEA_SCADUTAThe snapshot expired (snapshots live 24 hours).no
ISTANTANEA_SCONOSCIUTANo snapshot with this snapshot_id exists for this account and environment.no
ISTANTANEA_SOTTO_SOGLIAThe batches of this snapshot cover too few of the active products: nothing was withdrawn.no
LIMITE_RICHIESTEToo many requests for this key in the current minute.yes
LINGUA_NON_VALIDAlang is not a language code.no
LINK_NELLA_FRASEThe phrase contains a link.no
LOTTO_TROPPO_GRANDEThe batch has more items than this operation accepts: 500 per call, or 50,000 for POST /v1/catalog/imports.no
LOTTO_VUOTOThe batch list is empty.no
METODO_DI_PAGAMENTO_NON_AMMESSOA payment method is not one of those supported.no
METODO_NON_AMMESSOThe path exists, but not with this HTTP method.no
MOTIVO_NON_VALIDOreason is not one of the allowed codes, or not allowed with this status.no
NESSUN_CAMPOThe inventory item changes nothing.no
NESSUN_METODONo payment method is enabled.no
NON_TROVATOThe resource in the path does not exist for this account and this key's environment.no
NOTA_TROPPO_LUNGAThe note is longer than 500 characters.no
NUMERO_NON_VALIDOA numeric field is not a valid number for its range.no
NUTRIZIONE_INCOMPLETAWarning: the item carries part of the nutrition declaration but not all of it.no
OFFERTA_NON_SCONTATAWarning: the offer price is not below the regular price, so it will not be shown as an offer.no
OFFERTA_SUPERIORE_AL_PREZZOThe offer price is higher than the regular price.no
ORARI_NON_VALIDIThe opening or assistant hours are not valid.no
ORDINE_MANCANTEThe order line has no order_ref.no
ORDINE_SENZA_CLIENTEThe order line does not say who the customer is.no
OUTBOX_ASSENTEThe event log is not in service on this instance yet.yes
PACCHETTO_ASSENTEThe shop has no language pack yet, so the preview cannot be rendered.yes
PARAMETRO_NON_VALIDOA query parameter is outside its allowed values.no
PERCENTUALE_NON_VALIDAA percentage is outside its allowed range.no
PERCORSO_NON_VALIDOA site path is not valid.no
PESO_MEDIO_SENZA_PESOWarning: an average piece weight was sent for a product not sold by weight; it is not used.no
PREZZO_NON_VALIDOThe price is not a non-negative number.no
PUNTO_VENDITA_CON_ZONEThis store cannot be deactivated or removed while delivery zones use it.no
PUNTO_VENDITA_SCONOSCIUTONo active store has this store_code.no
QUANTITA_NON_VALIDAquantity is missing or not greater than zero.no
REGISTRO_ASSENTEThe order register is not in service on this instance yet.yes
REGOLA_SCONOSCIUTAA rule or text key is not one this API knows.no
REGOLE_SOLO_NEGOZI_DEL_PORTALEThis shop does not manage its rules and texts through GroceryAI.no
RICHIESTA_IN_CORSOA request with the same Idempotency-Key is still being processed.yes
RIFIUTATA_DAL_DATABASEThe database refused this item.no
ROTTA_SCONOSCIUTANo operation exists for this method and path.no
SEGNAPOSTO_DIVERSIThe phrase does not keep the same placeholders as the original.no
SKU_MANCANTEThe item has no sku.no
SKU_RIPETUTO_NEL_LOTTOThe same sku appears twice in one batch.no
SKU_SCONOSCIUTONo product with this sku exists for this account and environment.no
SKU_TROPPO_LUNGOThe sku is longer than 128 characters.no
SOGLIA_SOTTO_IL_COSTOA zone's free-delivery threshold is below its delivery fee.no
STATO_NON_MISURABILEThe service status cannot be read right now: the status is unknown, not operational.yes
STATO_NON_VALIDOThe status is missing or not one of the allowed values.no
STORICO_SOLO_NEGOZI_NATIVIThis shop reads its order history from its own connector, not from this route.no
TELEFONO_NON_E164The phone number is not in international E.164 format.no
TENANT_NON_DELLA_CHIAMATAThe body refers to a different account than the key's.no
TENANT_SOSPESOThe account that owns this key is not active.no
TERMINE_NON_VALIDOA term or time window is not valid.no
TESTO_TROPPO_LUNGOA text field is longer than allowed.no
TITLE_MANCANTEThe new product has no title.no
TITLE_TROPPO_LUNGOThe title is longer than 512 characters.no
TOTALE_NON_VALIDOorder_total is not a non-negative number.no
TRANSIZIONE_NON_AMMESSAThe order already has an outcome: a progress status is no longer recorded.no
TROPPI_ELEMENTIA list has more items than allowed.no
UNITA_NON_AMMESSAA unit field has a value that is not allowed.no
URL_NON_AMMESSOtracking_url is not an https address on a tracking domain the shop declared.no
VALORE_NON_AMMESSOA field has a value outside its allowed list.no
VALORE_RIPETUTOThe same value appears twice where values must be unique.no
VALUTA_DIVERSA_DAL_TENANTThe item's currency differs from the shop currency.no
VALUTA_NON_VALIDAcurrency is not an ISO 4217 code.no
VERSIONE_CAMBIATAThe rules changed since the version you read: nothing was saved.yes
ZONA_NON_VALIDAA delivery zone entry is malformed.no
ZONA_SCONOSCIUTAA delivery zone is not one of the shop's zones.no

Full catalog as JSON: GET https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors (no key needed).

_Generated from the OpenAPI document by tools/genera-openapi.mjs: do not edit by hand._

API GroceryAI · guida per chi integra

Il riferimento completo, rotta per rotta, è il documento OpenAPI 3.1 (openapi.json): forme delle risposte, codici d'errore per ogni stato (x-error-codes) ed eventi (webhooks). Questa guida spiega le regole che valgono per tutte le rotte. Gli esempi in examples/ sono provati a ogni giro contro il codice della piattaforma. Il documento OpenAPI è in inglese, si scarica senza chiave (GET /v1/openapi.json, con ETag e Cache-Control) e ha un esempio di richiesta e di risposta provato per ogni operazione. Ogni risposta d'errore porta error.doc_url, la pagina del suo codice (che cosa vuol dire, come si corregge): il catalogo intero è GET /v1/errors, anche lui senza chiave. Per cominciare: quickstart.it.md; per gli agenti di programmazione: AGENTS.md e il prompt pronto agent-prompt.md.

Indirizzo: https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api più il percorso (/v1/products…). Ogni risposta porta x-request-id (lo stesso valore è request_id nel corpo) e x-core-version: se ci scrivi, mandaci il request_id.

1. Chiavi e autenticazione

Ogni chiamata porta Authorization: Bearer <chiave>. La chiave si crea nel portale (Sviluppatori → Chiavi API) e si vede una volta sola: copiala subito in un posto sicuro.

formagai_<ambiente>_<prefisso di 8>_<segreto di 32><somma di 6>, per esempio gai_test_ab12cd34_…. Gli ultimi 6 caratteri sono la somma di controllo (CRC32 di tutto ciò che li precede, in base 62 0-9A-Za-z): una chiave troncata o ricopiata male si riconosce senza chiamarci, e la nostra porta la rifiuta prima di cercarla (401 CHIAVE_SOMMA_ERRATA). Le chiavi create prima del 5 novembre 2026 hanno 32 caratteri dopo il prefisso, senza somma, e continuano a valere: ruotale quando vuoi avere la somma
prefissogai_test_ab12cd34 è pubblico: lo vedi nel portale e nel registro attività, da solo non apre niente
ambientetest o live. Separa i dati, non solo l'etichetta: una chiave test vede solo il catalogo, i clienti e gli ordini di prova, una live solo quelli veri
permessicatalog:read, catalog:write, customers:read, customers:write, orders:read, orders:write, chat:write (aprire sessioni di chat dal tuo server). Nessuno ne contiene un altro: catalog:write non permette di leggere il catalogo
chiave pubblicabilegai_pk_… serve alla chat sul tuo sito, non ha permessi: su questa API riceve 403 AMBITO_MANCANTE
indirizzi IP ammessifacoltativi, per chiave (portale → la chiave → «Indirizzi IP ammessi»): reti CIDR o indirizzi singoli, al più 50. Una chiamata da fuori elenco, o di cui non conosciamo l'indirizzo, riceve 403 IP_NON_AMMESSO. Senza elenco la chiave si usa da ovunque
chiave per un agente AIfacoltativa, per chiave: le operazioni che tolgono o annullano qualcosa aspettano che una persona del negozio le approvi (§11)

Una chiave che non apre risponde 401 con un codice preciso: CHIAVE_ASSENTE, CHIAVE_MALFORMATA, CHIAVE_SOMMA_ERRATA, CHIAVE_SCONOSCIUTA, CHIAVE_REVOCATA, CHIAVE_SCADUTA, CHIAVE_INCOERENTE. Un negozio non attivo risponde 403 TENANT_SOSPESO; una chiave senza il permesso della rotta 403 AMBITO_MANCANTE; una chiave usata da un indirizzo che la sua politica non ammette 403 IP_NON_AMMESSO.

2. Errori

Un solo formato, su ogni rotta e per ogni errore, nostro o tuo:

{ "error": { "type": "richiesta_non_valida", "code": "PARAMETRO_NON_VALIDO", "message": "`limit` deve essere un intero fra 1 e 200.", "param": "limit" },
  "request_id": "6f1c…" }

  • code è ciò su cui programmi: i valori possibili di ogni rotta e stato sono in x-error-codes nel documento.
  • type è la famiglia, e dipende solo dallo stato HTTP: 400 e 405 richiesta_non_valida, 401 autenticazione, 403 autorizzazione, 404 non_trovato, 409 conflitto, 413 troppo_grande, 429 limite_richieste, 503 servizio_non_disponibile, altri 5xx errore_interno.
  • message è per chi legge e può cambiare; param c'è quando l'errore riguarda un campo o un parametro.
  • Un percorso che non esiste è 404 ROTTA_SCONOSCIUTA; un percorso che esiste con il metodo sbagliato è 405 METODO_NON_AMMESSO. La chiave si controlla prima del percorso: senza una chiave valida ricevi il 401.
  • Un 5xx non porta mai il dettaglio interno: il request_id basta a noi per ritrovarlo.

3. Idempotenza

Ogni chiamata che scrive (PUT /v1/products, PUT /v1/inventory, PUT /v1/customers, i POST …/ack) vuole l'intestazione Idempotency-Key: un valore tuo, al più 255 caratteri. Senza: 400 IDEMPOTENCY_KEY_MANCANTE.

  • Stessa chiave, stesso corpo: ricevi la stessa risposta (stato, corpo e request_id della prima volta) con idempotent-replayed: true, e niente viene rieseguito. Puoi quindi ripetere senza paura una chiamata di cui non hai visto la risposta (rete caduta, tempo scaduto).
  • Stessa chiave, corpo diverso: 409 IDEMPOTENCY_KEY_RIUSATA.
  • Stessa chiave mentre la prima chiamata è ancora in corso: 409 RICHIESTA_IN_CORSO; riprova fra qualche secondo.
  • La chiave vale per negozio e per ambiente (su tutte le chiavi API dello stesso ambiente): la stessa chiave usata prima con una chiave test e poi con una live esegue in live, senza rigiocare la risposta della prova. Scade dopo 24 ore: da lì la stessa chiave esegue di nuovo. Usa un valore nuovo per ogni operazione distinta (un UUID, o un id del tuo sistema come ack-<event_id>).
  • Viene registrato anche l'esito di una chiamata fallita dopo essere stata accettata (un 404 sull'ack di un ordine che non esiste, un 5xx): ripeterla con la stessa chiave ti ridà quell'esito, marcato idempotent-replayed. Per riprovare davvero serve una chiave nuova. Gli errori che arrivano prima (chiave API, permessi, limite, corpo non JSON o troppo grande, Idempotency-Key mancante o troppo lunga) non consumano la chiave.

4. Limiti

richiesteper chiave API, secondo il piano del negozio (tabella qui sotto): un ritmo sostenuto al secondo e una raffica che il secchio assorbe. Una chiave può avere un tetto suo al minuto, più basso. Oltre: 429 LIMITE_RICHIESTE con Retry-After. Ogni risposta dice quanto resta: RateLimit (qui sotto)
corpoal più 1 MiB (16 MiB per POST /v1/catalog/imports): oltre, 413 CORPO_TROPPO_GRANDE
lottial più 500 elementi per chiamata (50.000 per POST /v1/catalog/imports, §8-bis): oltre, 400 LOTTO_TROPPO_GRANDE; una lista vuota è 400 LOTTO_VUOTO
importazionial più 5 non finite per ambiente: oltre, 409 IMPORTAZIONI_IN_CORSO

I limiti per piano

pianochiavi testchiavi live
prova (nessun piano)5 al secondo, raffica 1205 al secondo, raffica 120
small10 al secondo, raffica 12025 al secondo, raffica 250
mid25 al secondo, raffica 25050 al secondo, raffica 500
enterprise25 al secondo, raffica 250100 al secondo, raffica 1000

Il limite si conta con un secchio per chiave: si riempie al ritmo del piano fino alla raffica, e ogni richiesta ne prende un gettone. Un gestionale che manda 250 richieste di fila con una chiave small live le vede passare tutte, poi prosegue a 25 al secondo; una richiesta respinta non consuma gettoni. Un contratto può fissare per il negozio un limite diverso da quello del piano (scritto da noi, mai implicito). Una chiave coniata con rate_limit_per_min ha in più il suo tetto al minuto, che vale solo se è più basso del piano; senza, segue il piano. Le chiavi test hanno limiti più bassi delle live, come nelle sandbox dei grandi fornitori: le prove di carico non si fanno in test.

Quanto resta: RateLimit-Policy e RateLimit

Ogni risposta di una rotta con chiave porta due intestazioni nella forma della bozza IETF draft-ietf-httpapi-ratelimit-headers (versione -11, 23 maggio 2026), così rallenti prima del 429 invece di scoprire il tetto sbattendoci contro:

RateLimit-Policy: "key";q=25;w=1;burst=250
RateLimit: "key";r=249;t=1

  • q è il ritmo sostenuto del piano, in richieste al secondo, w=1 la finestra di un secondo, burst la raffica (le richieste che passano di fila a secchio pieno).
  • r sono le richieste che puoi fare adesso, di fila, già tolta questa (i gettoni nel secchio); t i secondi al prossimo gettone. Ogni richiesta contata fa scendere r di uno, anche un rigioco con la stessa Idempotency-Key.
  • Se la chiave ha un tetto suo al minuto le liste hanno un secondo elemento, "key-minute";q=<tetto>;w=60 e "key-minute";r=<restano nel minuto>;t=<secondi alla fine del minuto>: vale il più stretto dei due.
  • Con r=0 la richiesta successiva prima di t secondi riceve 429, che porta r=0 e Retry-After uguale al t della politica che ha respinto.
  • Il 401, il 403 e il 404/405 di un percorso che non esiste arrivano prima del conteggio e non le portano; nemmeno le rotte senza chiave (/v1/openapi.json, /v1/errors, /v1/status). Il limite è per chiave: due chiavi dello stesso negozio hanno due secchi.
  • Un r positivo non è una garanzia (la bozza, §8.3): un 429 va gestito comunque.
  • Gli SDK ufficiali lo fanno da sé: con r=0 aspettano t secondi prima della richiesta successiva, e ritentano comunque sul 429 dopo Retry-After (docs/api/sdk.it.md; si spegne con throttle: false). Il server MCP porta le stesse due intestazioni, dallo stesso conteggio, a finestra di un minuto sul tetto equivalente del piano (docs/api/mcp.md, «I limiti»).

Un client che rallenta da sé (Node, fetch; l'esempio è eseguito dal nostro banco contro le intestazioni vere):

// Quanto aspettare prima della prossima richiesta, letto dalla risposta precedente.
function attesaMs(risposta) {
  let attesa = 0;                                // nessun limite dichiarato (rotta senza chiave, 401, 403): avanti
  // Un elemento per politica: il secchio del piano ("key") e, se c'e', il tetto al minuto della chiave ("key-minute").
  for (const m of (risposta.headers.get('ratelimit') ?? '').matchAll(/;r=(\d+);t=(\d+)/g)) {
    const restano = Number(m[1]), secondi = Number(m[2]);
    if (restano === 0) attesa = Math.max(attesa, secondi * 1000);      // quota finita: si aspetta t
    else if (restano < 10) attesa = Math.max(attesa, Math.ceil((secondi * 1000) / restano)); // quasi finita: si distribuisce il resto
  }
  return attesa;                                 // vale la politica più stretta
}

Nei lotti un elemento non valido non fa cadere il lotto: la risposta dice quanti ne sono arrivati, quanti scritti e quali rifiutati, con posizione e motivo.

{ "received": 3, "written": 2, "rejected": 1,
  "errors": [{ "index": 1, "id": "SKU-9", "code": "GTIN_NON_VALIDO", "message": "…" }],
  "request_id": "…" }

index è la posizione nel tuo lotto (da 0); è null quando a rifiutare è stato il database dopo la validazione (RIFIUTATA_DAL_DATABASE). Su PUT /v1/inventory uno SKU che non esiste è SKU_SCONOSCIUTO: non si crea un prodotto a metà. I prezzi si caricano nella valuta del negozio: un'altra valuta è VALUTA_DIVERSA_DAL_TENANT, non si converte.

5. Paginazione

  • Catalogo (GET /v1/products): ordinato per sku; limit da 1 a 200 (50 se manca); la pagina successiva si chiede con cursor = next_cursor della precedente. next_cursor c'è solo quando c'è davvero un'altra pagina: sull'ultima, anche se è piena, è null e il giro finisce senza chiamate in più. Filtri: sku, gtin.
  • Ordini e richieste di assistenza (GET /v1/orders, GET /v1/support_requests): dal più vecchio, limit da 1 a 200. Non c'è cursore: la coda avanza con l'ack. status=new (predefinito) dà ciò che non hai ancora confermato, status=acked ciò che hai confermato.

6. Eventi via webhook

Quando un cliente conferma un ordine (order.confirmed) o chiede una persona dello staff (support.requested), o quando il negozio comunica a che punto è un ordine (order.updated, sezione 7-bis), la piattaforma manda una POST firmata a ogni endpoint del negozio iscritto a quell'evento. Il pulsante «Manda un evento di prova» del portale manda un webhook.ping (ambiente test) al solo endpoint provato.

Le consegne seguono Standard Webhooks (specifica 1.0.0, https://www.standardwebhooks.com): la libreria ufficiale della tua lingua le verifica così come arrivano, senza niente di nostro da copiare.

Il corpo è sempre la stessa busta:

{ "id": "2b1e…", "type": "order.confirmed", "environment": "live", "timestamp": "2026-10-13T09:00:00.000Z",
  "occurred_at": "2026-10-13T09:00:00.000Z", "resource_id": "ORD-1042", "attempt": 1,
  "data": { "schema_version": 2, "order": { … } } }

data cambia con il tipo; le forme esatte sono nel documento (webhooks, schemi OrdineConfermato, RichiestaAssistenza, OrdineAggiornato, Ping). environment dice se è una prova o un fatto vero: gli endpoint sono gli stessi. timestamp (il campo di Standard Webhooks) e occurred_at sono lo stesso istante: quando è accaduto il fatto, non quando è partita la consegna.

Verificare la firma

Ogni consegna porta le tre intestazioni di Standard Webhooks:

intestazione
webhook-idl'id del messaggio: l'id dell'evento, uguale a ogni tentativo e a ogni riconsegna
webhook-timestampi secondi Unix di questo tentativo (cambia a ogni ritento)
webhook-signaturev1,<base64>, l'HMAC-SHA256 di <webhook-id>.<webhook-timestamp>.<corpo grezzo>; due, separate da uno spazio, mentre è in corso una rotazione del segreto

Si verifica con la libreria ufficiale (npm install standardwebhooks, pip install standardwebhooks), passando il corpo grezzo (i byte esatti ricevuti: rileggere e riscrivere il JSON li cambia) e il segreto così come il portale te l'ha mostrato, whsec_ compreso:

import { Webhook } from 'standardwebhooks';
const wh = new Webhook(process.env.GAI_WEBHOOK_SECRET);           // "whsec_..."
app.post('/webhooks', express.raw({ type: 'application/json' }), (req, res) => {
  let event;
  try { event = wh.verify(req.body.toString('utf8'), req.headers); }  // solleva se falsa, toccata o vecchia
  catch { return res.status(400).end(); }
  res.status(200).end();                                           // rispondi entro 15 secondi, lavora dopo
  // scarta i doppioni con req.headers['webhook-id'] (= event.id), poi tratta event.type
});

from standardwebhooks.webhooks import Webhook, WebhookVerificationError
wh = Webhook(os.environ["GAI_WEBHOOK_SECRET"])                    # "whsec_..."
def webhooks():                                                   # Flask; any framework works
    try:
        event = wh.verify(request.get_data(as_text=True), dict(request.headers))
    except WebhookVerificationError:
        return "", 400
    # scarta i doppioni con request.headers["webhook-id"] (= event["id"]), poi tratta event["type"]
    return "", 200
app.add_url_rule("/webhooks", view_func=webhooks, methods=["POST"])

La libreria rifiuta un webhook-timestamp che dista più di 300 secondi dal tuo orologio: una consegna vera intercettata e rimandata più tardi cade lì, anche con la firma giusta. Il segreto è whsec_ seguito dal base64 di 32 byte casuali; la chiave dell'HMAC sono i byte decodificati. Ricevitori completi e provati: examples/verify-standardwebhooks.mjs e examples/verify_standardwebhooks.py (librerie ufficiali); examples/verify-signature.mjs e examples/verify_signature.py fanno lo stesso senza nessuna dipendenza, per un ambiente in cui non puoi aggiungerne.

Ruotare il segreto

Attraverso il portale (POST /organizations/{org}/webhooks/{endpoint_id}/rotate-secret con {"overlap_hours": 0-72}) l'endpoint riceve un segreto nuovo, mostrato una volta. Per overlap_hours resta valido anche il vecchio: ogni consegna porta due firme, la nuova e la vecchia, e la libreria accetta l'una o l'altra. Metti il segreto nuovo nella tua configurazione entro quella finestra; 0 invalida subito il vecchio (per un segreto finito in mani sbagliate).

Rispondere e ritentare

  • Rispondi 2xx entro 15 secondi e lavora dopo. Qualunque altra risposta (un redirect compreso: non si segue), o nessuna risposta in tempo, è un tentativo fallito.
  • I tentativi sono dieci: il primo entro un minuto circa dall'evento, poi ciascuno dopo il precedente di 1 minuto, 5 minuti, 30 minuti, 2 ore, 5 ore, 10 ore, 14 ore, 20 ore e 24 ore (poco più di tre giorni in tutto), ogni ritardo variato fino al 10 % perché gli endpoint caduti insieme non vengano ritentati nello stesso secondo. Un'intestazione Retry-After nella tua risposta ci fa aspettare di più (fino a un giorno per quel tentativo), mai di meno. Dopo il decimo la consegna è abbandonata e lo vedi nel portale (Sviluppatori → Webhook → Consegne), da dove puoi rimandarla.
  • 410 Gone vuol dire «basta»: l'endpoint si disattiva subito (l'elenco degli endpoint del portale dice perché: disabled_reason: "http_410") e non riceve più niente finché non lo crei di nuovo. Ogni altro 4xx si ritenta come un 5xx: un endpoint che risponde 401 perché non ha ancora il segreto nuovo non perde niente.
  • Ogni tentativo è firmato di nuovo, con il suo webhook-timestamp e il suo attempt; webhook-id, id e data non cambiano.
  • Lo stesso evento può arrivarti più di una volta (un ritento dopo un 2xx che non ci è arrivato, una consegna rimandata dal portale): scarta i doppioni con webhook-id.
  • Il segreto si vede una volta sola, alla creazione dell'endpoint o alla rotazione. Un endpoint disattivato e poi riattivato riceve un segreto nuovo.

7. Ritiro in pull

Se non vuoi un endpoint in ingresso, ritiri ordini e richieste quando vuoi tu: GET /v1/orders?status=new (permesso orders:read), salvi, e confermi con POST /v1/orders/{order_id}/ack (permesso orders:write, con Idempotency-Key). Lo stesso per GET /v1/support_requests e POST /v1/support_requests/{support_id}/ack.

  • Vedi solo ciò che appartiene all'ambiente della tua chiave.
  • Ogni elemento porta event_id (lo stesso id del webhook), l'identificativo da passare all'ack, payload (lo stesso data del webhook), occurred_at e created_at, e stato (in_attesa finché non confermi, poi consegnato con consegnato_at).
  • Confermare due volte non è un errore. Finché non confermi, l'elemento torna a ogni lettura: salva per id, in modo idempotente, e se cadi fra il salvataggio e la conferma lo rivedrai, senza perderlo.
  • Gli ordini più vecchi dell'11/10/2026 sono nella versione 1 del contratto: niente schema_version, e il cliente ha il solo chatId.

Esempio completo e provato: examples/pull-orders.mjs.

7-bis. A che punto è l'ordine, e com'è andato

Dopo l'ack, il tuo sistema dice a GroceryAI che cosa succede all'ordine con una sola chiamata, la stessa per tutta la sua vita: POST /v1/orders/{order_id}/status (permesso orders:write, con Idempotency-Key). status è un codice:

  • avanzamento, prima dell'esito: preparing (in preparazione), ready (pronto, anche per il ritiro), out_for_delivery (in consegna), delayed (in ritardo), rescheduled (rinviato a una fascia nuova);
  • esito: delivered, substituted (con sostituzioni o voci mancanti, con delivered_amount), not_delivered, returned. È l'esito che conta per la fatturazione, e vale l'ultimo comunicato; l'avanzamento non la tocca mai.
{ "status": "out_for_delivery",
  "eta": { "start": "2026-11-06T17:00:00Z", "end": "2026-11-06T18:00:00Z" },
  "tracking_url": "https://tracking.example-carrier.com/t/ORD-1042" }

  • eta è la finestra prevista o concordata: obbligatoria con rescheduled (400 ETA_MANCANTE), facoltativa con out_for_delivery e delayed, vietata con gli altri stati (400 ETA_NON_AMMESSA); la fine dopo l'inizio, al più 24 ore dopo, l'inizio entro 30 giorni (400 DATA_NON_VALIDA).
  • reason è un codice, mai un testo: stock, capacity, traffic, weather, customer_request, shop_request, failed_attempt, other; solo con delayed, rescheduled e not_delivered (400 MOTIVO_NON_VALIDO). Il cliente legge la frase della sua lingua.
  • tracking_url va in https su un dominio di tracciamento dichiarato per il negozio (400 URL_NON_AMMESSO); per un corriere nuovo chiedi al supporto di dichiararne il dominio.
  • delivered_amount va solo con l'esito (400 IMPORTO_INCOERENTE con l'avanzamento).
  • Dopo un esito l'avanzamento non si registra più: 409 TRANSIZIONE_NON_AMMESSA. Un altro esito sì (vale l'ultimo).
  • Fra due avanzamenti vale il più recente per reported_at, non quello arrivato per ultimo: uno più vecchio si conserva e risponde superseded: true, senza evento.
  • Lo stesso stato ridetto (con un'altra Idempotency-Key) risponde duplicate: true e non produce un secondo evento.
  • Con una chiave agente l'avanzamento non chiede l'approvazione di una persona; not_delivered e returned sì (sezione 11).

La risposta ridice ciò che hai mandato, più kind (outcome o progress). Ogni comunicazione registrata diventa l'evento order.updated per gli endpoint iscritti (sezione 6): resource_id è l'identificativo della comunicazione, l'ordine è data.order.id, e il corpo non porta dati del cliente né importi. order.updated non si ritira in pull.

Il listino cambia ogni giorno: queste sono le vie per tenerlo vero senza ricaricare tutto.

  • Merge, di serie. PUT /v1/products aggiorna solo i campi che l'elemento nomina: un elemento con sku, title e price cambia il prezzo e lascia com'erano formato, pezzi, offerta, marca e reparto. Gli attributes si fondono con quelli che ci sono; per togliere un campo lo mandi a null. Lo stesso sku due volte nello stesso lotto: vale il primo.
  • I campi del contratto del catalogo si scrivono col loro nome nell'elemento (min_order_qty, min_order_unit, sold_by_weight, avg_piece_weight_kg, items_per_pack, pack_only, stock_managed, unit_price, gross_weight_kg, tare_kg, list_price, subcategory, description, vat_rate, diet_tags, offer_price, offer_start, offer_end, offer_min_qty, offer_label; is_online è available) e si validano come nel file del portale: un valore illeggibile ferma solo il suo elemento, con un code per campo.
  • Le informazioni alimentari (art. 14 del Reg. (UE) 1169/2011: per vendere a distanza un alimento preimballato vanno date prima dell'acquisto) sono campi facoltativi dello stesso elemento: allergens (i 14 dell'allegato II coi codici gluten, crustaceans, eggs, fish, peanuts, soybeans, milk, nuts, celery, mustard, sesame, sulphites, lupin, molluscs, o i codici GS1 come AW; none dichiara che non ce n'è nessuno), may_contain (le tracce), ingredients, nutrition_basis (100g o 100ml) con energy_kj, energy_kcal, fat_g, saturated_fat_g, carbohydrate_g, sugars_g, protein_g, salt_g, fibre_g, e storage_conditions, usage_instructions, food_business_operator, origin, alcohol_percent, food_info_url (la scheda, se le informazioni stanno in una pagina). Un campo assente vuol dire «non dichiarato»: l'assistente lo dice al cliente e non indovina mai un allergene. La risposta del lotto porta anche warnings: l'elemento è scritto, ma qualcosa non si userà (un'offerta che non sconta).
  • Prezzi, giacenze e offerte, leggeri. PUT /v1/inventory tocca solo ciò che l'elemento porta: price, stock_qty, available, il barrato list_price e l'offerta (offer_price, offer_start, offer_end). price resta il prezzo pieno; l'offerta vale nelle sue date, nel fuso del negozio, e finisce da sola.
  • Ritirare un prodotto. DELETE /v1/products/{sku} lo spegne, non lo cancella: l'assistente non lo vende più, gli ordini che lo citano restano leggibili. Per rimetterlo in vendita lo rimandi con PUT /v1/products.
  • «Questo è il catalogo intero». POST /v1/products/snapshots apre un'istantanea; mandi i lotti con PUT /v1/products e lo snapshot_id nel corpo; poi POST /v1/products/snapshots/{snapshot_id}/commit con {"dry_run": true} ti dice quanti prodotti attivi i lotti non hanno portato (to_switch_off) e i primi 20; lo richiami con {"expected_off": n} e quelli si ritirano. Se i lotti hanno portato meno del 90 % dei prodotti attivi non si ritira niente (409 ISTANTANEA_SOTTO_SOGLIA) e l'istantanea resta aperta: un file troncato non svuota il catalogo. Se il numero è cambiato fra la prova e la conferma, 409 CONTEGGIO_CAMBIATO e niente ritirato. L'istantanea vive 24 ore.
  • Il feed programmato. PUT /v1/catalog/feed con {"url": "https://…", "format": "google_merchant_xml"} (o google_merchant_tsv, csv, xlsx): lo leggiamo noi ogni every_hours ore (di serie 24), con le stesse regole del file del portale. Il feed prodotti di Google Merchant o Meta Commerce va bene così com'è: id, title, price, sale_price con sale_price_effective_date (le date dell'offerta), availability, gtin, brand, product_type, unit_pricing_measure, link, image_link. Con "mode": "snapshot" i prodotti che il feed non porta si ritirano, col cancello del 90 %. POST /v1/catalog/feed/run lo legge subito; GET /v1/catalog/feed dice com'è andato l'ultimo giro. L'URL deve essere https:// verso un nome pubblico.
  • La freschezza. Dichiari ogni quante ore aggiorni (PUT /v1/catalog/feed con {"declared_refresh_hours": 24}, anche senza feed); GET /v1/catalog/freshness dice l'ultimo aggiornamento e stale: true quando il catalogo è fermo da oltre il doppio.

8-bis. Il catalogo intero in una volta: le importazioni asincrone

Per un listino da decine di migliaia di referenze non servono ottanta lotti in fila: una chiamata, e il lavoro lo facciamo noi dopo, a pezzi. È il disegno delle Bulk Operations di Shopify: un'operazione con un id, lo stato da leggere, la fine come evento.

  1. Mandi il catalogo con POST /v1/catalog/imports e un Idempotency-Key, in uno di tre modi:
    • {"products": [...], "mode": "delta"}: fino a 50.000 elementi, gli stessi di PUT /v1/products (codici GS1 compresi), in un corpo fino a 16 MiB;
    • il CSV del file del portale nel corpo, con Content-Type: text/csv (e ?mode=snapshot nella query se è il catalogo intero);
    • {"url": "https://…", "format": "jsonl"}: l'indirizzo di un file che leggiamo noi, con le guardie del feed (fino a 40 MB). format è json (una lista, o {"products": [...]}), jsonl (un prodotto per riga, come i file di Shopify), csv o xlsx (il file del portale), google_merchant_xml o google_merchant_tsv.
  2. La risposta è subito 202 con l'importazione (status: queued, id) e l'intestazione Location, l'indirizzo del suo stato. Parte entro un minuto.
  3. Leggi lo stato con GET /v1/catalog/imports/{import_id} (una volta ogni 30 secondi basta): running mentre lavora (chunks_done su chunks_total, e written, rejected, warnings crescono), poi succeeded, partial (righe rifiutate, o il cancello dell'istantanea che non ha ritirato niente: error dice quale) o failed (error.code: l'indirizzo che non risponde, il file illeggibile, nessuna riga scritta…). GET /v1/catalog/imports le elenca.
  4. La fine arriva anche come evento catalog_import.completed agli endpoint iscritti (§6), con gli stessi numeri. Come per Shopify, una consegna di webhook può mancare: lo stato resta leggibile, sempre.
  5. I rifiuti, riga per riga: GET /v1/catalog/imports/{import_id}/errors (?type=warnings per gli avvisi), a pagine con cursor. Ogni riga dice index (la posizione in products, da 0) o row (la riga del file, con l'intestazione alla 1), lo sku, il code e il field. Con complete: true l'elenco è intero.

Le regole sono quelle che conosci: merge per sku come PUT /v1/products (o le regole del file del portale per CSV, XLSX e feed); lo stesso sku due volte nella stessa importazione vale il primo (SKU_RIPETUTO_NEL_LOTTO); con "mode": "snapshot" alla fine si ritirano le referenze attive che l'importazione non porta, col cancello del 90 % (con una chiave agente aspetta l'approvazione di una persona, §11). La stessa richiesta con lo stesso Idempotency-Key rende la stessa importazione, anche dopo le 24 ore del registro; una richiesta diversa con una chiave usata è 409 IDEMPOTENCY_KEY_RIUSATA. Se un pezzo non si riesce a scrivere (il database non risponde) si riprova al minuto dopo dal pezzo dove ci si era fermati, mai da capo; dopo cinque tentativi le sue righe tornano come PEZZO_NON_SCRITTO e il resto va avanti.

9. La chat del sito per il tuo cliente autenticato

Sulla chat del tuo sito il cliente è anonimo: il telefono, se lo scrive, nessuno lo verifica, e per questo la chat non apre il suo storico (mostrerebbe gli acquisti di una persona a chi digita il suo numero). Se il cliente è entrato nel tuo sito, il tuo server può garantirne l'identità, e da lì la chat è la sua: lo stesso carrello e la stessa conversazione da una visita all'altra, e il suo «solito» (lo storico di PUT /v1/order_history e gli ordini fatti in chat), come su WhatsApp.

Il cliente lo carichi prima con PUT /v1/customers ({"customers": [...]}), coi nomi di core.customers (external_ref, display_name, address, attributes) o con quelli del modello clienti della specifica (customer_ref, full_name, street, house_number, city, postal_code, floor, intercom, delivery_notes, language, exemption): gli indirizzi vanno in address col loro nome. Il telefono è internazionale (+39…), o la riga è rifiutata con TELEFONO_NON_E164. Un campo che non è di nessuno dei due elenchi non si scrive, e la risposta lo dice in warnings (CAMPO_SCONOSCIUTO); lo stesso dato in due posti con due valori diversi è CAMPO_IN_DUE_POSTI.

  1. Il tuo server chiede un gettone per quel cliente: POST /v1/chat_identity_tokens con la chiave segreta e il permesso chat:write, corpo {"customer_ref": "<external_ref del cliente>"} (facoltativo expires_in, in secondi: da 30 a 600, 300 se non lo dici). Il cliente deve esserci, nello stesso ambiente della chiave (PUT /v1/customers), o la risposta è 404 CLIENTE_SCONOSCIUTO.
  2. La risposta porta identity_token (gai_cid_test_… o gai_cid_live_…), expires_at e chat_id. Il gettone si vede solo in questa risposta: per questo la rotta non usa l'Idempotency-Key, e una chiamata ripetuta conia un altro gettone senza effetti in più. chat_id è l'identità di chat del cliente, sempre la stessa: è il customer.chatId degli ordini e delle richieste di assistenza che arrivano dalla sua chat, così li ricolleghi al tuo cliente.
  3. La pagina passa il gettone al widget (data-identity-token="…" accanto a data-site-key): il widget lo manda a core-chat /session come identity_token, con la tua chiave pubblicabile. In modalità server lo manda il tuo server stesso a /session, con la chiave segreta, e passa alla pagina il session_token.

Il gettone vale una volta sola e per pochi minuti, per il tuo negozio e per l'ambiente della chiave che l'ha coniato. Coniane uno quando componi la pagina per quel cliente, e servi quella pagina con Cache-Control: private, no-store: una pagina in cache servita a un altro visitatore porterebbe un gettone già usato, che non apre niente.

Senza gettone /session risponde come sempre. Con un gettone, la risposta ha in più identity: {"status": "verified"}, oppure {"status": "not_verified", "code": …} e la sessione nasce anonima, come oggi (la chat funziona lo stesso). I motivi: IDENTITA_MALFORMATA (non è un gettone), IDENTITA_SCONOSCIUTA (nessuno l'ha coniato, o l'ha coniato un altro negozio), IDENTITA_GIA_USATA, IDENTITA_SCADUTA, IDENTITA_DI_UN_ALTRO_AMBIENTE (coniato con la chiave test e usato con la live, o il contrario: resta buono per il suo ambiente), CLIENTE_SCONOSCIUTO (il cliente è stato tolto nel frattempo), IDENTITA_FUORI_DAL_NEGOZIO (la chat di prova del portale non porta un cliente), IDENTITA_NON_IN_SERVIZIO.

Esempi completi e provati, lato server: examples/chat-identity.mjs (Node) e examples/chat_identity.py (Python).

10. Versioni e deprecazione

Quello che costruisci oggi deve funzionare anche domani. Le regole:

  • La versione è nel percorso: /v1. x-core-version nelle risposte dice quale rilascio della piattaforma ha risposto, non la versione del contratto: non programmarci sopra.
  • Dentro /v1 cambiamo solo in modo compatibile: operazioni nuove, parametri e campi facoltativi nuovi nelle richieste, campi nuovi nelle risposte, codici d'errore nuovi, valori nuovi di campi che sono testo libero, tipi di evento nuovi, l'ordine dei campi, la lunghezza degli identificativi e il testo di error.message. Il tuo codice deve ignorare ciò che non conosce (un campo, un tipo di evento, un codice) invece di fallire. La regola vale dal 1° novembre 2026: prima alcune modifiche non compatibili sono entrate in /v1, quando l'API non aveva integratori in produzione, e il registro (CHANGELOG.md) le elenca tutte come tali.
  • Non compatibile è tutto ciò che può rompere un'integrazione scritta bene: togliere o rinominare un'operazione, un campo o un valore di un elenco chiuso (enum), cambiare un tipo, rendere obbligatorio un campo che non lo era, rifiutare un valore che prima si accettava, cambiare il significato di un campo o di un codice, cambiare l'ambito che un'operazione chiede, cambiare la firma dei webhook. Non lo facciamo dentro /v1: arriva con una versione nuova del percorso (/v2), oppure deprecando un'operazione e offrendone un'altra accanto.
  • Un'operazione deprecata funziona come prima per almeno 12 mesi dalla data di deprecazione. Lo vedi in tre posti: il documento OpenAPI la marca deprecated: true con x-deprecation (date e operazione sostituta); ogni sua risposta, riuscita o d'errore, porta le intestazioni
  Deprecation: @1793491200
  Sunset: Thu, 31 Dec 2099 23:59:59 GMT
  Link: <https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/openapi.json>; rel="deprecation"

dove Deprecation (RFC 9745) è la data di deprecazione in secondi dall'epoca dopo @, Sunset (RFC 8594) la data dalla quale l'operazione può smettere di rispondere (mai prima di 12 mesi dalla prima), e Link la pagina che dice che cosa usare al suo posto. Una chiamata respinta per la chiave (401) non le porta: la rotta non è ancora nota.

  • Il preavviso: il giorno della deprecazione scriviamo ai titolari del negozio (l'email dell'account nel portale) e pubblichiamo la voce nel registro delle modifiche (CHANGELOG.md), con la data di Sunset e la sostituta. Una versione del percorso che va in pensione (/v1 quando arriverà /v2) segue le stesse regole: 12 mesi, le stesse intestazioni su ogni sua risposta, lo stesso preavviso.
  • Il registro delle modifiche (CHANGELOG.md) elenca, giorno per giorno dal 7/9/2026, ogni cambiamento del contratto e se è compatibile.

Per provare il tuo codice che legge le intestazioni c'è una rotta di prova: GET /v1/_deprecation_probe con una chiave gai_test_… risponde 200 con le tre intestazioni qui sopra e le stesse date nel corpo (deprecated_at, sunset_at, replacement, link). Non è una funzione dell'API, non tocca i tuoi dati e non si ritira; con una chiave gai_live_… risponde 404 ROTTA_SCONOSCIUTA.

11. Chiavi per un agente AI e l'approvazione di una persona

Se dai la chiave a un agente AI (Claude Code, Codex, Cursor, un'automazione), creala nel portale con «Chiave per un agente AI». L'agente legge e scrive come con ogni chiave, ma le operazioni che tolgono o annullano qualcosa non si eseguono subito:

operazionequando aspetta
DELETE /v1/products/{sku}sempre
POST /v1/products/snapshots/{snapshot_id}/commitsenza dry_run: true (la prova risponde subito)
POST /v1/orders/{order_id}/statuscon status = not_delivered o returned
  1. L'agente chiama l'operazione come sempre e riceve 202 con data.id (l'approvazione), data.status = "pending" e data.next (che cosa fare). Niente è cambiato. Rimandare la stessa richiesta ritrova la stessa approvazione.
  2. Una persona del negozio (titolare o amministratore) la vede nel portale, Sviluppatori → Approvazioni, con l'operazione, il percorso e i dati, e la approva o la rifiuta.
  3. L'agente segue lo stato con GET /v1/approvals/{approval_id} (una volta al minuto basta). Quando è approved, rimanda la stessa richiesta (stesso metodo, percorso e corpo) con l'intestazione GroceryAI-Approval-Id: <id>: l'operazione si esegue, una volta sola. Puoi riusare la stessa Idempotency-Key della prima richiesta.

Che cosa può andare storto: 409 APPROVAZIONE_IN_ATTESA (nessuno ha ancora deciso), 409 APPROVAZIONE_RIFIUTATA, 409 APPROVAZIONE_SCADUTA (72 ore senza uso: chiedine una nuova), 409 APPROVAZIONE_GIA_USATA, 409 APPROVAZIONE_DIVERSA (la richiesta non è quella approvata), 404 APPROVAZIONE_SCONOSCIUTA (l'id non è di questa chiave). L'approvazione vale solo per la chiave che l'ha chiesta. Una chiave che non è «per un agente» lavora come prima, e l'intestazione non conta.

12. Lo stato del servizio

GET /v1/status, senza chiave, dice come sta il servizio adesso, componente per componente, e come è andato:

componenteche cos'è
assistantla conversazione che compone il carrello e l'ordine, su ogni canale
web_chatla chat sul sito del negozio
apiquesta API (/v1) e il feed programmato del catalogo
eventsi webhook, la coda in pull e le email d'ordine
portalil portale del negozio
mcpil server MCP per gli agenti AI
  • status: operational; degraded (risponde, ma una parte del lavoro fallisce: risposte 5xx, turni di conversazione con errore, consegne abbandonate o in ritardo, un lavoro programmato fermo); outage (non risponde come deve a due sonde di fila, una al minuto); unknown (non misurato: nessuna sonda, una sonda che non ha ancora completato un giro, o la misura è ferma). unknown non vuol dire attivo.
  • measured_at: l'ultima misura (una al minuto). Più vecchia di 3 minuti vuol dire ogni componente unknown.
  • availability.30d / availability.90d: calcolata sui soli minuti misurati, da from: ogni componente si conta da quando è nata la sua sonda (24 ottobre 2026; mcp dal 5 novembre 2026), e complete è false finché la sua storia non copre la finestra intera. uptime_percent conta i minuti outage; i minuti degraded si dicono a parte e non lo abbassano.
  • incidents: gli ultimi (al più 50 in 90 giorni), con started_at, last_seen_at (l'ultimo minuto in cui il guasto è stato visto) e resolved_at (un incidente si chiude dopo 10 minuti senza il guasto).

La risposta non contiene dati di nessun negozio. Cambia al più una volta al minuto: resta in cache 30 secondi e If-None-Match con l'ultimo ETag dà 304. Interrogala al più una volta al minuto. Se lo stato stesso non si può leggere la risposta è 503 STATO_NON_MISURABILE: lo stato è sconosciuto, e non dice niente degli altri componenti.

Riferimento delle rotte

Il riferimento è in inglese, come il documento OpenAPI di Core. I codici (error.code), i tipi (error.type) e valori come stato sono identificatori italiani stabili; error.message è in italiano e può cambiare.

The GroceryAI platform API, from your systems to ours: catalog, prices and stock, customers, order status (including what happened to an order after the shop took it: delivered, substituted, not delivered, returned).

Authentication: one API key per account, sent as Authorization: Bearer gai_live_…. Keys have an environment (test or live) that separates the data, not just the labels, and scopes (catalog:read, catalog:write, customers:read, customers:write, orders:read, orders:write, chat:write, history:write, rules:read, rules:write, texts:read, texts:write). The plain value is shown only once.

Batches: writes accept up to 500 items per call; each item is validated on its own and the rejected ones are listed in the response instead of failing the whole batch.

Idempotency: every call that writes requires Idempotency-Key. Replaying it with the same body returns the same response without running it again. The key is scoped to the environment (test and live never see each other) and expires after 24 hours.

Traceability: every response, successful or not, carries request_id. It is the only thing we ask for when you contact us.

Events: confirmed orders and customer support requests reach the shop's endpoint as webhooks signed according to Standard Webhooks (see webhooks; https://www.standardwebhooks.com: verify them with the official library for your language), or are pulled (GET /v1/orders, GET /v1/support_requests) and acknowledged.

Errors: a single format, {"error": {"type", "code", "message", "param", "doc_url"}, "request_id"}. Program against code; doc_url links to the code's page (what it means, how to fix it, whether retrying helps). The full catalog: GET /v1/errors.

No key needed: this document (GET /v1/openapi.json) and the error catalog (GET /v1/errors, GET /v1/errors/{code}) are readable without a key, with ETag and Cache-Control. Every other operation requires a key.

Getting started: with a gai_test_… key you work in the test environment, separate from real data. Every operation below has a request and a 200-response example (and every error response an example envelope): the examples are valid against the schemas and were sent to the test environment, but the data is illustrative; your test shop returns its own. Recommended first call: GET /v1/products?limit=1.

Versions and deprecation: the contract version is in the path (/v1). Within /v1 we only make compatible changes (new operations, optional fields, response fields, error codes, event types): your code must ignore what it does not know. An incompatible change only comes with a new path version, or by deprecating an operation: a deprecated operation carries deprecated: true here and the Deprecation (RFC 9745), Sunset (RFC 8594) and Link: rel="deprecation" headers on every response, and stays in service for at least 12 months; notice is sent by email to the shop owners and published in the changelog. To try them: GET /v1/_deprecation_probe with a gai_test_… key.

Language: this document is in English; codes (error.code), types (error.type) and values such as stato are stable Italian identifiers, and error.message is in Italian and may change.

Autenticazione

http bearerThe account's API key (gai_test_… or gai_live_…). A publishable key (gai_pk_…) has no scopes: here it receives 403 AMBITO_MANCANTE.

Gli ambiti delle chiavi

Ogni operazione chiede un ambito alla chiave; una chiave senza l'ambito riceve 403 AMBITO_MANCANTE. Qui ogni ambito con le operazioni che lo chiedono.

GET/v1/openapi.json

The OpenAPI document of this API

Generated from the same route table that serves the calls, so it cannot drift from the behaviour. Downloadable without a key from a stable address, with ETag and Cache-Control: with If-None-Match equal to the ETag the response is 304 with no body.

Nessuna chiave: si chiama senza autenticazione.

Parametri

  • If-None-Matchintestazionestring

    The ETag of a previous read: if the content has not changed the response is 304 with no body.

Esempio

Risposta 200

{
  "openapi": "3.1.0",
  "info": {
    "title": "GroceryAI Platform API",
    "version": "1.0.0"
  },
  "paths": {
    "/v1/products": {
      "get": {
        "operationId": "getProducts"
      }
    }
  }
}

Risposte

GET/v1/errors

The error code catalog

Every code this API can return in error.code, in a batch's errors[].code or in warnings[].code: what it means, how to fix it, with which statuses and in which operations it appears. No key needed.

Nessuna chiave: si chiama senza autenticazione.

Parametri

  • If-None-Matchintestazionestring

    The ETag of a previous read: if the content has not changed the response is 304 with no body.

Esempio

Risposta 200

{
  "data": [
    {
      "code": "IDEMPOTENCY_KEY_MANCANTE",
      "title": "This operation writes data and needs an `Idempotency-Key` header.",
      "how_to_fix": "Generate a unique value per logical operation (a UUID v4 is ideal), send it as `Idempotency-Key`, and reuse the same value only when retrying that same request.",
      "retryable": false,
      "appears_as": {
        "error": [
          {
            "status": 400,
            "type": "richiesta_non_valida",
            "operations": [
              "putProducts",
              "createProductSnapshot",
              "commitProductSnapshot",
              "putCatalogFeed",
              "runCatalogFeed",
              "createCatalogImport",
              "putInventory",
              "putCustomers",
              "putOrderHistory",
              "putStores",
              "putRules",
              "putStoreTexts",
              "ackOrder",
              "reportOrderStatus",
              "ackSupportRequest"
            ]
          }
        ],
        "batch_item_error": [],
        "batch_item_warning": [],
        "chat_session_identity": false
      },
      "doc_url": "https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/IDEMPOTENCY_KEY_MANCANTE"
    }
  ]
}

Risposte

GET/v1/errors/{code}

The page of one error code

The page error.doc_url points to: what the code means, how to fix it, the statuses and operations in which it appears. No key needed.

Nessuna chiave: si chiama senza autenticazione.

Parametri

  • codenel percorsostringobbligatorio

    The code, as written in error.code (for example IDEMPOTENCY_KEY_MANCANTE).

  • If-None-Matchintestazionestring

    The ETag of a previous read: if the content has not changed the response is 304 with no body.

Esempio

Risposta 200

{
  "data": {
    "code": "IDEMPOTENCY_KEY_MANCANTE",
    "title": "This operation writes data and needs an `Idempotency-Key` header.",
    "how_to_fix": "Generate a unique value per logical operation (a UUID v4 is ideal), send it as `Idempotency-Key`, and reuse the same value only when retrying that same request.",
    "retryable": false,
    "appears_as": {
      "error": [
        {
          "status": 400,
          "type": "richiesta_non_valida",
          "operations": [
            "putProducts",
            "createProductSnapshot",
            "commitProductSnapshot",
            "putCatalogFeed",
            "runCatalogFeed",
            "createCatalogImport",
            "putInventory",
            "putCustomers",
            "putOrderHistory",
            "putStores",
            "putRules",
            "putStoreTexts",
            "ackOrder",
            "reportOrderStatus",
            "ackSupportRequest"
          ]
        }
      ],
      "batch_item_error": [],
      "batch_item_warning": [],
      "chat_session_identity": false
    },
    "doc_url": "https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/errors/IDEMPOTENCY_KEY_MANCANTE"
  }
}

Risposte

GET/v1/status

The status of the service, per component

For each component (assistant, web_chat, api, events, portal, mcp) its status now, from the same rules as the internal alarms that measure the service every minute: operational, degraded (it answers, but part of the work fails: 5xx responses, conversation turns with errors, abandoned or late deliveries, stopped scheduled jobs), outage (it does not answer as it should to two probes in a row) or unknown (not measured: no probe, measurement stopped for more than 3 minutes or failing for more than 10). Then availability over the last 30 and 90 days, on measured minutes only (with from and complete: the history starts on 2026-10-24), and the latest incidents with start, last impact and resolution (an incident is resolved after 10 minutes without errors). No key, no data about any shop. Updated at most once a minute: Cache-Control of 30 seconds, ETag and 304.

Nessuna chiave: si chiama senza autenticazione.

Parametri

  • If-None-Matchintestazionestring

    The ETag of a previous read: if the content has not changed the response is 304 with no body.

Esempio

Risposta 200

{
  "status": "operational",
  "measured_at": "2026-10-31T09:15:00.000Z",
  "measured_since": "2026-10-24T12:51:00.000Z",
  "components": [
    {
      "id": "assistant",
      "name": "Shopping assistant",
      "description": "The conversation that builds the cart and the order, on every channel.",
      "status": "operational",
      "availability": {
        "30d": {
          "window_days": 30,
          "from": "2026-10-24T12:51:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 5,
          "uptime_percent": 100
        },
        "90d": {
          "window_days": 90,
          "from": "2026-10-24T12:51:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 5,
          "uptime_percent": 100
        },
        "month": {
          "month": "2026-10",
          "from": "2026-10-24T12:51:00.000Z",
          "to": "2026-10-31T09:15:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 5,
          "downtime_minutes": 5,
          "availability_percent": 99.951,
          "objective_percent": 99.9,
          "objective_met": true
        },
        "previous_month": null
      }
    },
    {
      "id": "web_chat",
      "name": "Web chat",
      "description": "The chat on the shop's website.",
      "status": "operational",
      "availability": {
        "30d": {
          "window_days": 30,
          "from": "2026-10-24T12:51:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 4,
          "degraded_minutes": 0,
          "uptime_percent": 99.96
        },
        "90d": {
          "window_days": 90,
          "from": "2026-10-24T12:51:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 4,
          "degraded_minutes": 0,
          "uptime_percent": 99.96
        },
        "month": {
          "month": "2026-10",
          "from": "2026-10-24T12:51:00.000Z",
          "to": "2026-10-31T09:15:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 4,
          "degraded_minutes": 0,
          "downtime_minutes": 4,
          "availability_percent": 99.96,
          "objective_percent": 99.9,
          "objective_met": true
        },
        "previous_month": null
      }
    },
    {
      "id": "api",
      "name": "API",
      "description": "The REST API for catalog, customers, orders and events (`/v1`), and the scheduled catalog feed.",
      "status": "operational",
      "availability": {
        "30d": {
          "window_days": 30,
          "from": "2026-10-24T12:51:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "uptime_percent": 100
        },
        "90d": {
          "window_days": 90,
          "from": "2026-10-24T12:51:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "uptime_percent": 100
        },
        "month": {
          "month": "2026-10",
          "from": "2026-10-24T12:51:00.000Z",
          "to": "2026-10-31T09:15:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "downtime_minutes": 0,
          "availability_percent": 100,
          "objective_percent": 99.9,
          "objective_met": true
        },
        "previous_month": null
      }
    },
    {
      "id": "events",
      "name": "Webhooks and order delivery",
      "description": "Signed events to your endpoints, the pull queue and the order emails.",
      "status": "operational",
      "availability": {
        "30d": {
          "window_days": 30,
          "from": "2026-10-24T12:51:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "uptime_percent": 100
        },
        "90d": {
          "window_days": 90,
          "from": "2026-10-24T12:51:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "uptime_percent": 100
        },
        "month": {
          "month": "2026-10",
          "from": "2026-10-24T12:51:00.000Z",
          "to": "2026-10-31T09:15:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "downtime_minutes": 0,
          "availability_percent": 100,
          "objective_percent": 99.9,
          "objective_met": true
        },
        "previous_month": null
      }
    },
    {
      "id": "portal",
      "name": "Merchant portal",
      "description": "The portal where shops manage their catalog, keys and settings.",
      "status": "operational",
      "availability": {
        "30d": {
          "window_days": 30,
          "from": "2026-10-24T12:51:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "uptime_percent": 100
        },
        "90d": {
          "window_days": 90,
          "from": "2026-10-24T12:51:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "uptime_percent": 100
        },
        "month": {
          "month": "2026-10",
          "from": "2026-10-24T12:51:00.000Z",
          "to": "2026-10-31T09:15:00.000Z",
          "complete": false,
          "measured_minutes": 10104,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "downtime_minutes": 0,
          "availability_percent": 100,
          "objective_percent": 99.9,
          "objective_met": true
        },
        "previous_month": null
      }
    },
    {
      "id": "mcp",
      "name": "MCP server",
      "description": "The Model Context Protocol server for AI agents.",
      "status": "operational",
      "availability": {
        "30d": {
          "window_days": 30,
          "from": "2026-10-30T12:00:00.000Z",
          "complete": false,
          "measured_minutes": 1275,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "uptime_percent": 100
        },
        "90d": {
          "window_days": 90,
          "from": "2026-10-30T12:00:00.000Z",
          "complete": false,
          "measured_minutes": 1275,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "uptime_percent": 100
        },
        "month": {
          "month": "2026-10",
          "from": "2026-10-30T12:00:00.000Z",
          "to": "2026-10-31T09:15:00.000Z",
          "complete": false,
          "measured_minutes": 1275,
          "outage_minutes": 0,
          "degraded_minutes": 0,
          "downtime_minutes": 0,
          "availability_percent": 100,
          "objective_percent": 99.9,
          "objective_met": true
        },
        "previous_month": null
      }
    }
  ],
  "incidents": [
    {
      "components": [
        "web_chat"
      ],
      "severity": "outage",
      "status": "resolved",
      "started_at": "2026-10-30T07:02:00.000Z",
      "last_seen_at": "2026-10-30T07:05:00.000Z",
      "resolved_at": "2026-10-30T07:15:00.000Z"
    },
    {
      "components": [
        "assistant"
      ],
      "severity": "degraded",
      "status": "resolved",
      "started_at": "2026-10-28T10:30:00.000Z",
      "last_seen_at": "2026-10-28T10:34:00.000Z",
      "resolved_at": "2026-10-28T10:44:00.000Z"
    }
  ]
}

Risposte

PUT/v1/products

Create or update the catalog, in batches

Upsert by sku, as a MERGE: on an existing product only the fields the item names are updated, and the ones it does not name stay as they were; attributes are merged, and a key set to null is removed. The catalog contract fields (min_order_qty, min_order_unit, sold_by_weight, avg_piece_weight_kg, items_per_pack, pack_only, stock_managed, unit_price, gross_weight_kg, tare_kg, list_price, subcategory, description, vat_rate, diet_tags, offer_price, offer_start, offer_end, offer_min_qty, offer_label; is_online is available) are written with their name on the item and validated. A withdrawn product (DELETE or snapshot) that is sent again goes back on sale. gtin is optional, but if present it must be a valid GTIN/GS1 (8, 12, 13 or 14 digits, check digit included): a wrong barcode is worse than none. With snapshot_id the batch is part of a snapshot (POST /v1/products/snapshots).

Permesso: catalog:write

Parametri

  • Idempotency-Keyintestazionestringobbligatorio

    A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

    maxLength: 255

Corpo della richiestaobbligatorio

Batch of products. At most 500 items per call; each item is validated on its own, and the rejected ones are listed in the response instead of failing the whole batch.

object

  • productsarray<ProdottoInIngresso>obbligatorio

    minItems: 1maxItems: 500

  • snapshot_idstring

    Optional: the snapshot opened with POST /v1/products/snapshots that this batch belongs to.

    format: uuid

Esempio

Corpo della richiesta

{
  "products": [
    {
      "sku": "EXAMPLE-SPAGHETTI-500",
      "title": "Spaghetti di semola 500 g",
      "gtin": "4006381333931",
      "brand": "Esempio",
      "category": "Pasta",
      "unit": "pz",
      "price": 1.29,
      "currency": "EUR",
      "stock_qty": 140,
      "available": true,
      "vat_rate": 4,
      "link": "https://shop.example.invalid/p/spaghetti-500",
      "image_link": "https://shop.example.invalid/img/spaghetti-500.jpg"
    },
    {
      "sku": "EXAMPLE-MILK-1L",
      "title": "Latte intero 1 l",
      "brand": "Esempio",
      "category": "Latte e derivati",
      "unit": "pz",
      "price": 1.49,
      "stock_qty": 60
    }
  ]
}

Risposta 200

{
  "received": 2,
  "written": 2,
  "rejected": 0,
  "errors": [],
  "warnings": [],
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

GET/v1/products

List the catalog

Sorted by sku. Cursor pagination: cursor is the last sku of the previous page.

Permesso: catalog:read

Parametri

  • skunella querystring

    A single product, by SKU.

  • gtinnella querystring

    The products with this GTIN.

  • limitnella queryinteger

    From 1 to 200 (default 50).

    minimum: 1maximum: 200

  • cursornella querystring

    Last sku of the previous page.

  • store_codenella querystring

    The catalog as it is in one store (GET /v1/stores): price, strikethrough price, offer, stock and availability of the store where it declares them, the shop's where it does not.

Esempio

Risposta 200

{
  "data": [
    {
      "sku": "EXAMPLE-SPAGHETTI-500",
      "gtin": "4006381333931",
      "title": "Spaghetti di semola 500 g",
      "brand": "Esempio",
      "category": "Pasta",
      "unit": "pz",
      "price": 1.29,
      "net_price": null,
      "currency": "EUR",
      "stock_qty": 140,
      "available": true,
      "link": "https://shop.example.invalid/p/spaghetti-500",
      "image_link": "https://shop.example.invalid/img/spaghetti-500.jpg",
      "attributes": {
        "vat_rate": 4
      }
    }
  ],
  "next_cursor": "EXAMPLE-SPAGHETTI-500",
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

DELETE/v1/products/{sku}

Withdraw a product from sale

The product is switched off (available: false, with the withdrawal date in attributes.withdrawn_at), not deleted: orders and history that mention it stay readable, and the assistant stops selling it. Withdrawing the same product twice is not an error. To put it back on sale, send it again with PUT /v1/products. With an agent key it waits for a person's approval (202).

Permesso: catalog:write

Parametri

  • skunel percorsostringobbligatorio

    The product's sku.

Esempio

Risposta 200

{
  "data": {
    "sku": "EXAMPLE-MILK-1L",
    "available": false,
    "withdrawn": true
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

POST/v1/products/snapshots

Open a catalog snapshot ("this is the whole catalog")

To say the catalog you send is the WHOLE catalog: open the snapshot, send the batches with PUT /v1/products and the snapshot_id, and close it with commit. On commit, the active products that no batch carried are withdrawn (switched off, not deleted), but only if the batches carried at least 90% of the active products (the threshold can be declared): a truncated file does not empty the catalog. A snapshot lives 24 hours.

Permesso: catalog:write

Parametri

  • Idempotency-Keyintestazionestringobbligatorio

    A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

    maxLength: 255

Corpo della richiesta

Empty, or {}.

object

Empty, or {}.

maxProperties: 0

Esempio

Corpo della richiesta

{}

Risposta 200

{
  "data": {
    "snapshot_id": "3b9f0e62-1d4a-4c8e-a7b2-5f6e9d0c1a23",
    "expires_at": "2026-11-01T09:15:00Z",
    "active_products": 1240
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

POST/v1/products/snapshots/{snapshot_id}/commit

Commit the snapshot: withdraw the products the batches did not carry

With dry_run: true it only returns the numbers (active, carried, to withdraw, the share, the threshold, the first 20 skus to withdraw) and changes nothing. Without it, it requires expected_off, the number to withdraw read in the dry run: if it changed in the meantime nothing is withdrawn (409 CONTEGGIO_CAMBIATO). Below the threshold nothing is withdrawn (409 ISTANTANEA_SOTTO_SOGLIA) and the snapshot stays open: the missing batches can still be sent. With an agent key the real commit (without dry_run) waits for a person's approval (202).

Permesso: catalog:write

Parametri

  • snapshot_idnel percorsostringobbligatorio

    The snapshot identifier.

  • Idempotency-Keyintestazionestringobbligatorio

    A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

    maxLength: 255

Corpo della richiesta

{dry_run: true} for the dry run; {expected_off: n} to withdraw.

Esempio

Corpo della richiesta

{
  "dry_run": true
}

Risposta 200

{
  "data": {
    "snapshot_id": "3b9f0e62-1d4a-4c8e-a7b2-5f6e9d0c1a23",
    "active": 1240,
    "seen_active": 1228,
    "to_switch_off": 12,
    "share": 0.9903,
    "min_share": 0.9,
    "allowed": true,
    "count_changed": false,
    "dry_run": true,
    "switched_off": 0,
    "sample": [
      "EXAMPLE-OLD-001",
      "EXAMPLE-OLD-002"
    ]
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

GET/v1/catalog/freshness

How fresh the catalog is

The last catalog update (any channel: file, API, feed), the refresh interval the shop declared, and whether the catalog has been unchanged for more than twice that interval (stale).

Permesso: catalog:read

Esempio

Risposta 200

{
  "data": {
    "environment": "test",
    "last_update_at": "2026-10-31T09:15:00Z",
    "age_hours": 2.5,
    "declared_refresh_hours": 24,
    "stale": false,
    "products": 1240,
    "available": 1198
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

GET/v1/catalog/feed

The scheduled catalog feed and its last run

The configuration (URL, format, how many hours apart, delta or snapshot, on or off, the declared refresh interval) and the outcome of the last run. A shop that never configured it receives data: null.

Permesso: catalog:read

Esempio

Risposta 200

{
  "data": {
    "url": "https://shop.example.invalid/feed/products.csv",
    "format": "csv",
    "every_hours": 6,
    "mode": "delta",
    "enabled": true,
    "declared_refresh_hours": 24,
    "next_run_at": "2026-10-31T15:15:00Z",
    "last_run_at": null,
    "last_run": null,
    "updated_at": "2026-10-31T09:15:00Z"
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

PUT/v1/catalog/feed

Configure the scheduled feed and the declared refresh interval

An https:// URL that GroceryAI reads every every_hours hours (24 by default): our CSV or XLSX, or the Google Merchant / Meta Commerce product feed (XML or TSV). mode: snapshot withdraws the products the feed does not carry, behind the 90% gate; the default delta only updates. declared_refresh_hours is how often the shop updates prices and stock (through any channel): past twice that, the catalog is flagged as stale. The interval can be declared without a feed (url: null).

Permesso: catalog:write

Parametri

  • Idempotency-Keyintestazionestringobbligatorio

    A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

    maxLength: 255

Corpo della richiestaobbligatorio

{url, format, every_hours, mode, enabled, declared_refresh_hours}.

Esempio

Corpo della richiesta

{
  "url": "https://shop.example.invalid/feed/products.csv",
  "format": "csv",
  "every_hours": 6,
  "mode": "delta",
  "enabled": true,
  "declared_refresh_hours": 24
}

Risposta 200

{
  "data": {
    "url": "https://shop.example.invalid/feed/products.csv",
    "format": "csv",
    "every_hours": 6,
    "mode": "delta",
    "enabled": true,
    "declared_refresh_hours": 24,
    "next_run_at": "2026-10-31T15:15:00Z",
    "last_run_at": null,
    "last_run": null,
    "updated_at": "2026-10-31T09:15:00Z"
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

POST/v1/catalog/feed/run

Run the feed now

The same run as the scheduler, right now: reads the URL, prepares the rows with the rules of the portal file import, writes them as a merge and, in mode: snapshot, withdraws the missing ones behind the gate. The run is recorded even when it fails.

Permesso: catalog:write

Parametri

  • Idempotency-Keyintestazionestringobbligatorio

    A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

    maxLength: 255

Corpo della richiesta

Empty, or {}.

object

Empty, or {}.

maxProperties: 0

Esempio

Corpo della richiesta

{}

Risposta 200

{
  "data": {
    "status": "ok",
    "error_code": null,
    "message": null,
    "received": 1240,
    "written": 1240,
    "rejected": 0,
    "switched_off": 0,
    "errors": [],
    "snapshot": null,
    "started_at": "2026-10-31T09:15:00Z",
    "finished_at": "2026-10-31T09:15:04Z"
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

POST/v1/catalog/imports

Import the whole catalog, asynchronously

For the whole catalog in one call: up to 50,000 products in the body (products: the same items as PUT /v1/products, GS1 codes included), a CSV in the body (Content-Type: text/csv, the columns of the portal file; mode in the query), or the address of a file (url and format: json, jsonl, csv, xlsx, google_merchant_xml, google_merchant_tsv). The body can be up to 16 MiB. The answer is an IMMEDIATE 202 with the import (status: queued) and Location: the work happens afterwards, in chunks of 500 items, with the rules of PUT /v1/products (merge by sku) or of the portal file. Read the status with GET /v1/catalog/imports/{import_id}, the rejected rows with .../errors, and the end arrives as a catalog_import.completed event at the subscribed endpoints. The same sku twice in the same import: the first one wins. mode: snapshot withdraws, at the end, the active products the import does not carry, behind the 90 % gate (with an agent key it waits for a person's approval). At most 5 unfinished imports per environment.

Permesso: catalog:write

Parametri

  • modenella querystring

    Only with a CSV body: delta (default) or snapshot. With a JSON body, mode goes in the body.

  • Idempotency-Keyintestazionestringobbligatorio

    A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

    maxLength: 255

Corpo della richiesta

{"products": [...], "mode": "delta"}, or {"url": "https://...", "format": "jsonl", "mode": "snapshot"}, or the text of a CSV with Content-Type: text/csv.

Esempio

Corpo della richiesta

{
  "products": [
    {
      "sku": "EXAMPLE-SPAGHETTI-500",
      "gtin": "8000000000017",
      "title": "Spaghetti n.5 500 g",
      "brand": "Esempio",
      "category": "Pasta",
      "price": 1.29,
      "stock_qty": 240
    },
    {
      "sku": "EXAMPLE-MILK-1L",
      "title": "Latte intero 1 l",
      "category": "Latte e derivati",
      "price": 1.49,
      "available": true
    }
  ],
  "mode": "delta"
}

Risposta 202

{
  "data": {
    "id": "3c9e7a51-2f4b-4d8e-9a16-5b7c0d2e4f81",
    "status": "queued",
    "mode": "delta",
    "source": "body",
    "format": "json",
    "url": null,
    "received": 2,
    "written": 0,
    "rejected": 0,
    "warnings": 0,
    "switched_off": 0,
    "chunks_total": 1,
    "chunks_done": 0,
    "error": null,
    "snapshot": null,
    "created_at": "2026-10-31T09:15:00.000Z",
    "started_at": null,
    "finished_at": null,
    "links": {
      "self": "https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/catalog/imports/3c9e7a51-2f4b-4d8e-9a16-5b7c0d2e4f81",
      "errors": "https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/catalog/imports/3c9e7a51-2f4b-4d8e-9a16-5b7c0d2e4f81/errors"
    }
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

GET/v1/catalog/imports

The catalog imports, most recent first

Cursor pagination: cursor is the id of the last import of the previous page.

Permesso: catalog:read

Parametri

  • limitnella queryinteger

    From 1 to 100 (default 20).

    minimum: 1maximum: 100

  • cursornella querystring

    The id of the last import of the previous page.

Esempio

Risposta 200

{
  "data": [
    {
      "id": "3c9e7a51-2f4b-4d8e-9a16-5b7c0d2e4f81",
      "status": "partial",
      "mode": "delta",
      "source": "url",
      "format": "jsonl",
      "url": "https://shop.example.invalid/export/products.jsonl",
      "received": 38412,
      "written": 38408,
      "rejected": 4,
      "warnings": 12,
      "switched_off": 0,
      "chunks_total": 77,
      "chunks_done": 77,
      "error": null,
      "snapshot": null,
      "created_at": "2026-10-31T09:15:00.000Z",
      "started_at": "2026-10-31T09:15:41.000Z",
      "finished_at": "2026-10-31T09:19:02.000Z",
      "links": {
        "self": "https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/catalog/imports/3c9e7a51-2f4b-4d8e-9a16-5b7c0d2e4f81",
        "errors": "https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/catalog/imports/3c9e7a51-2f4b-4d8e-9a16-5b7c0d2e4f81/errors"
      }
    }
  ],
  "next_cursor": null,
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

GET/v1/catalog/imports/{import_id}

The status of a catalog import

status: queued (waiting: it starts within a minute), running (in progress: chunks_done out of chunks_total, and the counts grow), succeeded, partial (rejected rows, or the snapshot gate that withdrew nothing: error), failed (error says why). received, written, rejected and warnings count the items (or the rows of the file).

Permesso: catalog:read

Parametri

  • import_idnel percorsostringobbligatorio

    The id returned by POST /v1/catalog/imports.

Esempio

Risposta 200

{
  "data": {
    "id": "3c9e7a51-2f4b-4d8e-9a16-5b7c0d2e4f81",
    "status": "partial",
    "mode": "delta",
    "source": "url",
    "format": "jsonl",
    "url": "https://shop.example.invalid/export/products.jsonl",
    "received": 38412,
    "written": 38408,
    "rejected": 4,
    "warnings": 12,
    "switched_off": 0,
    "chunks_total": 77,
    "chunks_done": 77,
    "error": null,
    "snapshot": null,
    "created_at": "2026-10-31T09:15:00.000Z",
    "started_at": "2026-10-31T09:15:41.000Z",
    "finished_at": "2026-10-31T09:19:02.000Z",
    "links": {
      "self": "https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/catalog/imports/3c9e7a51-2f4b-4d8e-9a16-5b7c0d2e4f81",
      "errors": "https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/catalog/imports/3c9e7a51-2f4b-4d8e-9a16-5b7c0d2e4f81/errors"
    }
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

GET/v1/catalog/imports/{import_id}/errors

The rejected rows (or the warnings) of an import, row by row

Each row says where (index of the JSON item, from 0, or row of the file, with the header on row 1), which sku, the code and the field. The rows are those of the chunks already written: once the import is finished (complete: true) the list is whole. type=warnings for the warnings (rows written with something to know).

Permesso: catalog:read

Parametri

  • import_idnel percorsostringobbligatorio

    The id of the import.

  • typenella querystring

    errors (default) or warnings.

  • limitnella queryinteger

    From 1 to 1000 (default 500).

    minimum: 1maximum: 1000

  • cursornella querystring

    The next_cursor of the previous page.

Esempio

Risposta 200

{
  "data": [
    {
      "index": 1204,
      "row": null,
      "id": "EXAMPLE-OLIVE-OIL-1L",
      "code": "PREZZO_NON_VALIDO",
      "field": "price",
      "message": "`price` deve essere un numero >= 0."
    },
    {
      "index": 20877,
      "row": null,
      "id": "EXAMPLE-SPAGHETTI-500",
      "code": "SKU_RIPETUTO_NEL_LOTTO",
      "field": "sku",
      "message": "Questo `sku` e' gia' in un elemento precedente della stessa importazione: vale il primo."
    },
    {
      "index": 31002,
      "row": null,
      "id": null,
      "code": "ELEMENTO_NON_JSON",
      "field": null,
      "message": "La riga non e' JSON: Unexpected end of JSON input"
    },
    {
      "index": 36511,
      "row": null,
      "id": "EXAMPLE-RICE-1KG",
      "code": "PEZZO_NON_SCRITTO",
      "field": null,
      "message": "Il pezzo non si e' potuto scrivere dopo 5 tentativi: connessione chiusa. Rimanda queste righe."
    }
  ],
  "next_cursor": null,
  "complete": true,
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

PUT/v1/inventory

Update prices, stock and offers, in batches

Touches ONLY the fields present in each item (price, net_price, stock_qty, available or is_online, the strikethrough price list_price and the offer offer_price, offer_start, offer_end, offer_min_qty, offer_label, null to remove it): whatever is not named stays as it was. An SKU that does not exist is a rejected item, not a half-created product. With store_code the item applies to THAT store (GET /v1/stores) and carries only price, stock_qty, available or is_online, list_price, offer_price, offer_start, offer_end (otherwise CAMPO_NON_PER_PUNTO_VENDITA): the shop-wide row is not touched, and whatever the store does not declare stays the shop's. A code that is not an active store is a rejected item (PUNTO_VENDITA_SCONOSCIUTO).

Permesso: catalog:write

Parametri

  • Idempotency-Keyintestazionestringobbligatorio

    A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

    maxLength: 255

Corpo della richiestaobbligatorio

Batch of stock and prices. At most 500 items per call; each item is validated on its own, and the rejected ones are listed in the response instead of failing the whole batch.

object

Esempio

Corpo della richiesta

{
  "inventory": [
    {
      "sku": "EXAMPLE-SPAGHETTI-500",
      "price": 1.19,
      "stock_qty": 120
    },
    {
      "sku": "EXAMPLE-MILK-1L",
      "available": false
    }
  ]
}

Risposta 200

{
  "received": 2,
  "written": 2,
  "rejected": 0,
  "errors": [],
  "warnings": [],
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

PUT/v1/customers

Sync customers, in batches

Upsert by external_ref, the identifier the customer has in your system.

Permesso: customers:write

Parametri

  • Idempotency-Keyintestazionestringobbligatorio

    A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

    maxLength: 255

Corpo della richiestaobbligatorio

Batch of customers. At most 500 items per call; each item is validated on its own, and the rejected ones are listed in the response instead of failing the whole batch.

object

Esempio

Corpo della richiesta

{
  "customers": [
    {
      "external_ref": "example-customer-001",
      "display_name": "Giulia Esempio",
      "email": "giulia@example.invalid",
      "phone": "+390000000001",
      "street": "Via delle Prove",
      "house_number": "1",
      "city": "Olbia",
      "postal_code": "07026",
      "language": "it"
    }
  ]
}

Risposta 200

{
  "received": 1,
  "written": 1,
  "rejected": 0,
  "errors": [],
  "warnings": [],
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

PUT/v1/order_history

Load the shop's order history, in batches

One row per order line, upsert by order_ref + sku: an optional field the row does not carry stays as it was. The customer is identified by E.164 phone (phone) or by their customer_ref (the external_ref of PUT /v1/customers). From this the assistant learns each customer's "usual": the products, the quantities of the last purchase, the last order. History is matched to a customer only when the channel guarantees the phone number (WhatsApp): in the web chat the customer types the number, and it opens nobody's history. Only for shops that live on GroceryAI (409 STORICO_SOLO_NEGOZI_NATIVI for shops that read history from their own connector).

Permesso: history:write

Parametri

  • Idempotency-Keyintestazionestringobbligatorio

    A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

    maxLength: 255

Corpo della richiestaobbligatorio

Batch of order lines. At most 500 items per call; each item is validated on its own, and the rejected ones are listed in the response instead of failing the whole batch.

object

Esempio

Corpo della richiesta

{
  "order_history": [
    {
      "order_ref": "EXAMPLE-ORDER-0001",
      "sku": "EXAMPLE-SPAGHETTI-500",
      "title": "Spaghetti di semola 500 g",
      "quantity": 2,
      "unit_price": 1.29,
      "customer_ref": "example-customer-001",
      "order_date": "2026-10-20",
      "status": "delivered"
    },
    {
      "order_ref": "EXAMPLE-ORDER-0001",
      "sku": "EXAMPLE-MILK-1L",
      "title": "Latte intero 1 l",
      "quantity": 1,
      "unit_price": 1.49,
      "customer_ref": "example-customer-001",
      "order_date": "2026-10-20",
      "status": "delivered"
    }
  ]
}

Risposta 200

{
  "received": 2,
  "written": 2,
  "rejected": 0,
  "errors": [],
  "warnings": [],
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

GET/v1/stores

Read the shop's stores

The list of stores (store_code, name, city, address, timezone, is_active), with principal (the shop's own store: it serves locations no zone covers), the zones each one serves and a preview of its catalog: products.sellable (products sellable there), own_price (those with a store-specific price), not_sold_here (those not sold there). A shop with a single store reads zero: its store is implicit.

Permesso: catalog:read

Esempio

Risposta 200

{
  "data": {
    "environment": "test",
    "catalog_products": 1240,
    "stores": [
      {
        "store_code": "OLB-01",
        "name": "Bottega Esempio Centro",
        "city": "Olbia",
        "address": "Via delle Prove 1",
        "timezone": "Europe/Rome",
        "is_active": true,
        "principal": true,
        "zones": [],
        "products": {
          "sellable": 1240,
          "own_price": 0,
          "not_sold_here": 0
        }
      }
    ]
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

PUT/v1/stores

Write the shop's stores

The body {stores: [...]} is the COMPLETE list: a store that is not named is switched off (never deleted). Each item: store_code (letters, digits, _ . -, up to 64), name, city, optional address and timezone (IANA; absent = the shop's), is_active. The first store is the shop's own. A store that serves an active delivery zone cannot be switched off (409 PUNTO_VENDITA_CON_ZONE): move the zone first. Zones choose their store in the portal (Delivery page, the zone's store_code); per-store prices arrive with PUT /v1/inventory and store_code.

Permesso: catalog:write

Parametri

  • Idempotency-Keyintestazionestringobbligatorio

    A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

    maxLength: 255

Corpo della richiestaobbligatorio

{stores: [{store_code, name, city, address?, timezone?, is_active?}]}, at most 200.

Esempio

Corpo della richiesta

{
  "stores": [
    {
      "store_code": "OLB-01",
      "name": "Bottega Esempio Centro",
      "city": "Olbia",
      "address": "Via delle Prove 1",
      "timezone": "Europe/Rome",
      "is_active": true
    }
  ]
}

Risposta 200

{
  "data": {
    "environment": "test",
    "catalog_products": 1240,
    "stores": [
      {
        "store_code": "OLB-01",
        "name": "Bottega Esempio Centro",
        "city": "Olbia",
        "address": "Via delle Prove 1",
        "timezone": "Europe/Rome",
        "is_active": true,
        "principal": true,
        "zones": [],
        "products": {
          "sellable": 1240,
          "own_price": 0,
          "not_sold_here": 0
        }
      }
    ]
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

GET/v1/rules

Read the shop's rules

The rules document the assistant applies: minimum order, payment methods, delivery fee and free-delivery threshold per zone, bank transfer details, prepayment, cash only with own delivery, discounts (welcome, welcome back, loyalty tiers, excluded on offers), friend codes, heavy-goods extras, order edit window, checkout upsell, cart reminder, delivery slot on send; plus the version to start from when writing it. Only for shops created in the portal (409 REGOLE_SOLO_NEGOZI_DEL_PORTALE).

Permesso: rules:read

Esempio

Risposta 200

{
  "data": {
    "version": 4,
    "currency": "EUR",
    "min_order_amount": "25.00",
    "payment_methods": [
      "cash",
      "card_pos"
    ],
    "payment_methods_source": "shop",
    "zones": [
      {
        "zone_slug": "centro",
        "is_active": true,
        "delivery_cost": "3.90",
        "free_threshold": "60.00"
      }
    ],
    "bank_transfer": null,
    "bank_transfer_ready": false,
    "prepaid_flow": "none",
    "cash_requires_own_delivery": false,
    "discounts": null,
    "friend_codes": null,
    "heavy_extras": null,
    "order_edit_window_hours": null,
    "checkout_upsell": null,
    "cart_reminder": true,
    "slot_on_send": "propose",
    "matches_version": null,
    "updated_at": "2026-10-31T09:15:00Z",
    "updated_by": "api_key:1201"
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

PUT/v1/rules

Write the shop's rules, versioned

The whole document of GET /v1/rules with based_on_version (the version you read): min_order_amount, payment_methods and zones are required, the commercial rules optional (absent = they stay as they are). Every write that changes something creates a version, like the portal; an outdated based_on_version is 409 VERSIONE_CAMBIATA. Field errors are all collected in errors: [{field, code, message}], with the message in the ?lang= language (it, en, es, fr, de, pt). Rules are one per shop: only a key of the environment the shop runs in can write them (409 AMBIENTE_DEL_NEGOZIO).

Permesso: rules:write

Parametri

  • langnella querystring

    The language of error messages (it, en, es, fr, de, pt; en by default).

  • Idempotency-Keyintestazionestringobbligatorio

    A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

    maxLength: 255

Corpo della richiestaobbligatorio

The rules document with based_on_version.

Esempio

Corpo della richiesta

{
  "based_on_version": 3,
  "min_order_amount": "25.00",
  "payment_methods": [
    "cash",
    "card_pos"
  ],
  "zones": [
    {
      "zone_slug": "centro",
      "delivery_cost": "3.90",
      "free_threshold": "60.00"
    }
  ],
  "cart_reminder": true,
  "slot_on_send": "propose"
}

Risposta 200

{
  "data": {
    "version": 4,
    "currency": "EUR",
    "min_order_amount": "25.00",
    "payment_methods": [
      "cash",
      "card_pos"
    ],
    "payment_methods_source": "shop",
    "zones": [
      {
        "zone_slug": "centro",
        "is_active": true,
        "delivery_cost": "3.90",
        "free_threshold": "60.00"
      }
    ],
    "bank_transfer": null,
    "bank_transfer_ready": false,
    "prepaid_flow": "none",
    "cash_requires_own_delivery": false,
    "discounts": null,
    "friend_codes": null,
    "heavy_extras": null,
    "order_edit_window_hours": null,
    "checkout_upsell": null,
    "cart_reminder": true,
    "slot_on_send": "propose",
    "matches_version": null,
    "updated_at": "2026-10-31T09:15:00Z",
    "updated_by": "api_key:1201",
    "changed": true
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

POST/v1/rules/preview

Preview what the customer will read with these rules (writes nothing)

The same body as PUT /v1/rules (based_on_version optional) plus example_subtotal and lang: the blocks the assistant would render (delivery per zone, totals, summary, minimum order) and commerce (each tier's discount, the friend code, the heavy-goods extra, the welcome discount that is not shown if the phrase states a different percentage), rendered by the assistant's renderer with the shop's language pack.

Permesso: rules:read

Corpo della richiesta

The rules document, with optional example_subtotal and lang.

Esempio

Corpo della richiesta

{
  "min_order_amount": "25.00",
  "payment_methods": [
    "cash",
    "card_pos"
  ],
  "zones": [
    {
      "zone_slug": "centro",
      "delivery_cost": "3.90",
      "free_threshold": "60.00"
    }
  ],
  "example_subtotal": "42.00",
  "lang": "en"
}

Risposta 200

{
  "data": {
    "zones": [
      {
        "zone_slug": "centro",
        "blocks": [
          "Delivery to centro costs €3.90, free over €60.00."
        ]
      }
    ],
    "min_order": "The minimum order is €25.00.",
    "commerce": {
      "discounts": null,
      "friend_codes": null,
      "heavy_extras": null
    },
    "missing_keys": [],
    "fallbacks": []
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

GET/v1/store_texts

Read the shop's texts and site settings

The template phrases of the language pack that the shop can rewrite (with the original phrase), the assistant's hours, the departments with their emoji, the basic weekly shopping list and, in the site block, the site paths (categories, FAQ, offers, delivery rates).

Permesso: texts:read

Esempio

Risposta 200

{
  "data": {
    "default_lang": "it",
    "languages": [
      "it",
      "en"
    ],
    "phrases": [
      {
        "key": "greeting",
        "base": "Ciao! Sono l'assistente del negozio.",
        "lang": "it",
        "text": "Ciao! Sono l'assistente di Bottega Esempio.",
        "customized": true
      }
    ],
    "assistant_hours": null,
    "departments": [],
    "weekly_shop_base_list": [
      "latte",
      "pane",
      "uova",
      "frutta"
    ],
    "site": {
      "origin": "https://shop.example.invalid",
      "faq_path": "/faq",
      "offers_path": "/offerte",
      "category_paths": [],
      "delivery_rates_path": null
    }
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

PUT/v1/store_texts

Write the shop's texts and site settings

Only the fields to change: phrases: [{lang, key, text|null}] (a phrase from the closed list, keeping the original phrase's placeholders and without links; null reverts to the original phrase), assistant_hours, departments, weekly_shop_base_list, site: {category_paths, faq_path, offers_path, delivery_rates_path}. Errors collected in errors, in the ?lang= language.

Permesso: texts:write

Parametri

  • langnella querystring

    The language of error messages (it, en, es, fr, de, pt; en by default).

  • Idempotency-Keyintestazionestringobbligatorio

    A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

    maxLength: 255

Corpo della richiestaobbligatorio

The fields to change.

Esempio

Corpo della richiesta

{
  "weekly_shop_base_list": [
    "latte",
    "pane",
    "uova",
    "frutta"
  ]
}

Risposta 200

{
  "data": {
    "default_lang": "it",
    "languages": [
      "it",
      "en"
    ],
    "phrases": [
      {
        "key": "greeting",
        "base": "Ciao! Sono l'assistente del negozio.",
        "lang": "it",
        "text": "Ciao! Sono l'assistente di Bottega Esempio.",
        "customized": true
      }
    ],
    "assistant_hours": null,
    "departments": [],
    "weekly_shop_base_list": [
      "latte",
      "pane",
      "uova",
      "frutta"
    ],
    "site": {
      "origin": "https://shop.example.invalid",
      "faq_path": "/faq",
      "offers_path": "/offerte",
      "category_paths": [],
      "delivery_rates_path": null
    },
    "changed": true
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

GET/v1/customers/{external_ref}

Read a customer

An external_ref of another account answers 404, not 403: whether someone else's record exists is not information to give out.

Permesso: customers:read

Parametri

  • external_refnel percorsostringobbligatorio

    The customer's identifier in your system.

Esempio

Risposta 200

{
  "data": {
    "external_ref": "example-customer-001",
    "display_name": "Giulia Esempio",
    "email": "giulia@example.invalid",
    "phone": "+390000000001",
    "address": {
      "street": "Via delle Prove",
      "house_number": "1",
      "city": "Olbia",
      "postal_code": "07026"
    },
    "attributes": {
      "language": "it"
    }
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

GET/v1/orders

Orders to take over (pull)

The alternative to webhooks for those who do not want an inbound endpoint: read status=new and confirm with the ack. Reads the platform's event log (outbox), filtered by the key's environment: a test key sees test orders, a live key the real ones.

Permesso: orders:read

Parametri

  • statusnella querystring

    new (default) or acked.

  • limitnella queryinteger

    From 1 to 200 (default 50).

    minimum: 1maximum: 200

Esempio

Risposta 200

{
  "data": [
    {
      "event_id": "8a4e2c10-5b3f-4d9a-b1c7-0e6f2a9d3b58",
      "order_id": "ORD-20261031-0042",
      "type": "order.confirmed",
      "payload": {
        "schema_version": 2,
        "order": {
          "id": "ORD-20261031-0042",
          "status": "confirmed",
          "lines": [
            {
              "sku": "EXAMPLE-SPAGHETTI-500",
              "name": "Spaghetti di semola 500 g",
              "brand": "Esempio",
              "qty": 2,
              "unit": "pz",
              "unit_price": 1.29,
              "out_of_catalog": false
            },
            {
              "sku": null,
              "name": "Basilico fresco",
              "brand": null,
              "qty": 1,
              "unit": null,
              "unit_price": null,
              "out_of_catalog": true
            }
          ],
          "totals": {
            "subtotal": 2.58,
            "discounts": 0,
            "delivery": 3.9,
            "extras": 0,
            "total": 6.48
          },
          "delivery": {
            "startISO": "2026-11-01T08:00:00.000Z",
            "endISO": "2026-11-01T10:00:00.000Z",
            "label": "domenica 1 novembre, 9:00-11:00"
          },
          "customer": {
            "chatId": "web:7d0c2b9e",
            "channel": "web",
            "fullName": "Giulia Esempio",
            "address": "Via delle Prove 1",
            "city": "Olbia",
            "zip": "07026",
            "phone": null,
            "email": null,
            "notes": null,
            "missing_fields": [
              "phone",
              "email"
            ]
          },
          "notes": "Citofono Esempio",
          "currency": "EUR"
        }
      },
      "occurred_at": "2026-10-31T09:10:00Z",
      "created_at": "2026-10-31T09:10:01Z",
      "stato": "in_attesa",
      "consegnato_at": null
    }
  ],
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

POST/v1/orders/{order_id}/ack

Acknowledge that you took over an order

From then on the order no longer appears in status=new. Acknowledging the same order twice is not an error: it returns the same response.

Permesso: orders:write

Parametri

  • order_idnel percorsostringobbligatorio

    The order identifier.

  • Idempotency-Keyintestazionestringobbligatorio

    A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

    maxLength: 255

Corpo della richiesta

Empty, or {}.

object

Empty, or {}.

maxProperties: 0

Esempio

Corpo della richiesta

{}

Risposta 200

{
  "data": {
    "order_id": "ORD-20261031-0042",
    "status": "acked"
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

POST/v1/orders/{order_id}/status

Report where an order stands or how it went: progress and outcome

The shop says how the order went after taking it over: delivered (delivered_amount optional; absent = in full), substituted (delivered with substitutions; delivered_amount required), not_delivered, returned (returned after delivery; delivered_amount = what is kept, even 0). It can be reported more than once: the last report counts, and all are recorded with who made them (the key) and when. An order with no report stays as it was sent. Before the outcome the same call reports PROGRESS, which does not count for billing: preparing, ready, out_for_delivery and delayed (with the expected window eta, optional), rescheduled (with the new window eta, required); reason (a code) with delayed, rescheduled and not_delivered; tracking_url on a declared tracking domain. After an outcome progress is no longer recorded (409). Every recorded report becomes the order.updated event; the same status reported again answers duplicate: true without a second event. With an agent key not_delivered and returned wait for a person's approval (202); progress does not.

Permesso: orders:write

Parametri

  • order_idnel percorsostringobbligatorio

    The order identifier (order.id of the order.confirmed event).

  • Idempotency-Keyintestazionestringobbligatorio

    A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

    maxLength: 255

Corpo della richiesta

The order status and, when needed, the value of the goods delivered.

Esempio

Corpo della richiesta

{
  "status": "substituted",
  "delivered_amount": 5.98,
  "note": "Latte intero sostituito con latte parzialmente scremato."
}

Risposta 200

{
  "data": {
    "order_id": "ORD-20261031-0042",
    "status": "substituted",
    "delivered_amount": 5.98,
    "source": "api",
    "reported_at": "2026-10-31T09:15:00Z",
    "received_at": "2026-10-31T09:15:00Z",
    "duplicate": false,
    "kind": "outcome"
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

GET/v1/support_requests

Customer support requests to take over (pull)

A chat customer asked for a person, made a complaint or wants to change an order already sent: the request travels the same way as orders. Read status=new and confirm with the ack. Filtered by the key's environment, like orders.

Permesso: orders:read

Parametri

  • statusnella querystring

    new (default) or acked.

  • limitnella queryinteger

    From 1 to 200 (default 50).

    minimum: 1maximum: 200

Esempio

Risposta 200

{
  "data": [
    {
      "support_id": "support:web:7d0c2b9e:1",
      "event_id": "0c7b3e91-2f4a-4b6d-8e15-9a3c7d2f4e60",
      "type": "support.requested",
      "payload": {
        "schema_version": 1,
        "support_request": {
          "id": "support:web:7d0c2b9e:1",
          "kind": "modify_order",
          "outcome": "nuova",
          "customer_message": "Posso aggiungere del latte all'ordine di domani?",
          "lang": "it",
          "channel": "web",
          "order_code": "ORD-20261031-0042",
          "customer": {
            "chatId": "web:7d0c2b9e",
            "channel": "web",
            "fullName": "Giulia Esempio",
            "address": "Via delle Prove 1",
            "city": "Olbia",
            "zip": "07026",
            "phone": null,
            "email": null,
            "notes": null,
            "missing_fields": [
              "phone",
              "email"
            ]
          }
        }
      },
      "occurred_at": "2026-10-31T09:12:00Z",
      "created_at": "2026-10-31T09:12:01Z",
      "stato": "in_attesa",
      "consegnato_at": null
    }
  ],
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

POST/v1/support_requests/{support_id}/ack

Acknowledge that you took over a support request

From then on the request no longer appears in status=new. Acknowledging the same request twice is not an error: it returns the same response.

Permesso: orders:write

Parametri

  • support_idnel percorsostringobbligatorio

    The request identifier (support_request.id).

  • Idempotency-Keyintestazionestringobbligatorio

    A key chosen by the caller. The same key with the same body returns the same response without running again; with a different body it is a 409.

    maxLength: 255

Corpo della richiesta

Empty, or {}.

object

Empty, or {}.

maxProperties: 0

Esempio

Corpo della richiesta

{}

Risposta 200

{
  "data": {
    "support_id": "support:web:7d0c2b9e:1",
    "status": "acked"
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

POST/v1/chat_identity_tokens

Open the website chat for one of your signed-in customers: a short-lived, single-use token

When the customer has signed in to your website, your server requests a token for them (customer_ref = their external_ref from PUT /v1/customers) and passes it to the page; the widget sends it to core-chat /session as identity_token. From then on the chat is THEIRS: the same cart and the same conversation from one visit to the next, and their history (PUT /v1/order_history and orders placed in chat), that is the "usual" as on WhatsApp. The token is valid for your shop and the key's environment, for at most expires_in seconds (300 if omitted, between 30 and 600), and ONCE only: never put it in a page a cache could serve to someone else. It is shown only in this response (our database keeps only its hash), so the route does not use Idempotency-Key: a repeated call mints another token, with no other effect. Without a token, or with one that does not pass, the chat stays anonymous and /session says why (identity). chat_id is the customer's chat identity, always the same: it is the customer.chatId of the orders and support requests that come from their chat. Only for shops that live on GroceryAI.

Permesso: chat:write

Corpo della richiesta

customer_ref and, optionally, expires_in in seconds.

Esempio

Corpo della richiesta

{
  "customer_ref": "example-customer-001",
  "expires_in": 300
}

Risposta 200

{
  "data": {
    "identity_token": "gai_cid_test_8Qm2ZpR4vT7xLc9NbF3kHs6WdJ1yAe5UoGi0XtKq",
    "expires_at": "2026-10-31T09:20:00Z",
    "chat_id": "cv_4f9a2c7e1b3d5f6a8c0e2b4d6f8a1c3e",
    "customer_ref": "example-customer-001"
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

GET/v1/approvals/{approval_id}

The status of an approval requested by an agent key

An agent key calling a destructive operation receives 202 with an approval: a person at the shop approves or rejects it in the portal. This operation says where it stands: pending (waiting), approved (send the same request again with GroceryAI-Approval-Id), rejected, consumed (already used) or expired (72 hours without use). Only the key that requested it can see it.

Permesso: basta una chiave segreta valida, senza un permesso particolare.

Parametri

  • approval_idnel percorsostringobbligatorio

    The approval id (data.id of the 202 response).

Esempio

Risposta 200

{
  "data": {
    "object": "approval",
    "id": "a0000000-0000-4000-8000-000000000001",
    "status": "pending",
    "operation_id": "deleteProduct",
    "method": "DELETE",
    "path": "/v1/products/EXAMPLE-MILK-1L",
    "environment": "test",
    "created_at": "2026-11-05T10:00:00.000Z",
    "expires_at": "2026-11-08T10:00:00.000Z",
    "decided_at": null,
    "consumed_at": null
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

GET/v1/_deprecation_probe

DeprecataRitiro non prima del 2099-12-31Rotta di prova: deprecata per costruzione, non si ritira mai.

Test route: the headers of a deprecated operation

Not a feature of the API: it exists so that integrators can see, with a gai_test_… key, the headers they would receive from a deprecated operation (Deprecation, RFC 9745; Sunset, RFC 8594; Link with rel="deprecation") and test their own code that reads them. It is deprecated by construction, with a distant Sunset, and is never retired. It does not touch the shop's data. With a gai_live_… key it returns 404 ROTTA_SCONOSCIUTA.

Permesso: basta una chiave segreta valida, senza un permesso particolare.

Esempio

Risposta 200

{
  "data": {
    "probe": true,
    "deprecated_at": "2026-11-01T00:00:00Z",
    "sunset_at": "2099-12-31T23:59:59Z",
    "replacement": null,
    "link": "https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api/v1/openapi.json"
  },
  "request_id": "6f1c9a2e-4b7d-4e0a-9c3f-2d8b5e7a1c40"
}

Risposte

Errori del percorso, su ogni rotta

  • 404 ROTTA_SCONOSCIUTANo route for that method and path.
  • 405 METODO_NON_AMMESSOThe path exists, but not for that method (a 404 would send you looking for a URL that does exist).

Intestazioni delle risposte

  • x-request-idstring

    The identifier of THIS call: equal to request_id in the body, except on replay (idempotent-replayed: true), where the body is the original call's and carries its request_id.

  • x-core-versionstring

    The platform version that answered.

  • retry-afterinteger

    Seconds to wait before retrying: until the next token of the plan's bucket, or until the end of the minute if the key's own cap refused the request. Always equal to the t parameter of the refusing policy in the RateLimit header of the same response.

  • ratelimit-policystring

    This key's rate-limit policy, in the form of the IETF draft draft-ietf-httpapi-ratelimit-headers (version -11, §3). The limit comes from the store's plan and is counted with a bucket: "key";q=<requests per second>;w=1;burst=<burst>, where q is the sustained rate, w a one-second window and burst how many requests in a row pass when the bucket is full (an extra parameter the draft allows, §3.1 and appendix C). If the key has its own per-minute cap, lower than the plan, the list carries a second item "key-minute";q=<requests>;w=60 (a calendar minute). Before per-plan limits the form was "key";q=<requests>;w=60. It is on every response of a keyed route except 401 and 403, which come before counting (like a 404 or 405 for a path that does not exist); unkeyed routes (/v1/openapi.json, /v1/errors, /v1/status) do not carry it.

  • ratelimitstring

    What is left, in the form of the IETF draft draft-ietf-httpapi-ratelimit-headers (version -11, §4): "key";r=<remaining>;t=<seconds>. r is how many requests this key may make right now, in a row, this one already counted (the tokens in the bucket); t the seconds to the next token (1 for a rate of at least one request per second). With the key's own per-minute cap there is a second item "key-minute";r=<left in the minute>;t=<seconds to the end of the minute>. It comes from the same count that decides the 429: with r=0 the next request before t seconds gets 429 with Retry-After equal to t. A client that reads it slows down before getting there (for example: with a low r, it spreads the remaining requests over the t seconds). A positive r is not a guarantee (the draft, §8.3).

  • cache-controlstring

    How long a cache may keep the response without asking again: public, max-age=300 for the documentation, public, max-age=30 for the service status; no-store on an error.

  • etagstring

    The content fingerprint (sha256 of the bytes served). Send it back in If-None-Match to get 304 if nothing changed.

  • access-control-allow-originstring

    Always *: the documentation can also be read from a browser or a tool running in a web page.

  • access-control-expose-headersstring

    The headers a web page can read: etag, x-request-id, x-core-version.

  • deprecationstring

    RFC 9745: the operation is deprecated from the given date, in seconds since the epoch after @ (for example @1793491200). It keeps working as before until the Sunset.

  • sunsetstring

    RFC 8594: from this date (HTTP-date, for example Sat, 01 Jan 2028 00:00:00 GMT) the operation may stop responding. It is never earlier than 12 months after the Deprecation date.

  • linkstring

    RFC 9745 §3: <address>; rel="deprecation", the page that says what to use instead (this document: the operation carries x-deprecation).

  • locationstring

    The address of the status of the accepted resource (data.links.self): read it with GET until it is finished. It is there also when the answer is replayed with the same Idempotency-Key.

  • idempotent-replayedstring

    true when the response is the replay of a call already executed with the same Idempotency-Key: same status, same body, same request_id as the first time, and no new execution.

Eventi dei webhook

order.confirmed

A customer confirmed an order in the shop's chat. Sent once per order (resource_id = the order identifier) to every endpoint subscribed to order.confirmed; the same order can also be pulled with GET /v1/orders.

Intestazioni

  • webhook-idintestazionestringobbligatorio

    The message identifier: the event id, the same on every attempt and on every redelivery. It is the key to drop duplicates with.

    format: uuid

  • webhook-timestampintestazionestringobbligatorio

    Unix seconds of the instant of the ATTEMPT (not of the fact): it changes on every retry. Reject a delivery more than 300 seconds away from your own clock.

    pattern: ^[0-9]+$

  • webhook-signatureintestazionestringobbligatorio

    One or two signatures separated by a space, each v1,<base64>: HMAC-SHA256 of <webhook-id>.<webhook-timestamp>.<raw body> keyed with the bytes of the endpoint's secret (whsec_<base64>: the base64-decoded value). During a secret rotation there are two signatures, with the new secret and with the old one: one matching is enough. Verify it with the official Standard Webhooks library.

    pattern: ^v1,[A-Za-z0-9+/]{43}=( v1,[A-Za-z0-9+/]{43}=)?$

  • user-agentintestazionestringobbligatorio

    Always GroceryAI-Core-Events/2.

Corpo dell'evento

object

  • idstringobbligatorio

    The event identifier (equal to webhook-id).

    format: uuid

  • typestringobbligatorio

    Valori: "order.confirmed"

  • environmentstringobbligatorio

    A test (test) or a real fact (live): the endpoints are the same.

    Valori: "test""live"

  • timestampstringobbligatorio

    When the fact happened, ISO 8601 (the Standard Webhooks field): equal to occurred_at.

    format: date-time

  • occurred_atstringobbligatorio

    When the fact happened (not when the delivery started).

    format: date-time

  • resource_idstringobbligatorio

    The order identifier (data.order.id).

  • attemptintegerobbligatorio

    The attempt number, from 1.

    minimum: 1

  • dataOrdineConfermatoobbligatorio

Risposte

  • 410Gone: the endpoint wants no more events. It is deactivated at once and receives nothing more until it is created again from the portal.

  • 2XXDelivered. Answer quickly (within 15 seconds) and work afterwards: beyond that, the attempt has failed.

  • defaultAny other response (a 3xx included: redirects are not followed), or no response within 15 seconds: it is retried with the delays of x-retry-schedule-seconds, lengthened by a Retry-After.

support.requested

A chat customer asks for a person, makes a complaint or wants to change an order already sent. Sent to every endpoint subscribed to support.requested; the same request can also be pulled with GET /v1/support_requests.

Intestazioni

  • webhook-idintestazionestringobbligatorio

    The message identifier: the event id, the same on every attempt and on every redelivery. It is the key to drop duplicates with.

    format: uuid

  • webhook-timestampintestazionestringobbligatorio

    Unix seconds of the instant of the ATTEMPT (not of the fact): it changes on every retry. Reject a delivery more than 300 seconds away from your own clock.

    pattern: ^[0-9]+$

  • webhook-signatureintestazionestringobbligatorio

    One or two signatures separated by a space, each v1,<base64>: HMAC-SHA256 of <webhook-id>.<webhook-timestamp>.<raw body> keyed with the bytes of the endpoint's secret (whsec_<base64>: the base64-decoded value). During a secret rotation there are two signatures, with the new secret and with the old one: one matching is enough. Verify it with the official Standard Webhooks library.

    pattern: ^v1,[A-Za-z0-9+/]{43}=( v1,[A-Za-z0-9+/]{43}=)?$

  • user-agentintestazionestringobbligatorio

    Always GroceryAI-Core-Events/2.

Corpo dell'evento

object

  • idstringobbligatorio

    The event identifier (equal to webhook-id).

    format: uuid

  • typestringobbligatorio

    Valori: "support.requested"

  • environmentstringobbligatorio

    A test (test) or a real fact (live): the endpoints are the same.

    Valori: "test""live"

  • timestampstringobbligatorio

    When the fact happened, ISO 8601 (the Standard Webhooks field): equal to occurred_at.

    format: date-time

  • occurred_atstringobbligatorio

    When the fact happened (not when the delivery started).

    format: date-time

  • resource_idstringobbligatorio

    The request identifier (data.support_request.id).

  • attemptintegerobbligatorio

    The attempt number, from 1.

    minimum: 1

  • dataRichiestaAssistenzaobbligatorio

Risposte

  • 410Gone: the endpoint wants no more events. It is deactivated at once and receives nothing more until it is created again from the portal.

  • 2XXDelivered. Answer quickly (within 15 seconds) and work afterwards: beyond that, the attempt has failed.

  • defaultAny other response (a 3xx included: redirects are not followed), or no response within 15 seconds: it is retried with the delays of x-retry-schedule-seconds, lengthened by a Retry-After.

order.updated

The shop reported where an order stands (POST /v1/orders/{order_id}/status): progress (preparing, ready, out for delivery, delayed, rescheduled) or an outcome (delivered, with substitutions, not delivered, returned). Sent once per report to every endpoint subscribed to order.updated; the same status reported again is not sent twice, and progress older than the last one reported is not sent. The order is data.order.id. Not available via pull.

Intestazioni

  • webhook-idintestazionestringobbligatorio

    The message identifier: the event id, the same on every attempt and on every redelivery. It is the key to drop duplicates with.

    format: uuid

  • webhook-timestampintestazionestringobbligatorio

    Unix seconds of the instant of the ATTEMPT (not of the fact): it changes on every retry. Reject a delivery more than 300 seconds away from your own clock.

    pattern: ^[0-9]+$

  • webhook-signatureintestazionestringobbligatorio

    One or two signatures separated by a space, each v1,<base64>: HMAC-SHA256 of <webhook-id>.<webhook-timestamp>.<raw body> keyed with the bytes of the endpoint's secret (whsec_<base64>: the base64-decoded value). During a secret rotation there are two signatures, with the new secret and with the old one: one matching is enough. Verify it with the official Standard Webhooks library.

    pattern: ^v1,[A-Za-z0-9+/]{43}=( v1,[A-Za-z0-9+/]{43}=)?$

  • user-agentintestazionestringobbligatorio

    Always GroceryAI-Core-Events/2.

Corpo dell'evento

object

  • idstringobbligatorio

    The event identifier (equal to webhook-id).

    format: uuid

  • typestringobbligatorio

    Valori: "order.updated"

  • environmentstringobbligatorio

    A test (test) or a real fact (live): the endpoints are the same.

    Valori: "test""live"

  • timestampstringobbligatorio

    When the fact happened, ISO 8601 (the Standard Webhooks field): equal to occurred_at.

    format: date-time

  • occurred_atstringobbligatorio

    When the fact happened (not when the delivery started).

    format: date-time

  • resource_idstringobbligatorio

    The identifier of the report (data.order.event_id); the order is data.order.id.

    format: uuid

  • attemptintegerobbligatorio

    The attempt number, from 1.

    minimum: 1

  • dataOrdineAggiornatoobbligatorio

Risposte

  • 410Gone: the endpoint wants no more events. It is deactivated at once and receives nothing more until it is created again from the portal.

  • 2XXDelivered. Answer quickly (within 15 seconds) and work afterwards: beyond that, the attempt has failed.

  • defaultAny other response (a 3xx included: redirects are not followed), or no response within 15 seconds: it is retried with the delays of x-retry-schedule-seconds, lengthened by a Retry-After.

catalog_import.completed

A catalog import (POST /v1/catalog/imports) has finished, well or badly (data.import.status): it arrives once per import at every endpoint subscribed to catalog_import.completed. It is the counterpart of Shopify's bulk_operations/finish: as there, a webhook delivery can go missing, and the status stays readable with GET /v1/catalog/imports/{import_id}. It cannot be pulled.

Intestazioni

  • webhook-idintestazionestringobbligatorio

    The message identifier: the event id, the same on every attempt and on every redelivery. It is the key to drop duplicates with.

    format: uuid

  • webhook-timestampintestazionestringobbligatorio

    Unix seconds of the instant of the ATTEMPT (not of the fact): it changes on every retry. Reject a delivery more than 300 seconds away from your own clock.

    pattern: ^[0-9]+$

  • webhook-signatureintestazionestringobbligatorio

    One or two signatures separated by a space, each v1,<base64>: HMAC-SHA256 of <webhook-id>.<webhook-timestamp>.<raw body> keyed with the bytes of the endpoint's secret (whsec_<base64>: the base64-decoded value). During a secret rotation there are two signatures, with the new secret and with the old one: one matching is enough. Verify it with the official Standard Webhooks library.

    pattern: ^v1,[A-Za-z0-9+/]{43}=( v1,[A-Za-z0-9+/]{43}=)?$

  • user-agentintestazionestringobbligatorio

    Always GroceryAI-Core-Events/2.

Corpo dell'evento

object

  • idstringobbligatorio

    The event identifier (equal to webhook-id).

    format: uuid

  • typestringobbligatorio

    Valori: "catalog_import.completed"

  • environmentstringobbligatorio

    A test (test) or a real fact (live): the endpoints are the same.

    Valori: "test""live"

  • timestampstringobbligatorio

    When the fact happened, ISO 8601 (the Standard Webhooks field): equal to occurred_at.

    format: date-time

  • occurred_atstringobbligatorio

    When the fact happened (not when the delivery started).

    format: date-time

  • resource_idstringobbligatorio

    The id of the import (data.import.id).

    format: uuid

  • attemptintegerobbligatorio

    The attempt number, from 1.

    minimum: 1

  • dataImportazioneCompletataobbligatorio

Risposte

  • 410Gone: the endpoint wants no more events. It is deactivated at once and receives nothing more until it is created again from the portal.

  • 2XXDelivered. Answer quickly (within 15 seconds) and work afterwards: beyond that, the attempt has failed.

  • defaultAny other response (a 3xx included: redirects are not followed), or no response within 15 seconds: it is retried with the delays of x-retry-schedule-seconds, lengthened by a Retry-After.

webhook.ping

The test event of the portal's "send a test event" button: a single delivery to the endpoint being tested, signed like the others. Cannot be pulled.

Intestazioni

  • webhook-idintestazionestringobbligatorio

    The message identifier: the event id, the same on every attempt and on every redelivery. It is the key to drop duplicates with.

    format: uuid

  • webhook-timestampintestazionestringobbligatorio

    Unix seconds of the instant of the ATTEMPT (not of the fact): it changes on every retry. Reject a delivery more than 300 seconds away from your own clock.

    pattern: ^[0-9]+$

  • webhook-signatureintestazionestringobbligatorio

    One or two signatures separated by a space, each v1,<base64>: HMAC-SHA256 of <webhook-id>.<webhook-timestamp>.<raw body> keyed with the bytes of the endpoint's secret (whsec_<base64>: the base64-decoded value). During a secret rotation there are two signatures, with the new secret and with the old one: one matching is enough. Verify it with the official Standard Webhooks library.

    pattern: ^v1,[A-Za-z0-9+/]{43}=( v1,[A-Za-z0-9+/]{43}=)?$

  • user-agentintestazionestringobbligatorio

    Always GroceryAI-Core-Events/2.

Corpo dell'evento

object

  • idstringobbligatorio

    The event identifier (equal to webhook-id).

    format: uuid

  • typestringobbligatorio

    Valori: "webhook.ping"

  • environmentstringobbligatorio

    A test (test) or a real fact (live): the endpoints are the same.

    Valori: "test"

  • timestampstringobbligatorio

    When the fact happened, ISO 8601 (the Standard Webhooks field): equal to occurred_at.

    format: date-time

  • occurred_atstringobbligatorio

    When the fact happened (not when the delivery started).

    format: date-time

  • resource_idnullobbligatorio

  • attemptintegerobbligatorio

    The attempt number, from 1.

    minimum: 1

  • dataPingobbligatorio

Risposte

  • 410Gone: the endpoint wants no more events. It is deactivated at once and receives nothing more until it is created again from the portal.

  • 2XXDelivered. Answer quickly (within 15 seconds) and work afterwards: beyond that, the attempt has failed.

  • defaultAny other response (a 3xx included: redirects are not followed), or no response within 15 seconds: it is retried with the delays of x-retry-schedule-seconds, lengthened by a Retry-After.

Consegna degli eventi

  • Ritenti, in secondi dopo il tentativo precedente: 60, 300, 1800, 7200, 18000, 36000, 50400, 72000, 86400
  • Tentativi al massimo: 10
  • Tempo per rispondere: 15000 ms
  • Firma: v1, + base64(HMAC-SHA256(bytes of the whsec_<base64> secret, ${webhook-id}.${webhook-timestamp}.${raw body})); two signatures separated by a space during a rotation
  • Formato: Standard Webhooks 1.0.0
  • Ogni attesa è variata fino al 10 %, perché gli endpoint caduti insieme non vengano ritentati nello stesso secondo.
  • Rifiuta una consegna il cui webhook-timestamp dista più di 300 secondi dal tuo orologio.
  • Una risposta 410 Gone disattiva l'endpoint (l'elenco degli endpoint del portale dice disabled_reason: http_410); ogni altro 4xx si ritenta.

Schemi

RequestId

string

The call identifier: also in the x-request-id header. It is the only thing we ask for when you contact us.

format: uuid

Errore

object

  • errorobjectobbligatorio

    • typestringobbligatorio

      The error family, derived from the HTTP status.

      Valori: "richiesta_non_valida""autenticazione""autorizzazione""non_trovato""conflitto""troppo_grande""limite_richieste""servizio_non_disponibile""errore_interno"

    • codestringobbligatorio

      The exact code: program against this. The possible values for each response are in x-error-codes.

    • messagestringobbligatorio

      For humans, not for code: the text may change.

    • paramstring

      The field or parameter involved, when there is one.

    • doc_urlstring

      The code's public page (GET /v1/errors/{code}, no key needed): what it means, how to fix it, whether retrying the request can be enough.

      format: uri

  • request_idRequestIdobbligatorio

StatoServizio

object

  • statusStatoComponenteobbligatorio

    The worst among the measured components; unknown only if none is measured.

  • measured_atstring | nullobbligatorio

    The last alarm round that measured (one a minute). If it is older than 3 minutes every component is unknown.

    format: date-time

  • measured_sincestring | nullobbligatorio

    The first measured minute: the history does not go further back.

    format: date-time

  • componentsarray<ComponenteServizio>obbligatorio

  • incidentsarray<IncidenteServizio>obbligatorio

    The latest incidents of the last 90 days (at most 50), most recent first.

    maxItems: 50

StatoComponente

string

operational; degraded (it answers, but part of the work fails); outage (it does not answer as it should to two probes in a row); unknown (not measured, or its probe has not completed a round yet: never read it as operational).

Valori: "operational""degraded""outage""unknown"

ComponenteServizio

object

  • idstringobbligatorio

    The stable name of the component.

    Valori: "assistant""web_chat""api""events""portal""mcp"

  • namestringobbligatorio

  • descriptionstringobbligatorio

  • statusStatoComponenteobbligatorio

  • availabilityobject | nullobbligatorio

    null for a component that no probe measures, or whose probe has no history yet. month and previous_month (the service commitments) are present when the measurement carries the calendar month's minutes.

DisponibilitaServizio

object

  • window_daysintegerobbligatorio

    Valori: 3090

  • fromstringobbligatorio

    The start of the calculation: the start of the window or, if the component's history is shorter, its first measured minute (when its probe was added, if that was after measurement began).

    format: date-time

  • completebooleanobbligatorio

    True if the component's history covers the whole window.

  • measured_minutesintegerobbligatorio

    The minutes in which the component was actually measured: unmeasured minutes count neither as available nor as down.

    minimum: 0

  • outage_minutesintegerobbligatorio

    minimum: 0

  • degraded_minutesintegerobbligatorio

    minimum: 0

  • uptime_percentnumber | nullobbligatorio

    100 times (measured minus outage) divided by measured, to three decimals; degraded does not lower it. null with no measured minutes.

    minimum: 0maximum: 100

DisponibilitaMese

object

The availability of a calendar month (UTC), measured with the rule of the service commitments: every minute with an outage or degraded incident is a minute of downtime, over measured minutes only.

  • monthstringobbligatorio

    The month, YYYY-MM, in UTC.

    pattern: ^\d{4}-\d{2}$

  • fromstringobbligatorio

    The start of the calculation: the first of the month or, if the component has been measured only since later, its first measured minute.

    format: date-time

  • tostringobbligatorio

    The end of the calculation: now for the current month, the first of the next month for a closed one.

    format: date-time

  • completebooleanobbligatorio

    True if the component was measured from the first of the month.

  • measured_minutesintegerobbligatorio

    The minutes actually measured: unmeasured minutes count neither as available nor as downtime.

    minimum: 0

  • outage_minutesintegerobbligatorio

    minimum: 0

  • degraded_minutesintegerobbligatorio

    The degraded minutes outside an outage.

    minimum: 0

  • downtime_minutesintegerobbligatorio

    The minutes of downtime: outage and degraded together.

    minimum: 0

  • availability_percentnumber | nullobbligatorio

    100 times (measured minus downtime) divided by measured, to three decimals. null without measured minutes.

    minimum: 0maximum: 100

  • objective_percentnumber | nullobbligatorio

    The component's monthly objective in the service commitments.

    minimum: 0maximum: 100

  • objective_metboolean | nullobbligatorio

    Whether the month's availability is at least the objective (for the current month: so far). null without measured minutes.

IncidenteServizio

object

  • componentsarray<string>obbligatorio

    minItems: 1

  • severitystringobbligatorio

    Valori: "degraded""outage"

  • statusstringobbligatorio

    Valori: "open""resolved"

  • started_atstringobbligatorio

    format: date-time

  • last_seen_atstringobbligatorio

    The last minute in which the failure was seen.

    format: date-time

  • resolved_atstring | nullobbligatorio

    When the incident was resolved: after 10 minutes without the failure. null while it is open.

    format: date-time

PaginaErrore

object

  • codestringobbligatorio

    The code, as written in error.code, errors[].code or warnings[].code.

  • titlestringobbligatorio

    What happened, in one sentence.

  • how_to_fixstringobbligatorio

    What to do to fix it.

  • retryablebooleanobbligatorio

    True if the same request, repeated later unchanged (with the same Idempotency-Key), can succeed.

  • appears_asobjectobbligatorio

    Where the code appears, computed from the OpenAPI document: it cannot drift from it.

    • errorarray<object>obbligatorio

      As error.code of an error response: with which status, which type, in which operations (empty = on any path).

      • statusintegerobbligatorio

      • typestringobbligatorio

        Valori: "richiesta_non_valida""autenticazione""autorizzazione""non_trovato""conflitto""troppo_grande""limite_richieste""servizio_non_disponibile""errore_interno"

      • operationsarray<string>obbligatorio

    • batch_item_errorarray<string>obbligatorio

      The batch operations in which the code rejects an item (errors[].code).

    • batch_item_warningarray<string>obbligatorio

      The batch operations in which the code is a warning on an item that was written (warnings[].code).

    • chat_session_identitybooleanobbligatorio

      True if the code is a reason in the chat session's identity.code.

  • doc_urlstringobbligatorio

    format: uri

ProdottoInIngresso

object

An invalid item does not fail the batch: it comes back in errors with its code. Numbers are also accepted as numeric strings.

  • skustringobbligatorio

    minLength: 1maxLength: 128

  • titlestringobbligatorio

    minLength: 1maxLength: 512

  • gtinstring

    GTIN/GS1 with the correct check digit.

    pattern: ^([0-9]{8}|[0-9]{12,14})$

  • brandstring

  • categorystring

  • unitstring

  • pricenumber

    minimum: 0

  • net_pricenumber

    minimum: 0

  • currencystring

    ISO 4217; if absent, the account's currency. A currency different from the account's is rejected: it is not converted.

    pattern: ^[A-Z]{3}$

  • stock_qtynumber

    minimum: 0

  • availableboolean

    If absent, true.

  • linkstring

  • image_linkstring

  • is_onlineboolean

    The contract name for available: either one, or both with the same value.

  • min_order_qtynumber | null

    Catalog contract field (number); in attributes under its own name.

    minimum: 0

  • min_order_unitstring | null

    Catalog contract field (symbol); in attributes under its own name.

    Valori: "kg""g""gr""l""lt""ml""cl""pz"null

  • sold_by_weightboolean | null

    Catalog contract field (boolean); in attributes under its own name.

  • avg_piece_weight_kgnumber | null

    Catalog contract field (number); in attributes under its own name.

    minimum: 0

  • items_per_packinteger | null

    Catalog contract field (integer); in attributes under its own name.

    minimum: 1

  • unit_pricenumber | null

    Catalog contract field (number); in attributes under its own name.

    minimum: 0

  • gross_weight_kgnumber | null

    Catalog contract field (number); in attributes under its own name.

    minimum: 0

  • list_pricenumber | null

    Catalog contract field (number); in attributes under its own name.

    minimum: 0

  • tare_kgnumber | null

    Catalog contract field (number); in attributes under its own name.

    minimum: 0

  • subcategorystring | null

    Catalog contract field (text); in attributes under its own name.

  • descriptionstring | null

    Catalog contract field (text); in attributes under its own name.

  • pack_onlyboolean | null

    Catalog contract field (boolean); in attributes under its own name.

  • stock_managedboolean | null

    Catalog contract field (boolean); in attributes under its own name.

  • vat_ratenumber | null

    Catalog contract field (number); in attributes under its own name.

    minimum: 0

  • diet_tagsarray | string | null

    Catalog contract field (list); in attributes under its own name.

  • offer_pricenumber | null

    Catalog contract field (number); in attributes under its own name.

    minimum: 0

  • offer_startstring | null

    Catalog contract field (date); in attributes under its own name.

    format: date

  • offer_endstring | null

    Catalog contract field (date); in attributes under its own name.

    format: date

  • offer_min_qtyinteger | null

    Catalog contract field (integer); in attributes under its own name.

    minimum: 1

  • offer_labelstring | null

    Catalog contract field (text); in attributes under its own name.

  • allergensarray | string | null

    The Annex II allergens of Regulation (EU) 1169/2011 that the product CONTAINS, as contract codes or as the GS1 AllergenTypeCode codes of the 14 (for example AW = gluten). none declares that it contains none of them and stands alone; an absent field means «not declared», and the chat tells the customer so instead of guessing. In attributes under its own name.

  • may_containarray | string | null

    The allergens the product MAY contain as traces (precautionary statement), with the same codes; never one that is also in allergens. In attributes under its own name.

  • ingredientsstring | null

    The list of ingredients as on the label (at most 4,000 characters). In attributes under its own name.

  • nutrition_basisstring | null

    The basis of the nutrition values: 100g or 100ml. In attributes under its own name.

    Valori: "100g""100ml"null

  • energy_kjnumber | null

    Energy in kJ per 100 g or 100 ml (at most 3,800). In attributes under its own name.

    minimum: 0

  • energy_kcalnumber | null

    Energy in kcal per 100 g or 100 ml (at most 900). In attributes under its own name.

    minimum: 0

  • fat_gnumber | null

    Fat in grams per 100 g or 100 ml. In attributes under its own name.

    minimum: 0

  • saturated_fat_gnumber | null

    Saturates in grams per 100 g or 100 ml (no more than fat_g). In attributes under its own name.

    minimum: 0

  • carbohydrate_gnumber | null

    Carbohydrate in grams per 100 g or 100 ml. In attributes under its own name.

    minimum: 0

  • sugars_gnumber | null

    Sugars in grams per 100 g or 100 ml (no more than carbohydrate_g). In attributes under its own name.

    minimum: 0

  • protein_gnumber | null

    Protein in grams per 100 g or 100 ml. In attributes under its own name.

    minimum: 0

  • salt_gnumber | null

    Salt in grams per 100 g or 100 ml. In attributes under its own name.

    minimum: 0

  • fibre_gnumber | null

    Fibre in grams per 100 g or 100 ml (optional). In attributes under its own name.

    minimum: 0

  • storage_conditionsstring | null

    Any special storage conditions and conditions of use, as on the label. In attributes under its own name.

  • usage_instructionsstring | null

    Instructions for use, where it would be difficult to make appropriate use of the food without them. In attributes under its own name.

  • food_business_operatorstring | null

    The name or business name and address of the food business operator responsible for the label. In attributes under its own name.

  • originstring | null

    The country of origin or place of provenance, where it is mandatory (Article 26). In attributes under its own name.

  • alcohol_percentnumber | null

    The actual alcoholic strength by volume, for beverages containing more than 1.2% by volume. In attributes under its own name.

    minimum: 0

  • food_info_urlstring | null

    The https:// address of the product page carrying the food information, when the fields are not sent one by one. In attributes under its own name.

    format: uripattern: ^https://maxLength: 2000

  • attributesobject

    MERGED with what is there: a key set to null is removed, an absent key stays. Contract fields written here are validated as if they were at the top of the item.

GiacenzaInIngresso

object

Touches ONLY the fields present. An item with none of the fields is rejected (NESSUN_CAMPO). The strikethrough price and the offer are merged into attributes (null removes).

Almeno uno fra: pricenet_pricestock_qtyavailableis_onlinelist_priceoffer_priceoffer_startoffer_endoffer_min_qtyoffer_label

  • skustringobbligatorio

    minLength: 1

  • pricenumber

    minimum: 0

  • net_pricenumber

    minimum: 0

  • stock_qtynumber

    minimum: 0

  • availableboolean

  • is_onlineboolean

  • store_codestring

    The store (GET /v1/stores): the item applies there and carries only price, stock_qty, available/is_online, list_price, offer_price, offer_start, offer_end (CAMPO_NON_PER_PUNTO_VENDITA). A store that does not exist is PUNTO_VENDITA_SCONOSCIUTO.

    pattern: ^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$

  • list_pricenumber | null

    Catalog contract field (number); in attributes under its own name.

    minimum: 0

  • offer_pricenumber | null

    Catalog contract field (number); in attributes under its own name.

    minimum: 0

  • offer_startstring | null

    Catalog contract field (date); in attributes under its own name.

    format: date

  • offer_endstring | null

    Catalog contract field (date); in attributes under its own name.

    format: date

  • offer_min_qtyinteger | null

    Catalog contract field (integer); in attributes under its own name.

    minimum: 1

  • offer_labelstring | null

    Catalog contract field (text); in attributes under its own name.

Istantanea

object

  • snapshot_idstringobbligatorio

    format: uuid

  • expires_atstringobbligatorio

    After this, the snapshot accepts no batches and no commit.

    format: date-time

  • active_productsintegerobbligatorio

    The products active now: the base of the gate.

    minimum: 0

ChiusuraIstantanea

object

{dry_run: true} for the numbers; {expected_off: n} to withdraw (n = to_switch_off from the dry run).

  • dry_runboolean

  • expected_offinteger

    minimum: 0

EsitoIstantanea

object

  • snapshot_idstringobbligatorio

    format: uuid

  • activeintegerobbligatorio

    The products active before the withdrawal.

    minimum: 0

  • seen_activeintegerobbligatorio

    How many of them the batches (or the file, or the feed) carried.

    minimum: 0

  • to_switch_offintegerobbligatorio

    How many would be withdrawn: pass it as expected_off.

    minimum: 0

  • sharenumberobbligatorio

    seen_active / active (1 if there are no active products).

    minimum: 0maximum: 1

  • min_sharenumberobbligatorio

    The threshold: 0.9 by default.

    minimum: 0.5maximum: 1

  • allowedbooleanobbligatorio

    True if share >= min_share.

  • count_changedbooleanobbligatorio

  • dry_runbooleanobbligatorio

  • switched_offintegerobbligatorio

    How many were withdrawn (0 in a dry run).

    minimum: 0

  • samplearray<string>obbligatorio

    The first 20 skus to withdraw, in order.

    maxItems: 20

Freschezza

object

  • environmentstringobbligatorio

    Valori: "test""live"

  • last_update_atstring | nullobbligatorio

    The last product written, through any channel.

    format: date-time

  • age_hoursnumber | nullobbligatorio

    Hours since last_update_at.

  • declared_refresh_hoursinteger | nullobbligatorio

    How often, in hours, the shop said it updates.

  • stalebooleanobbligatorio

    True if the catalog has been unchanged for more than twice the declared interval.

  • productsintegerobbligatorio

    minimum: 0

  • availableintegerobbligatorio

    minimum: 0

FeedInIngresso

object

  • urlstring | null

    https:// to a public host name; null to declare only the refresh interval.

  • formatstring | null

    Valori: "csv""xlsx""google_merchant_xml""google_merchant_tsv"null

  • every_hoursinteger

    24 by default.

    minimum: 1maximum: 168

  • modestring

    delta by default.

    Valori: "delta""snapshot"

  • enabledboolean

    True by default when there is a url.

  • declared_refresh_hoursinteger | null

    minimum: 1maximum: 720

ImportazioneInIngresso

object

Either products (the items of PUT /v1/products, up to 50000), or url with format. For a CSV in the body, send the text of the file with Content-Type: text/csv and mode in the query.

  • productsarray<ProdottoInIngresso>

    minItems: 1maxItems: 50000

  • urlstring

    The https:// address of the file, on a public name: it is read with the guards of the feed (at most 3 redirects, 40 MB, 30 s).

    format: uripattern: ^https://maxLength: 2048

  • formatstring

    json (a list of products, or {"products": [...]}), jsonl (one product per line, like Shopify Bulk Operations files), csv or xlsx (the portal file), google_merchant_xml or google_merchant_tsv (the Google Merchant / Meta product feed).

    Valori: "json""jsonl""csv""xlsx""google_merchant_xml""google_merchant_tsv"

  • modestring

    delta (default) updates and adds; snapshot withdraws at the end the active products the import does not carry, behind the 90 % gate.

    Valori: "delta""snapshot"

Importazione

object

  • idstringobbligatorio

    format: uuid

  • statusstringobbligatorio

    queued waiting (it starts within a minute), running in progress, then succeeded, partial (rejected rows, or the snapshot gate that withdrew nothing) or failed.

    Valori: "queued""running""succeeded""partial""failed"

  • modestringobbligatorio

    Valori: "delta""snapshot"

  • sourcestringobbligatorio

    Valori: "body""url"

  • formatstringobbligatorio

    Valori: "json""jsonl""csv""xlsx""google_merchant_xml""google_merchant_tsv"

  • urlstring | nullobbligatorio

    The address of the file, for imports from url.

  • receivedintegerobbligatorio

    The items (or the data rows of the file) received. For a file it is known once the file has been read.

    minimum: 0

  • writtenintegerobbligatorio

    The products written so far (merged by sku).

    minimum: 0

  • rejectedintegerobbligatorio

    The rows rejected so far: GET /v1/catalog/imports/{import_id}/errors lists them.

    minimum: 0

  • warningsintegerobbligatorio

    The rows written with a warning: .../errors?type=warnings.

    minimum: 0

  • switched_offintegerobbligatorio

    The products withdrawn at the end (mode: snapshot).

    minimum: 0

  • chunks_totalinteger | nullobbligatorio

    The chunks of 500 the import is split into; null until the file has been read.

  • chunks_doneintegerobbligatorio

    The chunks already written.

    minimum: 0

  • errorobbligatorio

    Why the import is failed, or why it is partial without withdrawal (ISTANTANEA_SOTTO_SOGLIA, CONTEGGIO_CAMBIATO).

    Almeno uno fra: code + message{"type":"null"}

  • snapshotobbligatorio

    Almeno uno fra: active + seen_active + to_switch_off + share + min_share + allowed + count_changed + dry_run + switched_off + sample{"type":"null"}

  • created_atstringobbligatorio

    format: date-time

  • started_atstring | nullobbligatorio

    format: date-time

  • finished_atstring | nullobbligatorio

    format: date-time

  • linksobjectobbligatorio

    • selfstringobbligatorio

      format: uri

    • errorsstringobbligatorio

      format: uri

RigaImportazione

object

A rejected row (or a row written with a warning). The codes are those of the batch (PUT /v1/products) and of the portal file; in addition ELEMENTO_NON_JSON, PEZZO_NON_SCRITTO (a line of a JSON Lines file that is not JSON; a chunk the database did not accept after five attempts: send those rows again).

  • indexinteger | nullobbligatorio

    The position of the item in products (or the line of the JSON Lines file), from 0.

  • rowinteger | nullobbligatorio

    The row of the CSV/XLSX file or of the feed (the header is row 1).

  • idstring | nullobbligatorio

    The sku, when there was one.

  • codestringobbligatorio

  • fieldstring | nullobbligatorio

  • messagestringobbligatorio

ImportazioneCompletata

object

The body of catalog_import.completed: the numbers and where to read the rejected rows; nothing about the products.

  • schema_versionintegerobbligatorio

    Valori: 1

  • importobjectobbligatorio

    • idstringobbligatorio

      format: uuid

    • statusstringobbligatorio

      Valori: "succeeded""partial""failed"

    • modestringobbligatorio

      Valori: "delta""snapshot"

    • sourcestringobbligatorio

      Valori: "body""url"

    • formatstringobbligatorio

      Valori: "json""jsonl""csv""xlsx""google_merchant_xml""google_merchant_tsv"

    • receivedintegerobbligatorio

      minimum: 0

    • writtenintegerobbligatorio

      minimum: 0

    • rejectedintegerobbligatorio

      minimum: 0

    • warningsintegerobbligatorio

      minimum: 0

    • switched_offintegerobbligatorio

      minimum: 0

    • errorobbligatorio

      Almeno uno fra: code + message{"type":"null"}

    • finished_atstringobbligatorio

      format: date-time

    • linksobjectobbligatorio

      • selfstringobbligatorio

        format: uri

      • errorsstringobbligatorio

        format: uri

GiroDelFeed

object

  • statusstringobbligatorio

    Valori: "ok""partial""failed"

  • error_codestring | nullobbligatorio

    Valori: "FEED_URL_NON_AMMESSO""FEED_IRRAGGIUNGIBILE""FEED_REDIREZIONE""FEED_RISPOSTA_NON_OK""FEED_TROPPO_GRANDE""FEED_ILLEGGIBILE""FEED_SENZA_COLONNE""FEED_VUOTO""ISTANTANEA_SOTTO_SOGLIA""CONTEGGIO_CAMBIATO""ERRORE_INTERNO"null

  • messagestring | nullobbligatorio

  • receivedintegerobbligatorio

    minimum: 0

  • writtenintegerobbligatorio

    minimum: 0

  • rejectedintegerobbligatorio

    minimum: 0

  • switched_offintegerobbligatorio

    minimum: 0

  • errorsarray<object>obbligatorio

    maxItems: 100

    • rowintegerobbligatorio

    • skustring | nullobbligatorio

    • codestringobbligatorio

    • fieldstring | nullobbligatorio

    • messagestringobbligatorio

  • snapshotobbligatorio

    Almeno uno fra: active + seen_active + to_switch_off + share + min_share + allowed + count_changed + dry_run + switched_off + sample{"type":"null"}

  • started_atstringobbligatorio

    format: date-time

  • finished_atstringobbligatorio

    format: date-time

ClienteInIngresso

object

A customer, with the field names of the customer record or those of the M8 customer template (customer_ref, full_name, street, house_number, city, postal_code, floor, intercom, delivery_notes, language, exemption). The M8 address fields are written into address under their own names, language and exemption into attributes. A field outside the list is not written, and the CAMPO_SCONOSCIUTO warning says so. Every write replaces the whole customer.

Almeno uno fra: external_refcustomer_ref

  • external_refstring

    The customer's identifier in your system.

    minLength: 1maxLength: 128

  • customer_refstring

    The M8 name for external_ref: either one, or both with the same value.

    minLength: 1maxLength: 128

  • display_namestring

  • full_namestring

    The M8 name for display_name: either one, or both with the same value.

  • emailstring

  • phonestring

    E.164: + (or 00) and 8-15 digits (+393331234567); spaces and dashes are removed and + plus the digits is stored. A number without the international prefix is rejected (TELEFONO_NON_E164): it is the key the chat uses to recognise the customer.

  • streetstring

    Into address.street.

    maxLength: 200

  • house_numberstring

    Into address.house_number.

    maxLength: 32

  • citystring

    Into address.city.

    maxLength: 120

  • postal_codestring

    Into address.postal_code.

    maxLength: 16

  • floorstring

    Into address.floor.

    maxLength: 32

  • intercomstring

    Into address.intercom.

    maxLength: 64

  • delivery_notesstring

    Into address.delivery_notes.

    maxLength: 200

  • languagestring

    A language code (it, en-GB), into attributes.language.

  • exemptionstring

    Only with the legal basis declared by the shop; into attributes.exemption.

    Valori: "over_65""disability"

  • addressobject

  • attributesobject

EsitoLottoProdotti

object

  • receivedintegerobbligatorio

    How many items arrived.

    minimum: 0

  • writtenintegerobbligatorio

    How many were written.

    minimum: 0

  • rejectedintegerobbligatorio

    How many were rejected: the length of errors.

    minimum: 0

  • errorsarray<object>obbligatorio

    • indexinteger | nullobbligatorio

      The position in the batch; null when the database rejected it after validation.

    • idstring | nullobbligatorio

      The item's sku or external_ref, when it had one.

    • codestringobbligatorio

      Valori: "ELEMENTO_NON_OGGETTO""SKU_MANCANTE""SKU_TROPPO_LUNGO""TITLE_MANCANTE""TITLE_TROPPO_LUNGO""GTIN_NON_VALIDO""PREZZO_NON_VALIDO""GIACENZA_NON_VALIDA""VALUTA_NON_VALIDA""VALUTA_DIVERSA_DAL_TENANT""DISPONIBILITA_NON_VALIDA""CAMPO_IN_DUE_POSTI""VALORE_NON_AMMESSO""NUMERO_NON_VALIDO""BOOLEANO_NON_VALIDO""UNITA_NON_AMMESSA""DATA_NON_VALIDA""DATE_INVERTITE""OFFERTA_SUPERIORE_AL_PREZZO""INFORMAZIONI_ALIMENTARI_INCOERENTI""SKU_RIPETUTO_NEL_LOTTO""RIFIUTATA_DAL_DATABASE"

    • messagestringobbligatorio

  • warningsarray<object>obbligatorio

    Warnings on items that were written: they remove nothing, they say what will not be used.

    • indexintegerobbligatorio

      minimum: 0

    • idstring | nullobbligatorio

    • codestringobbligatorio

      Valori: "OFFERTA_NON_SCONTATA""PESO_MEDIO_SENZA_PESO""ENERGIA_NON_COERENTE""NUTRIZIONE_INCOMPLETA"

    • messagestringobbligatorio

  • request_idRequestIdobbligatorio

EsitoLottoGiacenze

object

  • receivedintegerobbligatorio

    How many items arrived.

    minimum: 0

  • writtenintegerobbligatorio

    How many were written.

    minimum: 0

  • rejectedintegerobbligatorio

    How many were rejected: the length of errors.

    minimum: 0

  • errorsarray<object>obbligatorio

    • indexinteger | nullobbligatorio

      The position in the batch; null when the database rejected it after validation.

    • idstring | nullobbligatorio

      The item's sku or external_ref, when it had one.

    • codestringobbligatorio

      Valori: "ELEMENTO_NON_OGGETTO""SKU_MANCANTE""PUNTO_VENDITA_SCONOSCIUTO""CAMPO_NON_PER_PUNTO_VENDITA""PREZZO_NON_VALIDO""GIACENZA_NON_VALIDA""DISPONIBILITA_NON_VALIDA""CAMPO_IN_DUE_POSTI""VALORE_NON_AMMESSO""NUMERO_NON_VALIDO""BOOLEANO_NON_VALIDO""UNITA_NON_AMMESSA""DATA_NON_VALIDA""DATE_INVERTITE""OFFERTA_SUPERIORE_AL_PREZZO""INFORMAZIONI_ALIMENTARI_INCOERENTI""NESSUN_CAMPO""SKU_SCONOSCIUTO""RIFIUTATA_DAL_DATABASE"

    • messagestringobbligatorio

  • warningsarray<object>obbligatorio

    Warnings on items that were written: they remove nothing, they say what will not be used.

    • indexintegerobbligatorio

      minimum: 0

    • idstring | nullobbligatorio

    • codestringobbligatorio

      Valori: "OFFERTA_NON_SCONTATA""PESO_MEDIO_SENZA_PESO""ENERGIA_NON_COERENTE""NUTRIZIONE_INCOMPLETA"

    • messagestringobbligatorio

  • request_idRequestIdobbligatorio

EsitoLottoClienti

object

  • receivedintegerobbligatorio

    How many items arrived.

    minimum: 0

  • writtenintegerobbligatorio

    How many were written.

    minimum: 0

  • rejectedintegerobbligatorio

    How many were rejected: the length of errors.

    minimum: 0

  • errorsarray<object>obbligatorio

    • indexinteger | nullobbligatorio

      The position in the batch; null when the database rejected it after validation.

    • idstring | nullobbligatorio

      The item's sku or external_ref, when it had one.

    • codestringobbligatorio

      Valori: "ELEMENTO_NON_OGGETTO""EXTERNAL_REF_MANCANTE""EXTERNAL_REF_TROPPO_LUNGO""CAMPO_IN_DUE_POSTI""EMAIL_NON_VALIDA""TELEFONO_NON_E164""VALORE_NON_AMMESSO""TESTO_TROPPO_LUNGO""RIFIUTATA_DAL_DATABASE"

    • messagestringobbligatorio

  • warningsarray<object>obbligatorio

    Warnings on items that were written: they remove nothing, they say what will not be used.

    • indexintegerobbligatorio

      minimum: 0

    • idstring | nullobbligatorio

    • codestringobbligatorio

      Valori: "CAMPO_SCONOSCIUTO"

    • messagestringobbligatorio

  • request_idRequestIdobbligatorio

RigaStoricoInIngresso

object

One order line. The customer by E.164 phone or by customer_ref; with neither, the line is rejected (ORDINE_SENZA_CLIENTE). An sku no longer in the catalog is accepted and counts for habits, not for the cart.

Almeno uno fra: phonecustomer_ref

  • order_refstringobbligatorio

    The order code in the shop's system.

    minLength: 1maxLength: 128

  • skustringobbligatorio

    minLength: 1maxLength: 128

  • titlestring

    maxLength: 512

  • quantitynumberobbligatorio

    In the selling unit (packs, cases; kg for products sold by weight).

  • unit_pricenumber

    minimum: 0

  • phonestring

    E.164: + and 8-15 digits (+393331234567). A number without the international prefix is rejected (TELEFONO_NON_E164).

  • customer_refstring

    The customer's external_ref in PUT /v1/customers.

    maxLength: 128

  • order_datestringobbligatorio

    ISO 8601 with offset (2026-10-01T09:30:00+02:00), or the date alone 2026-10-01 (taken as 12:00 UTC).

  • statusstring

    A cancelled order does not become a habit.

    Valori: "delivered""cancelled"

  • store_codestring

    maxLength: 64

  • delivery_datestring

    format: date

  • delivery_slotstring

    maxLength: 64

  • order_totalnumber

    minimum: 0

  • payment_methodstring

    maxLength: 64

EsitoLottoStorico

object

  • receivedintegerobbligatorio

    How many items arrived.

    minimum: 0

  • writtenintegerobbligatorio

    How many were written.

    minimum: 0

  • rejectedintegerobbligatorio

    How many were rejected: the length of errors.

    minimum: 0

  • errorsarray<object>obbligatorio

    • indexinteger | nullobbligatorio

      The position in the batch; null when the database rejected it after validation.

    • idstring | nullobbligatorio

      The item's sku or external_ref, when it had one.

    • codestringobbligatorio

      Valori: "ELEMENTO_NON_OGGETTO""ORDINE_MANCANTE""SKU_MANCANTE""TESTO_TROPPO_LUNGO""QUANTITA_NON_VALIDA""PREZZO_NON_VALIDO""TOTALE_NON_VALIDO""TELEFONO_NON_E164""ORDINE_SENZA_CLIENTE""DATA_NON_VALIDA""STATO_NON_VALIDO""RIFIUTATA_DAL_DATABASE"

    • messagestringobbligatorio

  • warningsarray<object>obbligatorio

    Warnings on items that were written: they remove nothing, they say what will not be used.

    • indexintegerobbligatorio

      minimum: 0

    • idstring | nullobbligatorio

    • codestringobbligatorio

    • messagestringobbligatorio

  • request_idRequestIdobbligatorio

Prodotto

object

  • skustringobbligatorio

  • gtinstring | nullobbligatorio

  • titlestringobbligatorio

  • brandstring | nullobbligatorio

  • categorystring | nullobbligatorio

  • unitstring | nullobbligatorio

  • pricenumber | nullobbligatorio

  • net_pricenumber | nullobbligatorio

  • currencystringobbligatorio

  • stock_qtynumber | nullobbligatorio

  • availablebooleanobbligatorio

  • linkstring | nullobbligatorio

  • image_linkstring | nullobbligatorio

  • attributesobjectobbligatorio

Cliente

object

  • external_refstringobbligatorio

  • display_namestring | nullobbligatorio

  • emailstring | nullobbligatorio

  • phonestring | nullobbligatorio

  • addressobjectobbligatorio

  • attributesobjectobbligatorio

OrdineDaRitirare

object

  • event_idstringobbligatorio

    The event id: the same one that arrives with the webhook.

    format: uuid

  • order_idstringobbligatorio

    Pass it to the ack.

  • typestringobbligatorio

    Valori: "order.confirmed"

  • payloadOrdineConfermatoobbligatorio

  • occurred_atstringobbligatorio

    format: date-time

  • created_atstringobbligatorio

    format: date-time

  • statostringobbligatorio

    in_attesa (pending) in status=new, consegnato (acknowledged) in status=acked.

    Valori: "in_attesa""consegnato"

  • consegnato_atstring | nullobbligatorio

    The instant of the first ack.

    format: date-time

StatoOrdineInIngresso

object

What happened to the order, or where it stands. Amounts are in the tenant currency, like catalog prices; numbers are also accepted as numeric strings.

  • statusstringobbligatorio

    OUTCOMES (they count for billing, the last one wins): delivered · substituted delivered with substitutions or missing items · not_delivered · returned returned after delivery. PROGRESS (before the outcome; it does not touch billing): preparing · ready (also for pickup) · out_for_delivery · delayed · rescheduled to a new window. After an outcome progress is no longer recorded (409 TRANSIZIONE_NON_AMMESSA).

    Valori: "delivered""substituted""not_delivered""returned""preparing""ready""out_for_delivery""delayed""rescheduled"

  • delivered_amountnumber

    The total the customer paid for what was delivered: lines minus discounts, plus delivery and extras (excluding a tax added separately at payment). Required with substituted and returned; optional with delivered (absent = in full); absent or 0 with not_delivered; never with progress.

    minimum: 0

  • reported_atstring

    When it happened, for the shop. Absent = now. Not in the future. Between two progress reports the most recent by reported_at wins, not the one that arrived last.

    format: date-time

  • notestring

    A note for us (the reason for a return, for example). No personal data.

    maxLength: 500

  • etaobject

    The expected or agreed delivery window. Required with rescheduled; optional with out_for_delivery and delayed; not allowed with other statuses. The end comes after the start, at most 24 hours later; the start within 30 days.

    • startstringobbligatorio

      The start of the window, ISO 8601.

      format: date-time

    • endstringobbligatorio

      The end of the window, ISO 8601.

      format: date-time

  • reasonstring

    The reason, as a code (the customer reads the sentence in their language, never a text from the shop). Only with delayed, rescheduled and not_delivered.

    Valori: "stock""capacity""traffic""weather""customer_request""shop_request""failed_attempt""other"

  • tracking_urlstring

    The link to follow the delivery: https only, only on a tracking domain declared for the shop (otherwise 400 URL_NON_AMMESSO).

    format: uripattern: ^https://maxLength: 2000

PuntiVendita

object

  • environmentstring | null

  • catalog_productsinteger

    The shop's catalog products in the environment the assistant reads.

    minimum: 0

  • storesarray<object>obbligatorio

    • store_codestringobbligatorio

    • namestringobbligatorio

    • citystringobbligatorio

    • addressstring | null

    • timezonestring | null

    • is_activebooleanobbligatorio

    • principalbooleanobbligatorio

      The shop's own store: it serves the locations no zone covers (declared fallback).

    • zonesarray<string>obbligatorio

      The active delivery zones it serves.

    • productsobjectobbligatorio

      • sellableintegerobbligatorio

        minimum: 0

      • own_priceintegerobbligatorio

        minimum: 0

      • not_sold_hereintegerobbligatorio

        minimum: 0

PuntiVenditaInIngresso

object

  • storesarray<object>obbligatorio

    The COMPLETE list: a store that is missing is switched off.

    maxItems: 200

    • store_codestringobbligatorio

      pattern: ^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$

    • namestringobbligatorio

      minLength: 1maxLength: 120

    • citystringobbligatorio

      minLength: 1maxLength: 100

    • addressstring | null

    • timezonestring | null

      IANA (Europe/Rome); absent = the shop's time zone.

    • is_activeboolean

RegoleDelNegozio

object

The shop's rules document: when writing, with based_on_version; when reading, with version, currency, bank_transfer_ready, matches_version.

  • based_on_versioninteger

    minimum: 0

  • versioninteger

    minimum: 0

  • min_order_amountstring | null

  • payment_methodsarray<string>

  • zonesarray<object>

  • bank_transfer

    Almeno uno fra: {"type":"object"}{"type":"null"}

  • prepaid_flowstring

    Valori: "operator_link""none"

  • cash_requires_own_deliveryboolean

  • discounts

    Almeno uno fra: {"type":"object"}{"type":"null"}

  • friend_codes

    Almeno uno fra: {"type":"object"}{"type":"null"}

  • heavy_extras

    Almeno uno fra: {"type":"object"}{"type":"null"}

  • order_edit_window_hours

    Almeno uno fra: {"type":"number","minimum":0.5,"maximum":72}{"type":"null"}

  • checkout_upsell

    Almeno uno fra: {"type":"object"}{"type":"null"}

  • cart_reminderboolean

  • slot_on_sendstring

    Valori: "set_first""propose"

TestiDelNegozio

object

The shop's texts and site settings: the phrases of the closed list, the assistant's hours, the departments, the basic shopping list, site.

  • phrasesarray<object>

  • assistant_hours

    Almeno uno fra: {"type":"object"}{"type":"null"}

  • departmentsarray<object>

  • weekly_shop_base_listarray<string>

  • siteobject

GettoneIdentitaInIngresso

object

The customer your website has authenticated, and how long the token lasts.

  • customer_refstringobbligatorio

    The customer's external_ref (PUT /v1/customers), in the key's environment. No leading or trailing spaces.

    minLength: 1maxLength: 128

  • expires_ininteger

    Seconds the token is valid, from when we mint it to when the widget opens the session.

    minimum: 30maximum: 600default: 300

GettoneIdentita

object

  • identity_tokenstringobbligatorio

    The token, to pass to the widget (identity_token of core-chat /session). Shown only here; valid once.

    pattern: ^gai_cid_(test|live)_[A-Za-z0-9]{40}$

  • expires_atstringobbligatorio

    After this instant the token opens nothing.

    format: date-time

  • chat_idstringobbligatorio

    The customer's chat identity: always the same for them, and the customer.chatId of orders that come from their chat.

    pattern: ^cv_[0-9a-f]{32}$

  • customer_refstringobbligatorio

    The customer it was minted for, as you wrote it.

IdentitaDellaSessione

object

The identity field of the core-chat /session response, present only if the request carried identity_token. verified: the session belongs to your customer. not_verified: the session started anonymous, and code says why.

  • statusstringobbligatorio

    Valori: "verified""not_verified"

  • codestring

    Only with not_verified.

    Valori: "IDENTITA_MALFORMATA""IDENTITA_SCONOSCIUTA""IDENTITA_GIA_USATA""IDENTITA_SCADUTA""IDENTITA_DI_UN_ALTRO_AMBIENTE""CLIENTE_SCONOSCIUTO""IDENTITA_FUORI_DAL_NEGOZIO""IDENTITA_NON_IN_SERVIZIO"

StatoOrdineRegistrato

object

  • order_idstringobbligatorio

  • statusstringobbligatorio

    Valori: "delivered""substituted""not_delivered""returned""preparing""ready""out_for_delivery""delayed""rescheduled"

  • delivered_amountnumber | nullobbligatorio

    The reported value; null if not reported (always null with progress).

  • sourcestringobbligatorio

    The channel of the report.

    Valori: "api"

  • reported_atstringobbligatorio

    format: date-time

  • received_atstringobbligatorio

    When we recorded it.

    format: date-time

  • duplicatebooleanobbligatorio

    True if the same report had already arrived.

  • kindstringobbligatorio

    outcome an outcome (counts for billing) · progress a progress report.

    Valori: "outcome""progress"

  • etaobject

    Echoed as received, only if sent.

    • startstringobbligatorio

      format: date-time

    • endstringobbligatorio

      format: date-time

  • reasonstring

    Echoed as received, only if sent.

    Valori: "stock""capacity""traffic""weather""customer_request""shop_request""failed_attempt""other"

  • tracking_urlstring

    Echoed as received, only if sent.

    format: uri

  • supersededboolean

    Present when the progress report is older (by reported_at) than the last one recorded: kept, without an order.updated event.

    Valori: true

RichiestaDaRitirare

object

  • support_idstringobbligatorio

    Pass it to the ack.

  • event_idstringobbligatorio

    format: uuid

  • typestringobbligatorio

    Valori: "support.requested"

  • payloadRichiestaAssistenzaobbligatorio

  • occurred_atstringobbligatorio

    format: date-time

  • created_atstringobbligatorio

    format: date-time

  • statostringobbligatorio

    Valori: "in_attesa""consegnato"

  • consegnato_atstring | nullobbligatorio

    format: date-time

ClienteDellEvento

object

The customer to deliver to, read from their record and never from the model. The web channel has no contact details: phone and email are null and listed in missing_fields.

  • chatIdstringobbligatorio

    The customer's opaque identity in the channel.

  • channelstring | null

  • fullNamestring | null

  • addressstring | null

  • citystring | null

  • zipstring | null

  • phonestring | null

  • emailstring | null

  • notesstring | null

  • missing_fieldsarray<string>

    The fields the shop will not receive.

OrdineConfermato

object

The body of order.confirmed (webhook data, pull payload). schema_version 2 since 2026-10-11: it carries the whole customer. Version 1 events, still in the log and therefore in the pull, lack the field and their customer has only chatId.

  • schema_versioninteger

    Valori: 2

  • orderobjectobbligatorio

    • idstringobbligatorio

    • statusstringobbligatorio

      Valori: "confirmed"

    • linesarray<object>obbligatorio

      • skustring | nullobbligatorio

      • namestringobbligatorio

      • brandstring | nullobbligatorio

      • qtynumberobbligatorio

      • unitstring | nullobbligatorio

      • unit_pricenumber | nullobbligatorio

        null means "to be sourced", not zero.

      • out_of_catalogbooleanobbligatorio

    • totalsobjectobbligatorio

      Amounts in the account's currency, computed by the database.

      • subtotalnumber | null

      • discountsnumber | null

      • deliverynumber | null

      • extrasnumber | null

      • totalnumber | null

    • deliveryobjectobbligatorio

      The chosen delivery slot; empty if there is none.

      • startISOstring

        format: date-time

      • endISOstring

        format: date-time

      • labelstring

    • customerClienteDellEventoobbligatorio

    • notesstring | nullobbligatorio

      The order note, or the customer's notes when it is missing.

    • currencystring

      The currency of the amounts (ISO 4217), in orders of platform shops since 2026-10-27. Earlier events do not carry it: they were in euro.

      pattern: ^[A-Z]{3}$

RichiestaAssistenza

object

The body of support.requested (webhook data, pull payload).

  • schema_versionintegerobbligatorio

    Valori: 1

  • support_requestobjectobbligatorio

    • idstringobbligatorio

      Also the idempotency key: the same message received twice does not produce two requests.

    • kindstringobbligatorio

      Valori: "cancel_order""modify_order""order_status""complaint""third_party_order""contact_request""price_match""fragile""payment_link""payment_received""other""name_unverified"

    • outcomestringobbligatorio

      nuova (new), or a case already reported to which the customer adds a fact (cumulativa) or on which they insist (escalation).

      Valori: "nuova""cumulativa""escalation"

    • customer_messagestring | nullobbligatorio

      The customer's text (at most 300 characters), never a paraphrase.

    • langstring | nullobbligatorio

    • channelstringobbligatorio

    • order_codestring | nullobbligatorio

    • customerClienteDellEventoobbligatorio

OrdineAggiornato

object

The body of order.updated (webhook data). No customer data and no amounts: whoever listens to the order already has them from order.confirmed.

  • schema_versionintegerobbligatorio

    Valori: 1

  • orderobjectobbligatorio

    • idstringobbligatorio

      The order identifier (order.id of order.confirmed).

    • event_idstringobbligatorio

      The identifier of the report (also resource_id).

      format: uuid

    • statusstringobbligatorio

      Valori: "delivered""substituted""not_delivered""returned""preparing""ready""out_for_delivery""delayed""rescheduled"

    • kindstringobbligatorio

      Valori: "outcome""progress"

    • reported_atstringobbligatorio

      When it happened, for the shop.

      format: date-time

    • etaobject

      The expected or agreed window, if reported.

      • startstringobbligatorio

        format: date-time

      • endstringobbligatorio

        format: date-time

    • reasonstring

      The reason, if reported.

      Valori: "stock""capacity""traffic""weather""customer_request""shop_request""failed_attempt""other"

    • tracking_urlstring

      The tracking link, if reported.

      format: uri

Approvazione

object

  • objectstringobbligatorio

    Valori: "approval"

  • idstringobbligatorio

    format: uuid

  • statusstringobbligatorio

    pending waits for a person; approved: send the same request again with GroceryAI-Approval-Id; consumed: already executed; expired: 72 hours without use.

    Valori: "pending""approved""rejected""consumed""expired"

  • operation_idstringobbligatorio

    The requested operation (deleteProduct, commitProductSnapshot, reportOrderStatus).

  • methodstringobbligatorio

  • pathstringobbligatorio

    The path with its values, as it was called.

  • environmentstringobbligatorio

    Valori: "test""live"

  • created_atstringobbligatorio

    format: date-time

  • expires_atstringobbligatorio

    format: date-time

  • decided_atstring | nullobbligatorio

    format: date-time

  • consumed_atstring | nullobbligatorio

    format: date-time

ApprovazioneInAttesa

object

  • dataobjectobbligatorio

    • objectstringobbligatorio

      Valori: "approval"

    • idstringobbligatorio

      format: uuid

    • statusstringobbligatorio

      Valori: "pending""approved"

    • operation_idstringobbligatorio

    • methodstringobbligatorio

    • pathstringobbligatorio

    • expires_atstringobbligatorio

      format: date-time

    • nextstringobbligatorio

      What to do next, in one sentence.

  • request_idRequestIdobbligatorio

ProvaDeprecazione

object

  • probebooleanobbligatorio

    Valori: true

  • deprecated_atstringobbligatorio

    Since when the operation is deprecated: the same date as the Deprecation header.

    format: date-time

  • sunset_atstringobbligatorio

    Since when it may stop responding: the same date as the Sunset header.

    format: date-time

  • replacementstring | nullobbligatorio

    The operation to use instead (METHOD /v1/...), or null.

  • linkstringobbligatorio

    The deprecation page: the same address as the Link header.

    format: uri

Ping

object

  • testbooleanobbligatorio

    Valori: true

  • endpoint_idintegerobbligatorio

    The endpoint being tested.

Esempi provati

Verifica della firma con la libreria ufficiale Standard Webhooks (Node)

verify-standardwebhooks.mjs · javascript

// Receive GroceryAI webhooks with the OFFICIAL Standard Webhooks library. Node 18+.
//
//   npm install standardwebhooks
//   GAI_WEBHOOK_SECRET=whsec_... node verify-standardwebhooks.mjs      # http://localhost:8080/webhooks
//
// The library checks webhook-id, webhook-timestamp (300 seconds tolerance) and webhook-signature (one or two `v1,`
// signatures: two while a secret rotation is in progress). Pass the RAW body and the secret as the portal showed it.
// Specification: https://www.standardwebhooks.com

import http from 'node:http';
import { fileURLToPath } from 'node:url';
import { Webhook } from 'standardwebhooks';

/** Verify one delivery: the parsed event, or null when it is forged, altered or stale. */
export const verifyDelivery = (rawBody, headers, secret) => {
  try { return new Webhook(secret).verify(rawBody, headers); } catch { return null; }
};

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const wh = new Webhook(process.env.GAI_WEBHOOK_SECRET);   // "whsec_..."
  const seen = new Set();   // in production: a table with a unique key on webhook-id
  http.createServer((req, res) => {
    if (req.method !== 'POST' || req.url !== '/webhooks') { res.writeHead(404).end(); return; }
    const chunks = [];
    req.on('data', (c) => chunks.push(c));
    req.on('end', () => {
      let event;
      try { event = wh.verify(Buffer.concat(chunks).toString('utf8'), req.headers); } catch { res.writeHead(400).end(); return; }
      res.writeHead(200).end('ok');   // within 15 seconds, then work
      if (seen.has(req.headers['webhook-id'])) return;
      seen.add(req.headers['webhook-id']);
      console.log(event.type, event.environment, event.resource_id);
    });
  }).listen(Number(process.env.PORT ?? 8080));
}

Verifica della firma con la libreria ufficiale Standard Webhooks (Python)

verify_standardwebhooks.py · python

"""Receive GroceryAI webhooks with the OFFICIAL Standard Webhooks library. Python 3.8+.

    pip install standardwebhooks flask
    GAI_WEBHOOK_SECRET=whsec_... flask --app verify_standardwebhooks run --port 8080

The library checks webhook-id, webhook-timestamp (300 seconds tolerance) and webhook-signature (one or two `v1,`
signatures: two while a secret rotation is in progress). Pass the RAW body and the secret as the portal showed it.
Specification: https://www.standardwebhooks.com
"""

import os

from standardwebhooks.webhooks import Webhook, WebhookVerificationError


def verify_delivery(raw_body, headers, secret):
    """Return the parsed event, or None when the delivery is forged, altered or stale."""
    try:
        return Webhook(secret).verify(raw_body, dict(headers))
    except WebhookVerificationError:
        return None


try:
    from flask import Flask, request

    app = Flask(__name__)
    seen = set()  # in production: a table with a unique key on webhook-id

    @app.post("/webhooks")
    def webhooks():
        event = verify_delivery(request.get_data(as_text=True), request.headers, os.environ["GAI_WEBHOOK_SECRET"])
        if event is None:
            return "", 400
        if request.headers["webhook-id"] not in seen:
            seen.add(request.headers["webhook-id"])
            print(event["type"], event["environment"], event["resource_id"])
        return "ok", 200  # within 15 seconds, then work
except ImportError:  # the verification above works without Flask
    app = None

Verifica della firma senza dipendenze (Node)

verify-signature.mjs · javascript

// Verify a GroceryAI webhook delivery (Standard Webhooks 1.0.0) with NO dependency. Node 18+.
//
//   GAI_WEBHOOK_SECRET=whsec_... node verify-signature.mjs      # a minimal receiver on http://localhost:8080/webhooks
//
// Prefer the official library (`npm install standardwebhooks`, see verify-standardwebhooks.mjs): this file does exactly
// what it does, for a runtime where you cannot add a dependency. Specification: https://www.standardwebhooks.com
//
// Every delivery is a POST with a JSON body and these headers:
//   webhook-id         the message id = the event id (the same on every attempt: use it to drop duplicates)
//   webhook-timestamp  Unix seconds of this attempt (it changes on every retry)
//   webhook-signature  "v1,<base64>" HMAC-SHA256 of `${webhook-id}.${webhook-timestamp}.${raw body}`; during a secret
//                      rotation two of them, separated by a space: one matching is enough
//
// The secret is the endpoint's signing secret exactly as the portal showed it: "whsec_" + base64. The HMAC key is the
// base64-DECODED bytes, not the string. Verify on the RAW bytes of the body: parsing and re-serialising the JSON changes them.

import crypto from 'node:crypto';
import http from 'node:http';
import { fileURLToPath } from 'node:url';

/** The tolerance of the official libraries: five minutes covers clock drift and slow networks. */
export const TOLERANCE_SECONDS = 300;

const header = (headers, name) => {
  for (const [k, v] of Object.entries(headers)) if (k.toLowerCase() === name) return Array.isArray(v) ? v[0] : v;
  return undefined;
};

/**
 * @param {Buffer|string} rawBody  the request body exactly as received
 * @param {Record<string, string|string[]|undefined>} headers  the request headers (any case)
 * @param {string} secret  the endpoint's signing secret, "whsec_..." included
 * @returns {{ ok: true } | { ok: false, reason: 'bad_secret' | 'missing_headers' | 'bad_timestamp' | 'timestamp_out_of_tolerance' | 'signature_mismatch' }}
 */
export function verifyGroceryAiSignature(rawBody, headers, secret, { toleranceSeconds = TOLERANCE_SECONDS, now = Date.now() } = {}) {
  if (typeof secret !== 'string' || !secret.startsWith('whsec_')) return { ok: false, reason: 'bad_secret' };
  const key = Buffer.from(secret.slice('whsec_'.length), 'base64');
  if (key.length === 0) return { ok: false, reason: 'bad_secret' };
  const id = header(headers, 'webhook-id');
  const timestamp = header(headers, 'webhook-timestamp');
  const signatures = header(headers, 'webhook-signature');
  if (!id || !timestamp || !signatures) return { ok: false, reason: 'missing_headers' };
  if (!/^\d+$/.test(timestamp)) return { ok: false, reason: 'bad_timestamp' };
  // The timestamp is inside the signed string: an old delivery replayed later fails here, even with a valid signature.
  if (Math.abs(Math.floor(now / 1000) - Number(timestamp)) > toleranceSeconds) return { ok: false, reason: 'timestamp_out_of_tolerance' };
  const expected = Buffer.from(crypto.createHmac('sha256', key).update(`${id}.${timestamp}.`).update(rawBody).digest('base64'));
  for (const versioned of String(signatures).split(' ')) {
    const [version, value] = versioned.split(',');
    if (version !== 'v1' || value === undefined) continue;
    const given = Buffer.from(value);
    if (given.length === expected.length && crypto.timingSafeEqual(given, expected)) return { ok: true };
  }
  return { ok: false, reason: 'signature_mismatch' };
}

// A minimal receiver: verify, drop duplicates, answer 2xx fast, work afterwards.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const secret = process.env.GAI_WEBHOOK_SECRET;
  if (!secret) { console.error('set GAI_WEBHOOK_SECRET'); process.exit(1); }
  const seen = new Set();   // in production: a table with a unique key on webhook-id
  http.createServer((req, res) => {
    if (req.method !== 'POST' || req.url !== '/webhooks') { res.writeHead(404).end(); return; }
    const chunks = [];
    req.on('data', (c) => chunks.push(c));
    req.on('end', () => {
      const raw = Buffer.concat(chunks);
      const check = verifyGroceryAiSignature(raw, req.headers, secret);
      if (!check.ok) { res.writeHead(400).end(check.reason); return; }
      const event = JSON.parse(raw.toString('utf8'));
      res.writeHead(200).end('ok');   // within 15 seconds, or the attempt counts as failed
      if (seen.has(req.headers['webhook-id'])) return;
      seen.add(req.headers['webhook-id']);
      if (event.type === 'order.confirmed') console.log('order', event.data.order.id, event.environment);
      else if (event.type === 'support.requested') console.log('support request', event.data.support_request.id, event.data.support_request.kind);
      else if (event.type === 'webhook.ping') console.log('ping for endpoint', event.data.endpoint_id);
    });
  }).listen(Number(process.env.PORT ?? 8080));
}

Verifica della firma senza dipendenze (Python)

verify_signature.py · python

"""Verify a GroceryAI webhook delivery (Standard Webhooks 1.0.0) with NO dependency. Python 3.8+, standard library only.

Prefer the official library (`pip install standardwebhooks`, see verify_standardwebhooks.py): this file does exactly what
it does, for a runtime where you cannot add a dependency. Specification: https://www.standardwebhooks.com

Every delivery is a POST with a JSON body and these headers:
  webhook-id         the message id = the event id (the same on every attempt: use it to drop duplicates)
  webhook-timestamp  Unix seconds of this attempt (it changes on every retry)
  webhook-signature  "v1,<base64>" HMAC-SHA256 of f"{webhook-id}.{webhook-timestamp}.{raw body}"; during a secret
                     rotation two of them, separated by a space: one matching is enough

The secret is the endpoint's signing secret exactly as the portal showed it: "whsec_" + base64. The HMAC key is the
base64-DECODED bytes, not the string. Verify on the RAW bytes of the body: parsing and re-serialising the JSON changes them.

With Flask, for example:

    @app.post("/webhooks")
    def webhooks():
        ok, reason = verify_signature(request.get_data(), request.headers, os.environ["GAI_WEBHOOK_SECRET"])
        if not ok:
            return reason, 400
        event = request.get_json()
        # drop duplicates by request.headers["webhook-id"], answer within 15 seconds, work afterwards
        return "ok", 200
"""

import base64
import binascii
import hashlib
import hmac
import time

# The tolerance of the official libraries: five minutes covers clock drift and slow networks.
TOLERANCE_SECONDS = 300


def verify_signature(raw_body, headers, secret, tolerance_seconds=TOLERANCE_SECONDS, now=None):
    """Return (True, "ok") or (False, reason).

    reason is one of: bad_secret, missing_headers, bad_timestamp, timestamp_out_of_tolerance, signature_mismatch.
    raw_body: bytes exactly as received; headers: any mapping (any case); secret: "whsec_..." included.
    """
    if not isinstance(secret, str) or not secret.startswith("whsec_"):
        return False, "bad_secret"
    try:
        key = base64.b64decode(secret[len("whsec_"):], validate=True)
    except (binascii.Error, ValueError):
        return False, "bad_secret"
    if not key:
        return False, "bad_secret"
    lowered = {str(k).lower(): v for k, v in dict(headers).items()}
    msg_id = lowered.get("webhook-id")
    timestamp = lowered.get("webhook-timestamp")
    signatures = lowered.get("webhook-signature")
    if not msg_id or not timestamp or not signatures:
        return False, "missing_headers"
    if not str(timestamp).isdigit():
        return False, "bad_timestamp"
    current = int(time.time()) if now is None else int(now)
    # The timestamp is inside the signed string: an old delivery replayed later fails here, even with a valid signature.
    if abs(current - int(timestamp)) > tolerance_seconds:
        return False, "timestamp_out_of_tolerance"
    if isinstance(raw_body, str):
        raw_body = raw_body.encode("utf-8")
    signed = str(msg_id).encode("utf-8") + b"." + str(timestamp).encode("ascii") + b"." + raw_body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode("ascii")
    for versioned in str(signatures).split(" "):
        version, _, value = versioned.partition(",")
        if version == "v1" and hmac.compare_digest(value, expected):
            return True, "ok"
    return False, "signature_mismatch"

Ritiro in pull e conferma (Node)

pull-orders.mjs · javascript

// Take orders and support requests by pull, then acknowledge them. Node 18+, no dependencies.
//
//   GAI_API_KEY=gai_test_... node pull-orders.mjs
//
// The key needs `orders:read` (to list) and `orders:write` (to acknowledge). Its environment decides what you see:
// a `test` key sees test orders only, a `live` key real ones only. An item stays in `status=new` until you acknowledge
// it, so a crash between "saved" and "acknowledged" only means you will see it again: store by id, idempotently.

import { fileURLToPath } from 'node:url';

const BASE = process.env.GAI_API_BASE ?? 'https://qgdwytendnvkldxmbvpu.supabase.co/functions/v1/core-api';
const KEY = process.env.GAI_API_KEY;

const call = async (method, path, idempotencyKey) => {
  // `x-region` runs the platform next to its database (Frankfurt): optional, it only saves latency.
  const headers = { authorization: `Bearer ${KEY}`, 'x-region': 'eu-central-1' };
  if (idempotencyKey) headers['idempotency-key'] = idempotencyKey;
  const res = await fetch(`${BASE}${path}`, { method, headers });
  const body = await res.json();
  if (res.status === 429) {
    const wait = Number(res.headers.get('retry-after') ?? '60');
    await new Promise((r) => setTimeout(r, wait * 1000));
    return call(method, path, idempotencyKey);
  }
  if (!res.ok) throw new Error(`${method} ${path}: ${res.status} ${body.error?.code} (request_id ${body.request_id})`);
  return body;
};

/** Your side: save the item. Must be idempotent on the id (the same item can come twice). */
const save = async (kind, id, payload) => {
  console.log(`saved ${kind} ${id}`, kind === 'order' ? `${payload.order.lines.length} lines` : payload.support_request.kind);
};

export const pullOnce = async () => {
  let handled = 0;
  const done = new Set();
  for (const [kind, list, idField, ack] of [
    ['order', '/v1/orders', 'order_id', (id) => `/v1/orders/${encodeURIComponent(id)}/ack`],
    ['support request', '/v1/support_requests', 'support_id', (id) => `/v1/support_requests/${encodeURIComponent(id)}/ack`],
  ]) {
    // Oldest first, up to 200 per call; acknowledging is what moves the queue forward.
    for (;;) {
      const page = await call('GET', `${list}?status=new&limit=50`);
      if (page.data.length === 0) break;
      for (const item of page.data) {
        // An item acknowledged in this run must not come back: if it does, stop instead of looping.
        if (done.has(item.event_id)) throw new Error(`${kind} ${item[idField]} is still new after its ack`);
        done.add(item.event_id);
        await save(kind, item[idField], item.payload);
        // Acknowledging twice is not an error; the idempotency key makes a retried call harmless.
        await call('POST', ack(item[idField]), `ack-${item.event_id}`);
        handled++;
      }
    }
  }
  return handled;
};

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  if (!KEY) { console.error('set GAI_API_KEY'); process.exit(1); }
  pullOnce().then((n) => console.log(`done: ${n} acknowledged`)).catch((e) => { console.error(e.message); process.exit(1); });
}