> ## Documentation Index
> Fetch the complete documentation index at: https://docs.didit.me/llms.txt
> Use this file to discover all available pages before exploring further.

# KYC per app Lovable con Didit

> Aggiungi KYC con Didit a un'app Lovable: verifica dell'età, screening AML, due Edge Function Supabase e prompt pronti. Usa l'MCP di Didit in chat.

Didit aggiunge la verifica dell'identità (KYC), la verifica dell'età e lo Screening AML a un'app creata con Lovable tramite due funzioni lato server: una crea una sessione di verifica Didit e restituisce il suo link di verifica, l'altra riceve il webhook firmato di Didit e salva il risultato per quell'utente nel tuo database.
Puoi anche collegare il server MCP di Didit alla chat di Lovable, così l'agente di Lovable può creare workflow, sessioni di test e destinazioni webhook nel tuo account Didit mentre costruisce l'app.

Questa pagina ti offre un prompt da incollare in Lovable per ogni passaggio e il codice che quel prompt dovrebbe generare, così puoi verificare che cosa ha scritto Lovable.

***

## Come funziona

Tutto ciò che utilizza la tua chiave API di Didit viene eseguito sul server, nelle Supabase Edge Functions (il backend di un progetto Lovable Cloud o collegato a Supabase).
Il browser non vede mai la chiave.

