Developer Docs
REST API v1 per connettere PMS, sistemi di controllo accessi, channel manager e qualsiasi piattaforma hospitality con Shangrilux.
Sezioni
Tutte le richieste devono includere l'header X-API-Key con la tua chiave API. Le chiavi sono generate dal pannello admin del tuo tenant (Impostazioni → API Keys).
# Includi in ogni richiesta
X-API-Key: ostx_your_api_key_hereLe chiavi hanno formato ostx_.... Non esporle in codice client-side o repository pubblici.
Il rate limiting è sliding window di 1 ora. Ogni risposta include gli header di stato.
| Piano | Richieste/ora | Feature API |
|---|---|---|
| Essenziale | — | Non disponibile |
| Professional | 2.000 | Inclusa |
| Elite | 10.000 | Inclusa |
# Header di risposta rate limiting
X-RateLimit-Limit: 2000
X-RateLimit-Remaining: 1847
X-RateLimit-Reset: 1748563200 # Unix timestamp del prossimo reset
# Se superi il limite (HTTP 429):
{ "detail": "Rate limit superato: 2000 richieste/ora per il piano professional." }
# Retry-After: 3600| Codice HTTP | Significato |
|---|---|
| 200 | Successo (o deduplicazione booking esistente) |
| 201 | Risorsa creata con successo |
| 400 | Parametri non validi |
| 401 | API Key mancante o non valida |
| 403 | API non abilitata per questo piano |
| 404 | Risorsa non trovata |
| 409 | Conflitto (es. booking già annullata) |
| 422 | Validation error (body malformato) |
| 429 | Rate limit superato |
| 500 | Errore interno — contatta il supporto |
Shangrilux invia notifiche HTTP outbound al tuo endpoint ogni volta che si verifica un evento (prenotazione, check-in, comando accesso, ecc.). Ogni richiesta include una firma HMAC-SHA256 che puoi verificare per garantire l'autenticità del payload.
Header inviati da Shangrilux
| Header | Valore / Descrizione |
|---|---|
| X-Shangrilux-Signature | sha256=<hmac_hex> — Firma del body con il tuo secret |
| X-Shangrilux-Event | booking.created | booking.confirmed | booking.cancelled | ... |
| X-Shangrilux-Delivery | <webhook_id>-<attempt> — ID univoco della consegna |
| Content-Type | application/json |
| User-Agent | Shangrilux-Webhook/1.0 |
Verifica firma in Python
import hmac
import hashlib
from fastapi import Request, HTTPException
WEBHOOK_SECRET = "il_tuo_secret_shangrilux" # da salvare in .env
async def verify_shangrilux_signature(request: Request) -> dict:
"""Verifica la firma HMAC-SHA256 del webhook Shangrilux."""
signature_header = request.headers.get("X-Shangrilux-Signature", "")
event_type = request.headers.get("X-Shangrilux-Event", "")
body = await request.body()
# Calcola HMAC-SHA256 del body raw con il tuo secret
expected = "sha256=" + hmac.new(
WEBHOOK_SECRET.encode("utf-8"),
body,
hashlib.sha256
).hexdigest()
if not hmac.compare_digest(expected, signature_header):
raise HTTPException(status_code=401, detail="Firma webhook non valida.")
import json
payload = json.loads(body)
return payload
# Endpoint FastAPI di esempio
from fastapi import APIRouter
router = APIRouter()
@router.post("/webhook/shangrilux")
async def receive_webhook(request: Request):
payload = await verify_shangrilux_signature(request)
event = payload.get("event")
if event == "booking.created":
booking = payload["data"]
print(f"Nuova prenotazione: {booking['guest_name']} → {booking['property_id']}")
# Sincronizza con il tuo PMS qui...
elif event == "booking.confirmed":
print(f"Prenotazione confermata: {payload['data']['id']}")
return {"received": True}Verifica firma in Node.js / Express
const express = require('express');
const crypto = require('crypto');
const WEBHOOK_SECRET = process.env.SHANGRILUX_SECRET; // da .env
// Middleware: verifica firma HMAC-SHA256
function verifyShangriluxSignature(req, res, next) {
const signatureHeader = req.headers['x-shangrilux-signature'] || '';
const rawBody = req.rawBody; // richiede bodyParser con verify
if (!rawBody) {
return res.status(400).json({ error: 'Body grezzo non disponibile.' });
}
const expected = 'sha256=' + crypto
.createHmac('sha256', WEBHOOK_SECRET)
.update(rawBody)
.digest('hex');
// Usa timingSafeEqual per prevenire timing attacks
const sigBuffer = Buffer.from(signatureHeader);
const expBuffer = Buffer.from(expected);
if (sigBuffer.length !== expBuffer.length ||
!crypto.timingSafeEqual(sigBuffer, expBuffer)) {
return res.status(401).json({ error: 'Firma webhook non valida.' });
}
next();
}
const app = express();
// IMPORTANTE: usa il middleware con il body raw per l'HMAC
app.use('/webhook/shangrilux', express.json({
verify: (req, res, buf) => { req.rawBody = buf; }
}));
app.post('/webhook/shangrilux', verifyShangriluxSignature, (req, res) => {
const { event, data, tenant } = req.body;
switch (event) {
case 'booking.created':
console.log(`Nuova prenotazione da ${tenant}:`, data.guest_name);
// Sincronizza con PMS...
break;
case 'booking.confirmed':
console.log(`Confermata prenotazione:`, data.id);
break;
case 'access.command':
console.log(`Comando accesso:`, data.command, 'su', data.device);
break;
}
res.json({ received: true });
});
app.listen(3000);Eventi supportati
| Evento | Descrizione | Quando viene emesso |
|---|---|---|
| booking.created | Nuova prenotazione | Portale pubblico, API o pannello admin |
| booking.confirmed | Prenotazione confermata | Lo staff accetta la richiesta |
| booking.cancelled | Prenotazione cancellata | Cancellazione da qualsiasi fonte |
| booking.checkin | Check-in eseguito | Apertura serratura al check-in |
| access.command | Comando dispositivo | Lock/unlock da API o pannello |
| guest_key.generated | Chiave ospite generata | QR code / link condiviso |
| webhook.test | Test delivery | Test manuale dal pannello webhook |
Client pronti all'uso per Python e Node.js. Scarica il file, aggiungi la tua API Key e sei operativo in 5 minuti.
Python
~6KB
# Install pip install requests # Quick start from shangrilux_sdk import ShangriluxClient client = ShangriluxClient(api_key='ostx_...')
Node.js / Browser
~5KB
# Install # Nessuna dipendenza (usa fetch nativa) # Quick start const { ShangriluxClient } = require('./shangrilux-node-sdk'); const client = new ShangriluxClient({ apiKey: 'ostx_...' });
I SDK sono aggiornati alla versione API 1.0. Ogni file include esempi completi commentati.
Supporto
Per integrazioni personalizzate, webhook avanzati o accesso a funzionalità Enterprise, contatta il team tecnico Shangrilux.
🍪 Utilizziamo i cookie
Cookie necessari al funzionamento e cookie opzionali per analisi e marketing. Puoi scegliere quali accettare. Privacy Policy · Cookie Policy