Retry sicuri
Con idempotencyKey l'eventId è calcolato in modo deterministico (UUID v5 da applicazione e chiave). Dopo un timeout puoi ripetere la chiamata: lo stesso evento non viene elaborato due volte.
L'API di Saiot è piccola di proposito: una POST per inviare eventi, poche rotte per consultarli, un webhook per sapere com'è andata. Specifica OpenAPI 3.1 e documentazione Swagger pubbliche.
Dal backoffice ottieni la chiave API e il segreto HMAC della tua applicazione.
Crei il tipo di evento con il suo JSON Schema e i dati di esempio, partendo da un modello.
Configuri regole e template e li provi in anteprima con i dati di esempio.
Firmi la richiesta, invii l'evento e ricevi gli stati di consegna sul tuo webhook.
Nessun SDK obbligatorio: bastano un client HTTP e una funzione HMAC-SHA256. Sostituisci api.saiot.example con l'indirizzo che ti forniamo.
# SAIOT_API_KEY e SAIOT_SECRET arrivano dal backoffice
BODY='{"events":[{"type":"ordine.spedito","sender":"negozio-milano","idempotencyKey":"ord-A1042","data":{"ordine":"A-1042","totale":189.9,"cliente":{"nome":"Giulia","email":"giulia@example.com"}}}]}'
TS=$(date +%s)
SIG=$(printf '%s.%s' "$TS" "$BODY" | openssl dgst -sha256 -hmac "$SAIOT_SECRET" -hex | sed 's/^.* //')
curl https://api.saiot.example/v1/events \
-H "Authorization: Bearer $SAIOT_API_KEY" \
-H "Content-Type: application/json" \
-H "X-Saiot-Timestamp: $TS" \
-H "X-Saiot-Signature: v1=$SIG" \
--data-raw "$BODY"
import crypto from 'node:crypto';
const { SAIOT_API_KEY, SAIOT_SECRET } = process.env;
const body = JSON.stringify({
events: [{
type: 'ordine.spedito',
sender: 'negozio-milano',
idempotencyKey: 'ord-A1042',
data: {
ordine: 'A-1042',
totale: 189.9,
cliente: { nome: 'Giulia', email: 'giulia@example.com' },
},
}],
});
const ts = Math.floor(Date.now() / 1000).toString();
const sig = crypto
.createHmac('sha256', SAIOT_SECRET)
.update(`${ts}.${body}`)
.digest('hex');
const res = await fetch('https://api.saiot.example/v1/events', {
method: 'POST',
headers: {
'Authorization': `Bearer ${SAIOT_API_KEY}`,
'Content-Type': 'application/json',
'X-Saiot-Timestamp': ts,
'X-Saiot-Signature': `v1=${sig}`,
},
body,
});
console.log(res.status, await res.json()); // 202 { results: [ ... ] }
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
var apiKey = Environment.GetEnvironmentVariable("SAIOT_API_KEY")!;
var secret = Environment.GetEnvironmentVariable("SAIOT_SECRET")!;
var body = """
{"events":[{"type":"ordine.spedito","sender":"negozio-milano","idempotencyKey":"ord-A1042","data":{"ordine":"A-1042","totale":189.9}}]}
""";
var ts = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret));
var sig = Convert.ToHexString(hmac.ComputeHash(Encoding.UTF8.GetBytes($"{ts}.{body}"))).ToLowerInvariant();
using var http = new HttpClient();
using var req = new HttpRequestMessage(HttpMethod.Post, "https://api.saiot.example/v1/events")
{
Content = new StringContent(body, Encoding.UTF8, "application/json")
};
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
req.Headers.Add("X-Saiot-Timestamp", ts);
req.Headers.Add("X-Saiot-Signature", $"v1={sig}");
var res = await http.SendAsync(req);
Console.WriteLine($"{(int)res.StatusCode} {await res.Content.ReadAsStringAsync()}");
<?php
$body = json_encode(['events' => [[
'type' => 'ordine.spedito',
'sender' => 'negozio-milano',
'idempotencyKey' => 'ord-A1042',
'data' => ['ordine' => 'A-1042', 'totale' => 189.9],
]]]);
$ts = (string) time();
$sig = hash_hmac('sha256', $ts . '.' . $body, getenv('SAIOT_SECRET'));
$ch = curl_init('https://api.saiot.example/v1/events');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $body,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('SAIOT_API_KEY'),
'Content-Type: application/json',
'X-Saiot-Timestamp: ' . $ts,
'X-Saiot-Signature: v1=' . $sig,
],
]);
$response = curl_exec($ch);
echo curl_getinfo($ch, CURLINFO_HTTP_CODE), ' ', $response;
Firma esattamente i byte che invii: se serializzi di nuovo il JSON dopo aver calcolato la firma, la firma non corrisponde più.
POST /v1/eventsIl corpo contiene l'array events, da 1 a 100 elementi. Ogni elemento è un evento indipendente, con il suo esito.
| Campo | Obbligatorio | Descrizione |
|---|---|---|
type | sì | Codice del tipo di evento, per esempio ordine.spedito. |
data | sì | I dati dell'evento, validati con lo JSON Schema del tipo. |
sender | no | Codice del cliente: attiva le sue regole e i suoi template. Un codice sconosciuto viene rifiutato. |
component | no | Testo libero per statistiche e filtri, per esempio checkout. |
idempotencyKey | no | Chiave di deduplica: la stessa chiave genera sempre lo stesso eventId. |
sendAt | no | Data e ora ISO 8601 per l'invio programmato. |
attachments | no | Allegati in base64 con filename, contentType e content; fino a 20 MB in totale per chiamata. |
Con idempotencyKey l'eventId è calcolato in modo deterministico (UUID v5 da applicazione e chiave). Dopo un timeout puoi ripetere la chiamata: lo stesso evento non viene elaborato due volte.
Con sendAt l'evento viene elaborato all'ora indicata. Finché non è partito puoi annullarlo con DELETE /v1/events/:id.
| HTTP | Quando |
|---|---|
202 | Tutti gli eventi accettati |
207 | Almeno un evento rifiutato: l'esito è nel dettaglio di ogni elemento |
400 | JSON non valido, events assente o con più di 100 elementi |
401 | Chiave API o firma non valida |
413 | Allegati oltre 20 MB in totale |
429 | Limite di richieste dell'applicazione superato |
type non esiste per la tua applicazione.sender indicato non è censito.{
"results": [
{
"index": 0,
"status": "accepted",
"eventId": "5b1d9c3e-7a2f-5e0b-9c41-2f8a6d3e1b70"
},
{
"index": 1,
"status": "duplicate",
"eventId": "0f6a2c71-3d4e-5b8a-a1f0-7c9e2b4d6a13"
},
{
"index": 2,
"status": "error",
"code": "SCHEMA_INVALIDO",
"errors": ["data.totale deve essere un numero"]
}
]
}
La chiave API dice chi sei; la firma dimostra che la richiesta è tua, integra e recente.
Authorization: BearerAuthorization: Bearer <chiave API>
X-Saiot-Timestamp: 1791300000
X-Saiot-Signature: v1=<firma>
// firma = hex( HMAC-SHA256( segreto, timestamp + "." + corpo ) )
Per ogni messaggio Saiot chiama il tuo endpoint con una POST firmata con lo stesso schema, usando il segreto del webhook. Se non rispondi con un codice 2xx riprova con backoff fino a 24 ore; poi la notifica va in coda di scarto e si rinvia dal backoffice.
{
"eventId": "5b1d9c3e-7a2f-5e0b-9c41-2f8a6d3e1b70",
"messageId": "0192a6c4-8e1f-7b3a-9d2c-5e6f7a8b9c0d",
"channel": "whatsapp",
"recipient": "+393331234567",
"status": "delivered",
"at": "2026-10-07T09:00:04Z"
}
import crypto from 'node:crypto';
// rawBody: il corpo così come è arrivato, prima del parsing
export function firmaValida(rawBody, headers, segreto) {
const ts = headers['x-saiot-timestamp'];
const firma = headers['x-saiot-signature'] ?? '';
if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false;
const attesa = 'v1=' + crypto
.createHmac('sha256', segreto)
.update(`${ts}.${rawBody}`)
.digest('hex');
return firma.length === attesa.length &&
crypto.timingSafeEqual(Buffer.from(firma), Buffer.from(attesa));
}
| Stato | Significato |
|---|---|
queued | Messaggio composto e in coda per l'invio |
sent | Consegnato al provider |
delivered | Consegnato al destinatario |
read | Letto (WhatsApp) |
failed | Invio non riuscito |
bounced | Email rimbalzata |
complained | Email segnalata come spam dal destinatario |
skipped | Saltato: recapito assente nei dati, non fatturato |
| Rotta | Funzione |
|---|---|
POST /v1/events | Invia da 1 a 100 eventi |
GET /v1/events/:id | Stato dell'evento e dei suoi messaggi |
DELETE /v1/events/:id | Annulla un evento programmato non ancora partito |
GET /v1/event-types | Catalogo dei tipi di evento della tua applicazione |
GET /v1/event-types/:code/schema | JSON Schema di un tipo di evento |
GET /v1/openapi.json | Specifica OpenAPI 3.1, pubblica |
GET /v1/docs | Documentazione Swagger, pubblica |
Ti accompagniamo nell'integrazione: tipo di evento, regole, template e primo invio.