1. Un utente autenticato fa clic su **Verifica la mia identità**. Il frontend chiama la funzione `didit-create-session`.
2. La funzione chiama [`POST /v3/session/`](https://docs.didit.me/it/sessions-api/create-session) con l'ID del tuo workflow, l'ID dell'utente come `vendor_data` e un URL `callback`, e restituisce l'`url` della sessione. Se l'ultima sessione dell'utente non è ancora completata, restituisce invece il link di quella sessione.
3. Il frontend invia l'utente a quell'`url`. La pagina ospitata da Didit esegue i controlli del tuo workflow, poi reindirizza l'utente all'URL `callback`.
4. Didit invia un [webhook](https://docs.didit.me/it/integration/webhooks.md) `status.updated` alla funzione `didit-webhook`. La funzione verifica la firma, legge dalla API di Didit la decisione attuale della sessione e salva nella tabella `user_verifications` il suo stato (`Approved`, `Declined`, `In Review` e così via) e il `environment` (`live` o `sandbox`). Solo dopo risponde con `200`.
5. La tua app legge lo stato dal proprio database. Non si fida mai dello stato presente nell'URL di reindirizzamento.

***

## Prima di iniziare

**1. Crea un account Didit e un workflow**

Registrati su [business.didit.me](https://business.didit.me). In **Workflows**, crea un workflow da un template e copia il suo **workflow ID**. Il workflow decide quali passaggi deve completare l'utente (vedi [Scegli cosa verificare](#scegli-cosa-verificare)).

**2. Copia una chiave API**

In **Developers**, poi **API keys**, copia una chiave API per l'applicazione. Consulta [Chiavi API](https://docs.didit.me/it/console/api-keys.md) per concederle solo l'accesso di cui ha bisogno.

**3. Disponi di utenti e di un backend nel tuo progetto Lovable**

Il tuo progetto richiede un sistema di accesso (così ogni utente ha un ID) e un backend che esegue Edge Functions. Lovable Cloud ti fornisce entrambi; un progetto Supabase collegato funziona allo stesso modo.

### Scegli cosa verificare

Scegli i controlli selezionando il workflow. Il codice di questa pagina non cambia; cambia solo il workflow ID.

| Ti serve | Workflow | Cosa fa l'utente |
| - | - | - |
| KYC completo | Template **KYC** con [verifica dell'identità](https://docs.didit.me/it/core-technology/id-verification/overview.md), [rilevamento della vitalità](https://docs.didit.me/it/core-technology/liveness/overview.md) e [confronto facciale](https://docs.didit.me/it/core-technology/face-match/overview.md) | Scansiona un documento d'identità e scatta un selfie in tempo reale, che viene confrontato con la foto del documento |
| Verifica dell'età | Template **Adaptive Age Verification** ([stima dell'età](https://docs.didit.me/it/core-technology/age-estimation/overview.md)) | Scatta un selfie; solo gli utenti vicini alla tua soglia d'età vengono invitati a presentare un documento d'identità |
| KYC con AML | Template **KYC** con [Screening AML](https://docs.didit.me/it/core-technology/aml-screening/overview.md) aggiunto | Come il KYC completo; Didit effettua inoltre uno screening della persona rispetto alle liste di sanzioni, PEP e notizie negative |

Consulta [Workflows](https://docs.didit.me/it/console/workflows.md) per ogni template e funzionalità, e [Prezzi](https://docs.didit.me/it/getting-started/pricing.md) per il costo di ciascun controllo.

***

## Parte 1: Aggiungi Didit alla tua app Lovable

### Passaggio 1: Memorizza i tuoi segreti

Aggiungili come segreti del tuo progetto (in Lovable, chiedi all'assistente di aggiungere un segreto, oppure aggiungili nelle impostazioni dei segreti del tuo backend). Non metterli mai nel codice frontend né in una variabile `VITE_`: tutto ciò che sta nel frontend è pubblico.

| Segreto | Valore |
| - | - |
| `DIDIT_API_KEY` | La chiave API da **Developers > API keys**. Entrambe le funzioni la usano |
| `DIDIT_WORKFLOW_ID` | L'ID del workflow da **Workflows** |
| `DIDIT_WEBHOOK_SECRET` | Il segreto di firma della tua destinazione webhook (la crei nel [Passaggio 4](#passaggio-4-registra-il-webhook-in-didit)) |
| `APP_URL` | L'indirizzo pubblico della tua app, per esempio `https://your-app.lovable.app` |

Incolla questo in Lovable:

```text theme={null}
Add four backend secrets to this project: DIDIT_API_KEY, DIDIT_WORKFLOW_ID, DIDIT_WEBHOOK_SECRET and APP_URL. Ask me for their values. They must only ever be read inside Edge Functions with Deno.env.get, never in frontend code.
```

### Passaggio 2: Crea la sessione di verifica

Incolla questo in Lovable:

````text theme={null}
Add identity verification with Didit.

1. Database: run this SQL migration exactly as written.

```sql
-- One row per user who started a verification. Users read their own row; only the two functions below write it.
create table public.user_verifications (
  user_id uuid primary key references auth.users (id) on delete cascade,
  session_id text not null,        -- the Didit session this user started last
  status text not null default 'Not Started',
  environment text,                -- 'live' or 'sandbox', as Didit reports it
  updated_at timestamptz not null default now()
);
alter table public.user_verifications enable row level security;
create policy "Users read their own verification" on public.user_verifications
  for select to authenticated using ((select auth.uid()) = user_id);
-- Data API access: the signed-in user reads their row, the Edge Functions write it with the service role.
grant select on public.user_verifications to authenticated;
grant select, insert, update on public.user_verifications to service_role;
```

2. Create a Supabase Edge Function named didit-create-session that:
   - handles CORS (including OPTIONS) so the frontend can call it with supabase.functions.invoke;
   - reads the signed-in user from the Authorization header with supabase.auth.getUser(); returns 401 if there is none;
   - reads the user's row with the service role key (returns 500 if that read fails);
   - when the row has a session_id, reads GET https://verification.didit.me/v3/session/{session_id}/decision/ with
     the header x-api-key: DIDIT_API_KEY, and decides from Didit's answer, not from the row:
     - status 'Approved' with environment 'live': returns 409 with { status, environment };
     - status 'Declined', 'Abandoned', 'Expired' or 'Kyc Expired', a sandbox 'Approved', or a 404: goes on to create
       a new session;
     - any other status (Not Started, In Progress, In Review, Resubmitted and so on): returns { "url": <its
       session_url> } and never creates a new session; returns 502 if it has no session_url;
     - any other error: returns 502;
   - to create a session, calls POST https://verification.didit.me/v3/session/ with the header x-api-key: DIDIT_API_KEY
     and the JSON body { "workflow_id": DIDIT_WORKFLOW_ID, "vendor_data": <the user's id>,
     "callback": APP_URL + "/verification-complete" };
   - upserts the user's row with the new session_id, status 'Not Started' and environment null; returns 500 without
     the link if that write fails;
   - returns { "url": <the url field of Didit's response> }. The field is called url, not verification_url.
   Never accept the user id from the request body, and never send DIDIT_API_KEY to the browser.

3. Frontend: on the account page, read the user's row from user_verifications. The user is verified only when
   status = 'Approved' AND environment = 'live'. When environment is 'sandbox', show the status labelled "Test result".
   When status is 'In Review', show "Your verification is being reviewed" and no button.
   Otherwise, if the user is not verified, show a "Verify my identity" button that calls didit-create-session and
   then does window.location.href = url. On a 409 answer, re-read the user's row and show its status.
   Add a /verification-complete page that says "Thanks, we're checking your verification" and re-reads the user's
   status and environment every 3 seconds until status is 'Approved', 'Declined' or 'In Review', for up to 2 minutes;
   if it is still pending after that, show a "Refresh" button. If a read fails, stop and show "Try again" (or
   "Sign in" when the user is signed out), not the pending message. Do not trust the status query parameter Didit
   adds to that URL.
````

La funzione dovrebbe avere questo aspetto:

```typescript supabase/functions/didit-create-session/index.ts theme={null}
import { createClient } from "npm:@supabase/supabase-js@2";

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};

// Sessions that allow a new attempt. A sandbox approval does too; a live approval does not.
const CAN_RETRY = ["Declined", "Abandoned", "Expired", "Kyc Expired"];

function json(body: unknown, status = 200) {
  return new Response(JSON.stringify(body), {
    status,
    headers: { ...corsHeaders, "Content-Type": "application/json" },
  });
}

Deno.serve(async (req) => {
  if (req.method === "OPTIONS") return new Response("ok", { headers: corsHeaders });

  // Who is asking: the signed-in user, from their own session token.
  const supabase = createClient(
    Deno.env.get("SUPABASE_URL")!,
    Deno.env.get("SUPABASE_ANON_KEY")!,
    { global: { headers: { Authorization: req.headers.get("Authorization") ?? "" } } },
  );
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) return json({ error: "Not signed in" }, 401);

  const admin = createClient(
    Deno.env.get("SUPABASE_URL")!,
    Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!,
  );
  const didit = { "x-api-key": Deno.env.get("DIDIT_API_KEY")!, "Content-Type": "application/json" };

  const { data: current, error: readError } = await admin
    .from("user_verifications")
    .select("session_id")
    .eq("user_id", user.id)
    .maybeSingle();
  if (readError) return json({ error: "Could not start verification" }, 500);

  // Ask Didit how the tracked session stands: its webhook may not have arrived yet.
  if (current) {
    const check = await fetch(
      `https://verification.didit.me/v3/session/${encodeURIComponent(current.session_id)}/decision/`,
      { headers: didit },
    );
    if (check.ok) {
      const tracked = await check.json();
      if (tracked.status === "Approved" && tracked.environment === "live") {
        return json({ error: "Already verified", status: tracked.status, environment: tracked.environment }, 409);
      }
      // Unfinished (Not Started, In Progress, In Review, Resubmitted): resume it, never start a second one.
      if (!CAN_RETRY.includes(tracked.status) && tracked.status !== "Approved") {
        return tracked.session_url
          ? json({ url: tracked.session_url })
          : json({ error: "Could not resume verification" }, 502);
      }
    } else if (check.status !== 404) {
      // 404: the session no longer exists, so a new one is fine. Anything else: do not guess.
      return json({ error: "Could not start verification" }, 502);
    }
  }

  const response = await fetch("https://verification.didit.me/v3/session/", {
    method: "POST",
    headers: didit,
    body: JSON.stringify({
      workflow_id: Deno.env.get("DIDIT_WORKFLOW_ID"),
      vendor_data: user.id,
      callback: `${Deno.env.get("APP_URL")}/verification-complete`,
    }),
  });
  const session = await response.json();
  if (!response.ok) {
    console.error("Didit session error", response.status, session);
    return json({ error: "Could not start verification" }, 502);
  }

  // Track the new session before handing out its link: the webhook saves results for this session only.
  const { error } = await admin.from("user_verifications").upsert({
    user_id: user.id,
    session_id: session.session_id,
    status: "Not Started",
    environment: null,
    updated_at: new Date().toISOString(),
  });
  if (error) return json({ error: "Could not start verification" }, 500);

  return json({ url: session.url });
});
```

Il pulsante:

```typescript theme={null}
const { data, error } = await supabase.functions.invoke("didit-create-session");
if (data?.url) window.location.href = data.url;
else if (error?.context?.status === 409) await loadVerification(); // Re-read the user's row and show its status.
else showError();
```

La pagina di completamento attende il webhook, perché l'utente potrebbe arrivarci prima che il webhook sia stato ricevuto:

```typescript theme={null}
// Re-read the user's own row every 3 seconds, for up to 2 minutes.
const SETTLED = ["Approved", "Declined", "In Review"];
type Decision = { status: string; environment: string | null };
async function waitForDecision(userId: string): Promise<Decision | "pending" | "error"> {
  for (let attempt = 0; attempt < 40; attempt++) {
    const { data, error } = await supabase
      .from("user_verifications")
      .select("status, environment")
      .eq("user_id", userId)
      .maybeSingle();
    // A failed read is not a pending decision: show "Try again", or "Sign in" when the user is signed out.
    if (error) return "error";
    // environment 'sandbox' is labelled "Test result".
    if (data && SETTLED.includes(data.status)) return data;
    await new Promise((resolve) => setTimeout(resolve, 3000));
  }
  return "pending"; // Still pending: show a Refresh button.
}
```

> [!NOTE]
>
> Finché la sessione tracciata dell'utente non è conclusa (`Not Started`, `In Progress`, `In Review`, `Resubmitted`), la funzione restituisce il link di quella sessione e non ne crea una nuova, così un utente in attesa della revisione del tuo team resta sulla sessione in revisione. Legge lo stato da Didit, perché il webhook potrebbe non essere ancora arrivato. Crea una nuova sessione solo dopo `Declined`, `Abandoned`, `Expired`, `Kyc Expired` o un'approvazione in sandbox, e risponde `409` dopo un'approvazione in produzione. Per un workflow di Verifica degli utenti (KYC), Didit restituisce anche la sessione non conclusa esistente quando due chiamate arrivano in contemporanea, così un doppio clic non crea due sessioni; un workflow di Verifica aziendale (KYB) crea una nuova sessione a ogni chiamata. Se la tua applicazione limita i **domini consentiti**, il `callback` deve trovarsi in uno di essi. Vedi [Crea sessione](https://docs.didit.me/it/sessions-api/create-session.md).

Preferisci mantenere l'utente all'interno della tua app? Apri lo stesso `url` nella modale dell'[SDK JavaScript di Didit](https://docs.didit.me/it/integration/web-sdks/javascript-sdk.md) invece di reindirizzare.

### Passaggio 3: Ricevi il risultato

Incolla questo in Lovable:

```text theme={null}
Create a Supabase Edge Function named didit-webhook that receives Didit webhooks. It is called by Didit, not by a
signed-in user, so deploy it without JWT verification (verify_jwt = false for this function in supabase/config.toml).

For each POST request:
1. Read the body as raw bytes with req.arrayBuffer(). Do not call req.json() and do not re-serialize the body
   before the signature check. Parse it with JSON.parse only to read its fields.
2. Signature: compute HMAC-SHA256 with DIDIT_WEBHOOK_SECRET, hex encoded, over the raw bytes, and compare it in
   constant time (timingSafeEqual from node:crypto, on TextEncoder bytes; Deno has no global Buffer) with the
   X-Signature header and, when present, X-Signature-Previous. Return 401 if neither matches. Parse the body only
   after this check.
3. Timestamp: return 401 unless X-Timestamp is an integer, the body's timestamp field equals it, and
   abs(now_in_seconds - X-Timestamp) <= 300.
4. Return 200 without writing anything when the header X-Didit-Test-Webhook is "true" or webhook_type is not
   "status.updated", or when vendor_data is not a user id (a UUID).
5. Do not save the status from the body: deliveries can arrive late or out of order. Read the session's current
   decision with GET https://verification.didit.me/v3/session/{session_id}/decision/ and the header
   x-api-key: DIDIT_API_KEY. Return 200 on a 404 (the session no longer exists) and 500 on any other error.
6. With the service role key, update user_verifications set status and environment from that decision, and
   updated_at = now(), where user_id = vendor_data from the body and session_id = session_id from the body.
   No ordering logic: the decision Didit returns is the current one.
7. Return 200 only after the update succeeds. If it fails, return 500 so Didit retries the delivery.
```

La funzione dovrebbe avere questo aspetto. Segue la [verifica della firma](https://docs.didit.me/it/integration/webhooks.md#verifica-della-firma) della pagina Webhooks con `X-Signature`, cioè l'HMAC dei byte esatti inviati da Didit. `X-Signature-V2` esiste per i framework che ricodificano il corpo della richiesta prima che il tuo codice lo veda; una Edge Function legge i byte non modificati con `req.arrayBuffer()`, quindi non richiede un JSON canonico, che dovrebbe riprodurre byte per byte la formattazione dei numeri di Didit.

```typescript supabase/functions/didit-webhook/index.ts theme={null}
import { createHmac, timingSafeEqual } from "node:crypto";
import { createClient } from "npm:@supabase/supabase-js@2";

const SECRET = Deno.env.get("DIDIT_WEBHOOK_SECRET")!;
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const encoder = new TextEncoder();

// Constant-time comparison of two hex digests, as bytes.
function sameDigest(expected: string, received: string | null): boolean {
  if (!received) return false;
  const a = encoder.encode(expected);
  const b = encoder.encode(received);
  return a.length === b.length && timingSafeEqual(a, b);
}

const ok = () => Response.json({ ok: true });
const reject = (message: string) => new Response(message, { status: 401 });
const retry = (message: string) => new Response(message, { status: 500 });

Deno.serve(async (req) => {
  if (req.method !== "POST") return new Response("Method not allowed", { status: 405 });

  // 1. The exact bytes Didit sent.
  const raw = new Uint8Array(await req.arrayBuffer());

  // 2. Signature over those bytes. X-Signature-Previous is sent for 24 hours after you rotate the signing secret.
  const digest = createHmac("sha256", SECRET).update(raw).digest("hex");
  if (
    !sameDigest(digest, req.headers.get("X-Signature")) &&
    !sameDigest(digest, req.headers.get("X-Signature-Previous"))
  ) {
    return reject("Invalid signature");
  }
  const body = JSON.parse(new TextDecoder().decode(raw));

  // 3. Freshness, from the signed body: its timestamp must match X-Timestamp and be under 5 minutes old.
  const timestamp = Number(req.headers.get("X-Timestamp"));
  if (
    !Number.isInteger(timestamp) ||
    body.timestamp !== timestamp ||
    Math.abs(Date.now() / 1000 - timestamp) > 300
  ) {
    return reject("Stale or mismatched timestamp");
  }

  // 4. Test deliveries carry sample data, and this app stores session results only.
  if (req.headers.get("X-Didit-Test-Webhook") === "true") return ok();
  if (body.webhook_type !== "status.updated") return ok();
  if (!UUID.test(String(body.vendor_data ?? ""))) {
    console.warn("status.updated without an app user id", body.session_id);
    return ok();
  }

  // 5. Didit is the source of truth: read the session's current decision, not the event's status.
  const check = await fetch(
    `https://verification.didit.me/v3/session/${encodeURIComponent(body.session_id)}/decision/`,
    { headers: { "x-api-key": Deno.env.get("DIDIT_API_KEY")! } },
  );
  if (check.status === 404) return ok();
  if (!check.ok) return retry("Could not read the decision");
  const decision = await check.json();

  // 6. Save it on the user's row, only for the session the user started last.
  const admin = createClient(
    Deno.env.get("SUPABASE_URL")!,
    Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!,
  );
  const { error } = await admin
    .from("user_verifications")
    .update({ status: decision.status, environment: decision.environment, updated_at: new Date().toISOString() })
    .eq("user_id", body.vendor_data)
    .eq("session_id", body.session_id);

  // 7. Acknowledge only what is saved: a 500 makes Didit retry the delivery.
  if (error) {
    console.error("Could not save the Didit decision", body.event_id, error);
    return retry("Could not save");
  }
  return ok();
});
```

```toml supabase/config.toml theme={null}
[functions.didit-webhook]
verify_jwt = false
```

> [!WARNING]
>
> Disattivare la verifica JWT è corretto solo per questa funzione: Didit non può inviare un token di Supabase, quindi è la firma HMAC a dimostrare che la richiesta proviene da Didit. Mantieni attiva la verifica JWT per `didit-create-session`.

Cosa protegge il codice:

* **Consegne in ritardo o ripetute.** Didit non garantisce l'[ordine delle consegne](https://docs.didit.me/it/integration/webhooks.md#ordine-di-consegna) e ritenta una consegna non riuscita. La funzione tratta ogni consegna come un segnale e salva la decisione corrente della sessione recuperandola da [`GET /v3/session/{session_id}/decision/`](https://docs.didit.me/it/sessions-api/retrieve-session), come consiglia la pagina Webhooks, così una consegna in ritardo non riporta lo stato che conteneva.
* **Altre sessioni.** L'aggiornamento corrisponde al `session_id` tracciato dell'utente, quindi il risultato di una sessione precedente non sostituisce quella che l'utente ha avviato per ultima. Avviare una nuova sessione riporta la riga a `Not Started`.
* **Replay.** `X-Timestamp` non è firmato di per sé, quindi la funzione richiede anche che il `timestamp` del body firmato sia uguale ad esso prima di applicare la finestra di 5 minuti.
* **Decisioni perse.** La funzione risponde `200` solo dopo che la decisione è stata salvata. Se il salvataggio non riesce, la funzione risponde `500`, e Didit [ritenta](https://docs.didit.me/it/integration/webhooks.md#politica-dei-nuovi-tentativi) due volte in circa cinque minuti; dopo di che, rinvia la consegna dalla scheda **Deliveries** della destinazione.

Per il payload completo, ogni valore di stato e gli altri eventi, vedi [Webhooks](https://docs.didit.me/it/integration/webhooks.md).

### Passaggio 4: Registra il webhook in Didit

1. Nella Business Console, vai su **Developers**, poi **Webhooks**, e aggiungi una destinazione.
2. Imposta il suo URL sulla tua funzione: `https://<your-project-ref>.supabase.co/functions/v1/didit-webhook`.
3. Iscrivila a `status.updated`.
4. Copia il suo segreto di firma nel segreto `DIDIT_WEBHOOK_SECRET`.
5. Invia un webhook di test dalla destinazione. La funzione risponde `200` e, poiché le consegne di test includono `X-Didit-Test-Webhook: true`, non scrive nulla.

Puoi anche creare la destinazione con [`POST /v3/webhook/destinations/`](https://docs.didit.me/it/integration/webhooks), oppure chiedere all'agente di Lovable di farlo tramite il server MCP di Didit ([Parte 2](#parte-2-usa-didit-nella-chat-di-lovable)).

### Passaggio 5: Testa dall'inizio alla fine

1. Usa un'[applicazione sandbox](https://docs.didit.me/it/integration/sandbox-testing.md) mentre sviluppi, così non viene addebitato nessun controllo reale. Per ora, la sua chiave API, l'ID del workflow e il segreto della destinazione webhook sono i valori dei tuoi segreti.
2. Accedi alla tua app, clicca su **Verifica la mia identità** e completa il flusso ospitato.
3. Tornando su `/verification-complete`, la pagina mostra `Approved`, `Declined` o `In Review` appena il webhook è arrivato, etichettato come risultato di test perché il suo `environment` è `sandbox`. Una sessione in `In Review` cambia di nuovo quando il tuo team prende una decisione al riguardo nella console, e il webhook aggiorna di nuovo la riga; fino ad allora, l'utente vede che la sua verifica è in revisione.
4. Limita le funzionalità che richiedono un utente verificato a `status = 'Approved'` **e** `environment = 'live'`, leggendo il dato sul server o tramite una policy di sicurezza a livello di riga, non solo nel frontend. Un'approvazione in sandbox non sblocca mai queste funzionalità.

### Passaggio 6: Vai in produzione

Sandbox e produzione sono applicazioni separate, ciascuna con la propria chiave API, i propri workflow e le proprie destinazioni webhook, quindi cambia tutti e tre insieme:

1. Nella tua applicazione di produzione, pubblica il workflow testato e copia il suo ID.
2. Copia una chiave API dell'applicazione di produzione.
3. Aggiungi una destinazione webhook nell'applicazione di produzione con lo stesso URL della funzione `didit-webhook`, iscritta a `status.updated`, e copia il suo segreto di firma.
4. Sostituisci `DIDIT_API_KEY`, `DIDIT_WORKFLOW_ID` e `DIDIT_WEBHOOK_SECRET` con questi tre valori nello stesso momento, e ridistribuisci entrambe le funzioni. Una chiave di produzione non può aprire una sessione su un workflow sandbox, e una destinazione sandbox non riceve mai decisioni di produzione.
5. Cancella i risultati sandbox, così una sessione di test lasciata `In Review` non impedisce al suo utente di avviarne una in produzione:

   ```sql theme={null}
   delete from public.user_verifications where environment = 'sandbox';
   ```

Ogni utente si verifica quindi di nuovo in una sessione in produzione: un'approvazione in sandbox non vale, e la nuova sessione parte dallo stato `Not Started`.

***

## Parte 2: Usa Didit nella chat di Lovable

L'agente di Lovable può usare server MCP personalizzati; per sapere chi può aggiungerne uno, consulta la pagina di Lovable [Server MCP personalizzati](https://docs.lovable.dev/integrations/custom-mcp). Aggiungi il server MCP ospitato di Didit e l'agente di Lovable può leggere e modificare il tuo account Didit mentre costruisci l'app: creare il workflow, registrare la destinazione webhook, avviare una sessione di test.

> [!NOTE]
>
> Una connessione MCP fornisce contesto solo alla **chat** di Lovable. Non fa mai parte dell'app pubblicata, che comunica con Didit tramite le funzioni descritte in [Parte 1](#parte-1-aggiungi-didit-alla-tua-app-lovable).

1. In Lovable, apri **Connectors**, seleziona **Add custom** e scegli **MCP server**. Se **MCP server** è in grigio, un amministratore dello spazio di lavoro ha disattivato l'impostazione **Custom MCP**.
2. **Server name:** `Didit`.
3. **Server URL:** `https://mcp.didit.me/mcp`.
4. Lascia **OAuth** come opzione di autenticazione e fai clic su **Add & authorize**.
5. Completa **Log in with Didit** nella finestra che si apre e approva le organizzazioni che Lovable può usare.

Il server compare poi tra i connettori della chat. La connessione è personale: ogni membro del team che la vuole la configura per conto proprio.

> [!NOTE]
>
> **Non serve alcuna chiave API.** Con OAuth il server agisce per tuo conto, nelle organizzazioni che approvi al momento dell'accesso, con le autorizzazioni del tuo ruolo. Per connetterti con una chiave API dell'applicazione, scegli **Bearer token or API key**, incolla la chiave e fai clic su **Add server**: il server la accetta come bearer token. Consulta [Autenticazione](https://docs.didit.me/it/integration/mcp/authentication.md).

### Verifica che funzioni

In una chat di Lovable, chiedi:

```text theme={null}
Use the Didit MCP server to call didit_context_get and list my organizations and applications.
```

Poi mettilo alla prova:

* "Crea un workflow KYC in sandbox con verifica dell'identità, rilevamento della vitalità e confronto facciale, e dammi l'ID del workflow."
* "Registra una destinazione webhook di Didit per status.updated che punti alla mia Edge Function didit-webhook, e dimmi dove trovare il suo segreto di firma."
* "Crea una sessione di test per il mio ID utente e dammi il link di verifica."

Lovable esegue senza chiedere conferma gli strumenti in sola lettura e chiede la tua approvazione prima di qualsiasi strumento che modifichi qualcosa.

### Risoluzione dei problemi

* **L'accesso non riesce o entra in un ciclo.** Prima accedi a [business.didit.me](https://business.didit.me) nello stesso browser, poi fai di nuovo clic su **Add & authorize**.
* **Uno strumento risponde con `missing_scope`.** Il tuo ruolo in quell'organizzazione non ha l'autorizzazione necessaria. Consulta [ruoli e autorizzazioni](https://docs.didit.me/it/integration/mcp/authentication.md#ruoli-e-autorizzazioni).
* **La funzione webhook restituisce `401`.** Verifica che `DIDIT_WEBHOOK_SECRET` sia il segreto della destinazione che invia il webhook, che la funzione sia distribuita con `verify_jwt = false`, e che legga il corpo con `req.arrayBuffer()` prima che venga analizzato o ricodificato. Un `401` sul controllo del timestamp significa che la consegna ha più di cinque minuti, oppure che l'orologio del server non è corretto.
* **`didit-create-session` restituisce `409`.** Didit segnala che la sessione tracciata dell'utente risulta approvata nell'ambiente di produzione. La pagina rilegge la riga, che il webhook aggiorna.
* **`didit-create-session` restituisce `502`.** Didit non è raggiungibile, oppure una sessione non completata non ha un link per riprenderla. Non viene creato nulla di nuovo; riprova.
* **La richiesta di sessione restituisce `400` su `callback`.** Aggiungi l'indirizzo della tua app ai domini consentiti dell'applicazione, oppure controlla `APP_URL`.

***

## Prossimi passi

> [card] [Webhook](https://docs.didit.me/it/integration/webhooks.md)
>
> Ogni evento, campo del payload e intestazione della firma.

> [card] [Crea una sessione](https://docs.didit.me/it/sessions-api/create-session.md)
>
> Tutti i campi della richiesta, come i dettagli previsti e i metadati.

> [card] [Riferimento agli strumenti MCP](https://docs.didit.me/it/integration/mcp/tools.md)
>
> Tutto ciò che l'agente di Lovable può chiamare, strumento per strumento.

> [card] [Prezzi](https://docs.didit.me/it/getting-started/pricing.md)
>
> Quanto costa ogni controllo nel tuo workflow.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.