> ## 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.

# Lovable 앱에 KYC 추가하기: Didit 연동 가이드

> Lovable 앱에 Didit KYC, 연령 확인, AML 스크리닝을 추가하세요. Supabase Edge Function 2개와 복사해서 쓸 수 있는 프롬프트로 구성하고, Lovable 채팅에서 Didit MCP를 사용할 수 있습니다.

Didit는 Lovable로 만든 앱에 신원 확인(KYC), 연령 확인, AML 스크리닝을 추가합니다. 서버 측 함수 두 개로 구현합니다. 하나는 Didit 인증 세션을 생성하고 인증 링크를 반환하며, 다른 하나는 Didit이 보내는 서명된 webhook을 받아 해당 사용자의 결과를 데이터베이스에 저장합니다.
Didit MCP 서버를 Lovable의 채팅에 연결할 수도 있습니다. 그러면 Lovable의 에이전트가 앱을 만드는 동안 Didit 계정에서 워크플로, 테스트 세션, webhook 대상을 생성할 수 있습니다.

이 페이지에서는 각 단계마다 Lovable에 붙여 넣을 프롬프트와 그 프롬프트로 생성되어야 하는 코드를 제공합니다. 이를 통해 Lovable이 작성한 코드를 직접 확인할 수 있습니다.

***

## 작동 방식

Didit API 키를 사용하는 모든 작업은 서버의 Supabase Edge Functions에서 실행됩니다(Lovable Cloud 또는 Supabase에 연결된 프로젝트의 백엔드).
브라우저는 키를 전혀 보지 않습니다.

