Webhook dell'API rivenditori
Eventi webhook, payload, verifica della firma HMAC in Python e Node, retry con backoff, regole di sicurezza degli URL e deduplicazione per ID evento.
Eventi webhook, payload, verifica della firma HMAC in Python e Node, nuovi tentativi con backoff, regole di sicurezza degli URL e deduplicazione per id dell'evento.
Tutti i modelli, le funzionalità e i prezzi Indice della documentazione per agenti AI:https://oneprovider.dev/docs/llms.txt Creare un webhook
POST /webhooks (scope webhooks): un URL solo https e un elenco non vuoto di eventi. Al massimo 5 webhook. Idempotency-Key facoltativa: una ripetizione restituisce lo stesso webhook, senza il segreto. last_delivered_at è l'ora dell'ultima risposta 2xx del tuo server (null finché non ce n'è stata una).
curl -s -X POST https://app.oneprovider.dev/partner/v1/webhooks \
-H "Authorization: Bearer $OP_PARTNER_TOKEN" \
-H "Content-Type: application/json" \
-d '{"url":"https://shop.example.com/op-webhook","events":["order.completed","balance.low"]}' json {
"id": "<webhook id>",
"url": "https://shop.example.com/op-webhook",
"events": ["order.completed", "balance.low"],
"active": true,
"secret_last4": "a1b2",
"created_at": "2026-10-08T12:00:00Z",
"last_delivered_at": null,
"secret": "whsec_..."
} Il segreto di firma viene mostrato una sola volta Il campo secret arriva solo nella risposta di creazione. Conservalo sul tuo server; un segreto perso non si recupera, crea di nuovo il webhook. Eventi
| Evento | Quando | data |
|---|---|---|
key.created | È stata emessa una chiave (dall'API, dall'area personale, da un ordine o da un codice). | key_id, name, limit_usd, customer_id, source (api, cabinet, order, code) |
key.paused | Una chiave è stata messa in pausa (a mano o perché il suo cliente è stato bloccato). | key_id, reason (solo per un blocco: customer_blocked) |
key.resumed | Una chiave è stata riattivata (a mano o perché il suo cliente è stato sbloccato). | key_id, reason (solo per uno sblocco: customer_unblocked) |
code.redeemed | Un codice è stato riscattato. | batch_id, code_tail, key_id, amount_usd |
order.completed | Un ordine è stato completato. | order_id, external_order_id, kind, key_id, amount_usd |
balance.topped_up | Il saldo da rivenditore è stato ricaricato. | amount_usd, order_id |
balance.low | Il saldo è sceso sotto la soglia (la imposta OneProvider, $10 di default, uguale per tutti). Arriva una volta sola, e di nuovo solo dopo che il saldo è tornato sopra la soglia. | balance_usd, threshold_usd |
key.exhausted | Il limite di una chiave è esaurito. Una volta per chiave e limite venduto, entro pochi minuti; una ricarica della chiave riattiva l'evento. | key_id, limit_usd |
I dati dell'evento non contengono mai segreti: né chiavi, né token, né codici. Il test (POST /webhooks/{id}/test) invia l'evento di servizio webhook.test con data {"message": "test"}; non puoi iscriverti a questo evento.
Richiesta e firma
Inviamo una POST con un corpo JSON:
json{
"id": "evt_...",
"type": "order.completed",
"created_at": "2026-10-08T12:00:00Z",
"data": {
"order_id": 42,
"external_order_id": "shop-1042",
"kind": "new_key",
"key_id": "<key id>",
"amount_usd": "10.00"
}
} Il corpo viene inviato come JSON compatto con le chiavi in ordine alfabetico; verifica la firma sui byte esattamente come sono arrivati, non su un JSON ricostruito.
| Header | Valore |
|---|---|
X-OP-Signature | t=<unix>,v1=<hex> |
X-OP-Event | Il tipo di evento. |
X-OP-Delivery | Uguale all'id dell'evento. |
User-Agent | OneProvider-Webhooks/1 |
v1 è l'esadecimale di un HMAC-SHA256 la cui chiave è il segreto del webhook (whsec_...) e il cui messaggio è la stringa "<t>" + "." + raw_body.
Verificare la firma
- Leggi il corpo grezzo della richiesta: la firma copre i byte esatti, un JSON serializzato di nuovo non corrisponderà.
- Ricalcola l'HMAC e confrontalo con v1 in tempo costante (hmac.compare_digest, timingSafeEqual).
- Rifiuta la richiesta se |now - t| supera 5 minuti, così una vecchia firma non può essere riutilizzata.
- Rispondi 2xx in fretta (il timeout è di 10 secondi) e fai il lavoro pesante in modo asincrono.
Python
pythonimport hashlib
import hmac
import time
TOLERANCE = 300 # seconds
def verify(secret: str, header: str, raw_body: bytes) -> bool:
"""header is X-OP-Signature: t=<unix>,v1=<hex>; raw_body is the unparsed request body."""
parts = dict(p.strip().partition("=")[::2] for p in header.split(","))
t, v1 = parts.get("t", ""), parts.get("v1", "")
if not t.isdigit() or abs(time.time() - int(t)) > TOLERANCE:
return False
signed = t.encode() + b"." + raw_body
expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, v1) python import json
import os
from fastapi import FastAPI, HTTPException, Request
app = FastAPI()
SECRET = os.environ["OP_WEBHOOK_SECRET"] # whsec_...
seen: set[str] = set() # use a database table with a unique index in production
@app.post("/op-webhook")
async def op_webhook(request: Request):
raw = await request.body() # the raw bytes, before any JSON parsing
if not verify(SECRET, request.headers.get("X-OP-Signature", ""), raw):
raise HTTPException(status_code=400, detail="bad signature")
event = json.loads(raw)
if event["id"] in seen: # retries resend the same event id
return {"ok": True}
seen.add(event["id"])
if event["type"] == "order.completed":
... # your logic
return {"ok": True} # any 2xx marks the event as delivered Node.js
javascriptimport crypto from "node:crypto"
import express from "express"
const SECRET = process.env.OP_WEBHOOK_SECRET // whsec_...
const TOLERANCE = 300 // seconds
const seen = new Set() // use a database table with a unique index in production
function verify(secret, header, raw) {
const parts = Object.fromEntries(
String(header).split(",").map((p) => p.trim().split("=")),
)
const t = Number(parts.t)
if (!Number.isInteger(t) || Math.abs(Date.now() / 1000 - t) > TOLERANCE) return false
const expected = crypto
.createHmac("sha256", secret)
.update(parts.t + ".")
.update(raw)
.digest("hex")
const a = Buffer.from(expected)
const b = Buffer.from(parts.v1 ?? "")
return a.length === b.length && crypto.timingSafeEqual(a, b)
}
const app = express()
// express.raw keeps the body as a Buffer: do not use express.json() on this route
app.post("/op-webhook", express.raw({ type: "application/json" }), (req, res) => {
if (!verify(SECRET, req.get("X-OP-Signature"), req.body)) return res.sendStatus(400)
const event = JSON.parse(req.body.toString("utf8"))
if (!seen.has(event.id)) {
seen.add(event.id) // retries resend the same event id
if (event.type === "order.completed") {
// your logic
}
}
res.sendStatus(200) // any 2xx marks the event as delivered
})
app.listen(3000) Nuovi tentativi
Solo una risposta 2xx conta come consegnata. Tutto il resto (compreso 3xx, perché i redirect non vengono seguiti, oltre a timeout ed errori di connessione) viene ritentato con backoff esponenziale: 1 minuto, 2, 4 e così via (l'intervallo tra i tentativi non supera le 4 ore), fino a 24 ore dopo l'evento; poi la consegna diventa failed. Ogni nuovo tentativo porta lo stesso id dell'evento, quindi deduplica su quello: tieni gli id elaborati in una tabella con un indice univoco.
Regole per gli URL
- Solo https, porta 443 (qualsiasi altra porta dà 400 invalid_url) e un hostname; gli IP letterali vengono rifiutati. L'URL è lungo al massimo 500 caratteri ASCII, senza nome utente, password né frammento.
- Ogni indirizzo a cui il nome si risolve non deve essere privato, loopback, link-local o riservato.
- Il controllo viene eseguito alla creazione e a ogni consegna. Una violazione alla creazione dà 400
invalid_url.
Test e registro
bashcurl -s -X POST https://app.oneprovider.dev/partner/v1/webhooks/<webhook id>/test -H "Authorization: Bearer $OP_PARTNER_TOKEN"
curl -s "https://app.oneprovider.dev/partner/v1/webhooks/<webhook id>/deliveries?limit=20" -H "Authorization: Bearer $OP_PARTNER_TOKEN" Oggetto consegna: id, event_id, event, status (pending, delivered, failed), attempts, next_attempt_at, last_error (http_<status>, timeout, blocked_address o il nome dell'errore di connessione), last_status (lo stato HTTP con cui ha risposto il tuo server, null se non ha risposto), last_body (l'inizio della risposta, fino a 300 caratteri, su una riga), created_at. Eliminare un webhook: DELETE /webhooks/{id}. Test e nuovi tentativi manuali (nell'area personale) insieme sono limitati a 6 al minuto; si può ritentare solo un evento non consegnato, uno consegnato dà 409 already_delivered. Il nuovo tentativo manuale è disponibile solo nell'area personale, non con un token.