Aller au contenu
KelkiDéveloppeurs

Exemples de code

Les mêmes appels en curl, JavaScript et Python, sans dépendance. Lancez-les avec une clé de test : aucune demande réelle, aucun e-mail.

curl

# Jeton OAuth (ou utilisez directement une clé kk_test_… en Bearer)
curl -s https://kelki.ai/api/v1/oauth/token -u "$KELKI_CLIENT_ID:$KELKI_CLIENT_SECRET" \
  -d grant_type=client_credentials -d "scope=catalog.read requests.write requests.read"

# Brouillon
curl -s https://kelki.ai/api/v1/requests \
  -H "Authorization: Bearer $KELKI_TOKEN" -H "Content-Type: application/json" \
  -H "Idempotency-Key: resa-0042-draft-1" \
  -d '{"country":"FR","lang":"fr","trade_id":"plombier","service":"Recherche de fuite",
       "delay":"Dès que possible","place_id":"fr-creteil-94000",
       "contact":{"name":"Camille Exemple","phone":"+33639980042","email":"camille.exemple@example.com"},
       "reference":"resa-2026-0042"}'

# Confirmation par e-mail, APRÈS l'accord de la personne sur le récapitulatif
curl -s https://kelki.ai/api/v1/requests/req_01JC00000000000000000000RQ/confirmation \
  -H "Authorization: Bearer $KELKI_TOKEN" -H "Content-Type: application/json" \
  -H "Idempotency-Key: resa-0042-confirmation-1" \
  -d '{"method":"email","consent_text_version":"v2026-10-18","consent_given":true}'

# Statut
curl -s https://kelki.ai/api/v1/requests/req_01JC00000000000000000000RQ \
  -H "Authorization: Bearer $KELKI_TOKEN"

JavaScript (Node 18+, fetch)

const API = "https://kelki.ai/api/v1";
const headers = (extra = {}) => ({ Authorization: `Bearer ${process.env.KELKI_KEY}`, "Content-Type": "application/json", ...extra });

async function call(method, path, body, idem) {
  const r = await fetch(API + path, { method, headers: headers(idem ? { "Idempotency-Key": idem } : {}),
                                      body: body ? JSON.stringify(body) : undefined });
  const data = await r.json();
  if (!r.ok) throw Object.assign(new Error(data.title), { problem: data });   // RFC 9457
  return data;
}

// 1. le besoin → métiers (à proposer à la personne)
const { data: matches } = await call("POST", "/trade-matches", { need: "Volet roulant bloqué", country: "FR", lang: "fr" });
// 2. brouillon, puis affichage de draft.recap et draft.consent.text dans l'application
const draft = await call("POST", "/requests", {
  trade_id: matches[0].trade.id, service: "Autre besoin", other_need: "Volet roulant bloqué en bas",
  delay: "Dès que possible", place_id: "fr-creteil-94000",
  contact: { name: "Camille Exemple", phone: "+33639980042", email: "camille.exemple@example.com" },
  reference: "resa-2026-0042" }, "resa-0042-draft-1");
// 3. après la case cochée par la personne
await call("POST", `/requests/${draft.id}/confirmation`,
  { method: "email", consent_text_version: draft.consent.version, consent_given: true }, "resa-0042-confirmation-1");

Python (bibliothèque standard)

import json, os, urllib.error, urllib.request

API = "https://kelki.ai/api/v1"

def call(method, path, body=None, idem=None):
    h = {"Authorization": f"Bearer {os.environ['KELKI_KEY']}", "Content-Type": "application/json"}
    if idem:
        h["Idempotency-Key"] = idem
    req = urllib.request.Request(API + path, method=method, headers=h,
                                 data=json.dumps(body).encode() if body is not None else None)
    try:
        with urllib.request.urlopen(req, timeout=15) as r:
            return json.load(r)
    except urllib.error.HTTPError as e:      # corps application/problem+json
        raise RuntimeError(json.load(e)) from None

trade = call("GET", "/trades/plombier?country=FR&lang=fr")
draft = call("POST", "/requests", {
    "trade_id": "plombier", "service": trade["services"][0], "delay": trade["delays"][0]["label"],
    "place_id": "fr-creteil-94000",
    "contact": {"name": "Camille Exemple", "phone": "+33639980042", "email": "camille.exemple@example.com"},
}, idem="resa-0042-draft-1")
# … montrer draft["recap"] et draft["consent"]["text"], case non cochée …
call("POST", f"/requests/{draft['id']}/confirmation",
     {"method": "email", "consent_text_version": draft["consent"]["version"], "consent_given": True},
     idem="resa-0042-confirmation-1")

Vérifier un webhook

JavaScript (Node) :

import crypto from "node:crypto";

function verify(rawBody, header, secret, toleranceS = 300) {
  const parts = Object.fromEntries(header.split(",").map(p => p.split("=")).map(([k, ...v]) => [k, v.join("=")]));
  const sigs = header.split(",").filter(p => p.startsWith("v1=")).map(p => p.slice(3));
  if (Math.abs(Date.now() / 1000 - Number(parts.t)) > toleranceS) return false;
  const expected = crypto.createHmac("sha256", secret).update(`${parts.t}.${rawBody}`).digest("hex");
  return sigs.some(s => s.length === expected.length && crypto.timingSafeEqual(Buffer.from(s), Buffer.from(expected)));
}

Python :

import hashlib, hmac, time

def verify_webhook(raw_body: bytes, header: str, secret: str, tolerance=300) -> bool:
    parts = [p.split("=", 1) for p in header.split(",")]
    t = next(v for k, v in parts if k == "t")
    if abs(time.time() - int(t)) > tolerance:
        return False
    expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return any(k == "v1" and hmac.compare_digest(v, expected) for k, v in parts)

Vérifiez la signature sur le corps brut, avant tout décodage JSON. Pendant un remplacement de secret, l'en-tête porte deux v1= : l'une des deux suffit.