1. 로그인한 사용자가 **내 신원 확인하기**를 클릭합니다. 프론트엔드가 `didit-create-session` 함수를 호출합니다.
2. 함수는 워크플로 ID, 사용자 ID를 담은 `vendor_data`, `callback` URL을 포함해 [`POST /v3/session/`](https://docs.didit.me/ko/sessions-api/create-session)을 호출하고, 세션의 `url`을 반환합니다. 사용자의 마지막 세션이 아직 완료되지 않았다면, 대신 그 세션의 링크를 반환합니다.
3. 프론트엔드는 사용자를 그 `url`로 이동시킵니다. Didit의 호스팅 인증 페이지가 워크플로의 검사를 실행한 다음, 사용자를 `callback` URL로 리디렉션합니다.
4. Didit는 `didit-webhook` 함수로 `status.updated` [webhook](https://docs.didit.me/ko/integration/webhooks.md)을 보냅니다. 함수는 서명을 검증하고, Didit에서 세션의 현재 결정을 가져온 다음, 상태(`Approved`, `Declined`, `In Review` 등)와 `environment`(`live` 또는 `sandbox`)을 `user_verifications` 테이블에 저장합니다. 그 후에만 `200`으로 응답합니다.
5. 앱은 자체 데이터베이스에서 상태를 읽습니다. 리디렉션 URL에 있는 상태는 절대 신뢰하지 않습니다.

***

## 시작하기 전에

**1. Didit 계정을 만들고 워크플로를 생성하세요**

[business.didit.me](https://business.didit.me)에서 가입합니다. **Workflows**에서 템플릿으로 워크플로를 만들고 **워크플로 ID**를 복사합니다. 워크플로는 사용자가 거치는 단계를 정합니다([확인 항목 선택](#확인-항목-선택) 참고).

**2. API 키를 복사하세요**

**Developers**, **API keys** 순서로 이동해 애플리케이션용 API 키를 복사합니다. 필요한 권한만 부여하려면 [API keys](https://docs.didit.me/ko/console/api-keys.md)를 참고하세요.

**3. Lovable 프로젝트에 사용자 및 백엔드를 준비하세요**

프로젝트에는 로그인 기능(각 사용자에게 ID가 있어야 함)과 Edge Functions를 실행하는 백엔드가 필요합니다. Lovable Cloud에서 둘 다 제공하며, 연결된 Supabase 프로젝트도 같은 방식으로 사용할 수 있습니다.

### 확인 항목 선택

확인 항목은 워크플로를 선택해서 정합니다. 이 페이지의 코드는 바뀌지 않으며, 워크플로 ID만 바뀝니다.

| 필요한 확인 | 워크플로 | 사용자가 하는 일 |
| - | - | - |
| 전체 KYC | [신분증 인증](https://docs.didit.me/ko/core-technology/id-verification/overview.md), [라이브니스 감지](https://docs.didit.me/ko/core-technology/liveness/overview.md), [얼굴 대조](https://docs.didit.me/ko/core-technology/face-match/overview.md)가 포함된 **KYC** 템플릿 | 신분증 문서를 스캔하고, 문서의 사진과 대조되는 실시간 셀피를 촬영합니다 |
| 연령 확인 | [연령 추정](https://docs.didit.me/ko/core-technology/age-estimation/overview.md)이 포함된 **Adaptive Age Verification** 템플릿 | 셀피를 촬영합니다. 연령 임계값에 가까운 사용자에게만 신분증 문서를 요청합니다 |
| AML이 포함된 KYC | [AML 스크리닝](https://docs.didit.me/ko/core-technology/aml-screening/overview.md)을 추가한 **KYC** 템플릿 | 전체 KYC와 같습니다. Didit은 해당 사람을 제재 목록, 정치적 주요 인물(PEP) 목록 및 부정적 언론 보도 목록과 대조해 스크리닝합니다 |

모든 템플릿과 기능은 [Workflows](https://docs.didit.me/ko/console/workflows.md)에서, 각 확인의 비용은 [요금](https://docs.didit.me/ko/getting-started/pricing.md)에서 확인하세요.

***

## 1부: Lovable 앱에 Didit 추가하기

### 1단계: 시크릿 저장하기

프로젝트의 시크릿으로 추가하세요. Lovable에서는 시크릿 추가를 요청하거나, 백엔드의 시크릿 설정에서 추가할 수 있습니다. 프런트엔드 코드나 `VITE_` 변수에는 절대 넣지 마세요. 프런트엔드에 있는 모든 값은 공개되기 때문입니다.

| 시크릿 | 값 |
| - | - |
| `DIDIT_API_KEY` | **Developers > API keys**에 있는 API 키입니다. 두 함수 모두 이 키를 사용합니다 |
| `DIDIT_WORKFLOW_ID` | **Workflows**에 있는 워크플로 ID입니다 |
| `DIDIT_WEBHOOK_SECRET` | webhook 대상의 서명 비밀 값입니다. [4단계](#4단계-didit에-webhook-등록하기)에서 생성합니다 |
| `APP_URL` | 앱의 공개 주소입니다. 예: `https://your-app.lovable.app` |

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.
```

### 2단계: 인증 세션 생성하기

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.
````

함수는 다음과 같아야 합니다:

```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 });
});
```

버튼은 다음과 같습니다:

```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();
```

완료 페이지는 webhook을 기다립니다. 사용자가 webhook보다 먼저 도착할 수 있기 때문입니다:

```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]
>
> 사용자의 추적 중인 세션이 아직 완료되지 않은 상태(`Not Started`, `In Progress`, `In Review`, `Resubmitted`)이면, 함수는 해당 세션의 링크를 반환하고 새 세션을 만들지 않습니다. 따라서 팀의 검토를 기다리는 사용자는 검토 중인 세션을 그대로 유지합니다. webhook이 아직 도착하지 않았을 수 있으므로, 함수는 Didit에서 상태를 직접 읽습니다. 새 세션은 `Declined`, `Abandoned`, `Expired`, `Kyc Expired` 또는 샌드박스 승인 이후에만 만들어지며, 라이브 승인 이후에는 `409`를 응답합니다. 사용자 인증(KYC) 워크플로의 경우 두 호출이 경합하면 Didit이 기존의 미완료 세션을 반환하므로, 더블 클릭으로 세션이 두 개 생기지 않습니다. 기업 확인(KYB) 워크플로는 호출할 때마다 새 세션을 만듭니다. 앱에서 **허용된 도메인**을 제한하고 있다면 `callback`이 그중 하나에 속해야 합니다. 자세한 내용은 [세션 생성](https://docs.didit.me/ko/sessions-api/create-session.md)을 참조하세요.

사용자를 앱 안에 머무르게 하고 싶으신가요? 리다이렉트하는 대신, 같은 `url`을 Didit의 [JavaScript SDK](https://docs.didit.me/ko/integration/web-sdks/javascript-sdk.md) 모달에서 여세요.

### 3단계: 결과 받기

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.
```

함수는 다음과 같아야 합니다. webhook 페이지의 [서명 검증](https://docs.didit.me/ko/integration/webhooks.md#서명-검증)을 따르며, `X-Signature`를 사용합니다. 이는 Didit이 보낸 정확한 바이트에 대한 HMAC입니다. `X-Signature-V2`는 코드가 본문을 보기 전에 프레임워크가 본문을 다시 인코딩하는 경우를 위한 것입니다. Edge Function은 `req.arrayBuffer()`로 변형되지 않은 바이트를 읽으므로, Didit 자체의 숫자 형식을 바이트 단위로 재현해야 하는 정규 JSON이 필요 없습니다.

```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]
>
> JWT 검증을 끄는 것은 이 함수에만 적합합니다. Didit은 Supabase 토큰을 보낼 수 없으므로, 요청이 Didit에서 왔다는 것을 증명하는 것은 HMAC 서명입니다. `didit-create-session`에는 JWT 검증을 계속 켜 두세요.

이 코드가 방어하는 상황은 다음과 같습니다:

* **늦게 도착하거나 반복된 전송.** Didit은 [전송 순서](https://docs.didit.me/ko/integration/webhooks.md#전송-순서)를 보장하지 않으며, 실패한 전송은 재시도합니다. 함수는 각 전송을 신호로 취급하고, webhook 페이지가 권장하는 대로 [`GET /v3/session/{session_id}/decision/`](https://docs.didit.me/ko/sessions-api/retrieve-session)에서 세션의 현재 결정을 저장합니다. 따라서 늦게 도착한 전송이 이전 상태를 되살리지 않습니다.
* **다른 세션.** 업데이트는 사용자의 추적 중인 `session_id`와 일치하는 행에만 적용되므로, 이전 세션의 결과가 사용자가 마지막으로 시작한 세션을 덮어쓰지 않습니다. 새 세션을 시작하면 행이 `Not Started`로 재설정됩니다.
* **재전송 공격.** `X-Timestamp` 자체는 서명되지 않으므로, 함수는 5분 시간 창을 적용하기 전에 서명된 본문의 `timestamp`가 이 값과 같은지도 요구합니다.
* **유실된 결정.** 함수는 결정이 저장된 후에만 `200`을 응답합니다. 저장에 실패하면 `500`을 응답하며, Didit은 약 5분에 걸쳐 두 번 [재시도](https://docs.didit.me/ko/integration/webhooks.md#재시도-정책)합니다. 그 후에는 대상의 **Deliveries** 탭에서 전송을 다시 보내세요.

전체 페이로드, 모든 상태 값, 그리고 다른 이벤트에 대해서는 [Webhooks](https://docs.didit.me/ko/integration/webhooks.md)를 참조하세요.

### 4단계: Didit에 webhook 등록하기

1. 비즈니스 콘솔에서 **Developers**, **Webhooks** 순서로 이동한 후, 대상을 추가하세요.
2. URL을 함수 주소로 설정하세요: `https://<your-project-ref>.supabase.co/functions/v1/didit-webhook`.
3. `status.updated`를 구독하세요.
4. 서명 비밀 값을 복사해 `DIDIT_WEBHOOK_SECRET` 시크릿에 넣으세요.
5. 대상에서 테스트 webhook을 보내세요. 함수가 `200`을 응답합니다. 테스트 전송에는 `X-Didit-Test-Webhook: true`가 포함되므로 함수는 아무것도 저장하지 않습니다.

[`POST /v3/webhook/destinations/`](https://docs.didit.me/ko/integration/webhooks)로 대상을 만들 수도 있고, Lovable의 에이전트에게 Didit MCP 서버([2부](#part-2-lovable-채팅에서-didit-사용하기))를 통해 만들어 달라고 요청할 수도 있습니다.

### 5단계: 전체 흐름 테스트하기

1. 개발하는 동안에는 [샌드박스 애플리케이션](https://docs.didit.me/ko/integration/sandbox-testing.md)을 사용하세요. 실제 검사에 요금이 청구되지 않습니다. 현재 시크릿의 값은 샌드박스 애플리케이션의 API 키, 워크플로 ID, webhook 대상의 서명 비밀 값입니다.
2. 앱에 로그인하고 **신원 확인하기**를 클릭한 후 호스팅 흐름을 완료하세요.
3. `/verification-complete` 페이지로 돌아오면, webhook이 도착하는 즉시 `Approved`, `Declined` 또는 `In Review`가 표시됩니다. `environment`가 `sandbox`이므로 테스트 결과라는 표시도 함께 나타납니다. `In Review` 세션은 팀이 콘솔에서 결정하면 다시 변경되며, webhook이 행을 다시 업데이트합니다. 그때까지 사용자에게는 인증이 검토 중인 것으로 표시됩니다.
4. 인증된 사용자가 필요한 기능은 `status = 'Approved'`**그리고** `environment = 'live'` 조건으로 제한하세요. 이 조건은 프런트엔드에서만이 아니라 서버에서 또는 행 수준 보안(RLS) 정책으로 확인해야 합니다. 샌드박스 승인으로는 이 기능들이 열리지 않습니다.

### 6단계: 라이브로 전환하기

샌드박스와 라이브는 별도의 애플리케이션이며, 각각 고유한 API 키, 워크플로, webhook 대상을 가집니다. 따라서 세 가지를 함께 전환하세요:

1. 라이브 애플리케이션에서 테스트한 워크플로를 게시하고 워크플로 ID를 복사하세요.
2. 라이브 애플리케이션의 API 키를 복사하세요.
3. 라이브 애플리케이션에 같은 `didit-webhook` URL로 webhook 대상을 추가하고, `status.updated`를 구독한 후 서명 비밀 값을 복사하세요.
4. `DIDIT_API_KEY`, `DIDIT_WORKFLOW_ID`, `DIDIT_WEBHOOK_SECRET`을 이 세 값으로 동시에 교체한 후, 두 함수를 모두 다시 배포하세요. 라이브 키로는 샌드박스 워크플로에서 세션을 열 수 없으며, 샌드박스 대상은 라이브 결정을 절대 받지 않습니다.
5. 샌드박스 결과를 지워서, `In Review` 상태로 남은 테스트 세션 때문에 사용자가 라이브 세션을 시작하지 못하는 일이 없도록 하세요:

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

각 사용자는 이후 실제 세션에서 한 번 더 인증해야 합니다. 샌드박스 승인은 인정되지 않으며, 새 세션은 `Not Started` 상태로 시작합니다.

***

## Part 2: Lovable 채팅에서 Didit 사용하기

Lovable의 에이전트는 커스텀 MCP 서버를 사용할 수 있습니다. 누가 서버를 추가할 수 있는지는 Lovable의 [Custom MCP servers](https://docs.lovable.dev/integrations/custom-mcp) 페이지를 참고하세요. 호스팅된 Didit MCP 서버를 추가하면 Lovable의 에이전트가 빌드하는 동안 Didit 계정을 읽고 변경할 수 있습니다. 예를 들어 워크플로 생성, webhook 대상 등록, 테스트 세션 시작이 가능합니다.

> [!NOTE]
>
> MCP 연결은 Lovable의 **채팅**에만 컨텍스트를 제공합니다. 게시된 앱의 일부가 아니며, 게시된 앱은 [1부](#1부-lovable-앱에-didit-추가하기)의 함수를 통해 Didit과 통신합니다.

1. Lovable에서 **Connectors**를 열고 **Add custom**을 선택한 다음 **MCP server**를 선택합니다. **MCP server**가 비활성화되어 있다면 워크스페이스 관리자가 **Custom MCP** 설정을 끈 것입니다.
2. **Server name:** `Didit`
3. **Server URL:** `https://mcp.didit.me/mcp`
4. 인증 옵션으로 **OAuth**를 유지하고 **Add & authorize**를 클릭합니다.
5. 열리는 창에서 **Log in with Didit**을 완료하고, Lovable이 사용할 수 있는 조직을 승인합니다.

이후 서버가 채팅 커넥터에 나타납니다. 이 연결은 개인별로 이루어지므로, 연결을 원하는 팀원은 각자 직접 연결해야 합니다.

> [!NOTE]
>
> **API 키가 필요하지 않습니다.** OAuth를 사용하면 서버는 로그인 시 승인한 조직에서, 사용자의 역할에 부여된 권한으로 사용자를 대신해 작동합니다. 대신 애플리케이션 API 키로 연결하려면 **Bearer token or API key**를 선택하고, 키를 붙여 넣은 다음 **Add server**를 클릭합니다. 서버는 해당 키를 Bearer 토큰으로 받아들입니다. 자세한 내용은 [인증](https://docs.didit.me/ko/integration/mcp/authentication.md)을 참고하세요.

### 작동 확인

Lovable 채팅에서 다음을 입력합니다.

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

그다음 실제로 작업을 맡겨 보세요.

* "샌드박스 KYC 워크플로를 만들어 줘. 신분증 인증, 라이브니스 감지, 얼굴 대조를 포함하고, 워크플로 ID를 알려 줘."
* "status.updated 이벤트에 대해 내 didit-webhook Edge Function을 가리키는 Didit webhook 대상을 등록해 줘. 서명 비밀 값을 어디서 찾을 수 있는지도 알려 줘."
* "내 사용자 ID로 테스트 세션을 만들고 인증 링크를 알려 줘."

Lovable은 읽기 전용 도구를 별도 확인 없이 실행합니다. 무언가를 변경하는 도구는 실행하기 전에 승인을 요청합니다.

### 문제 해결

* **로그인이 실패하거나 반복됩니다.** 같은 브라우저에서 먼저 [business.didit.me](https://business.didit.me)에 로그인한 다음 **Add & authorize**를 다시 클릭하세요.
* **도구가 `missing_scope`로 응답합니다.** 해당 조직에서 사용자의 역할에 권한이 없습니다. [역할 및 권한](https://docs.didit.me/ko/integration/mcp/authentication.md#역할과-권한)을 참고하세요.
* **webhook 함수가 `401`을 반환합니다.** `DIDIT_WEBHOOK_SECRET`이 webhook을 보내는 대상의 비밀 값과 같은지, 함수가 `verify_jwt = false`로 배포되었는지, 그리고 본문을 파싱하거나 다시 인코딩하기 전에 `req.arrayBuffer()`로 읽는지 확인하세요. 타임스탬프 검사에서 `401`이 발생하면 전달된 지 5분이 넘었거나 서버 시계가 맞지 않는 것입니다.
* **`didit-create-session`이 `409`를 반환합니다.** Didit이 해당 사용자의 추적 중인 세션을 라이브 환경에서 승인됨으로 보고했습니다. 페이지는 webhook이 업데이트하는 행을 다시 읽습니다.
* **`didit-create-session`이 `502`를 반환합니다.** Didit에 연결할 수 없거나, 완료되지 않은 세션에 이어서 진행할 링크가 없습니다. 새로 생성된 항목은 없으므로 다시 시도하세요.
* **세션 요청이 `callback`에서 `400`을 반환합니다.** 앱의 주소를 애플리케이션의 허용된 도메인에 추가하거나 `APP_URL`을 확인하세요.

***

## 다음 단계

> [card] [webhook](https://docs.didit.me/ko/integration/webhooks.md)
>
> 모든 이벤트, payload 필드, 서명 헤더를 확인하세요.

> [card] [세션 생성](https://docs.didit.me/ko/sessions-api/create-session.md)
>
> 예상 정보, 메타데이터 등 모든 요청 필드를 확인하세요.

> [card] [MCP 도구 레퍼런스](https://docs.didit.me/ko/integration/mcp/tools.md)
>
> Lovable 에이전트가 호출할 수 있는 모든 도구를 하나씩 확인하세요.

> [card] [요금](https://docs.didit.me/ko/getting-started/pricing.md)
>
> 워크플로의 각 검사에 드는 비용을 확인하세요.


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