> ## 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 إلى تطبيق Lovable باستخدام Didit

> أضف Didit للتحقق KYC أو تحقق العمر أو فحص AML إلى تطبيق Lovable عبر دالتين Supabase Edge Function ومطالبات جاهزة، واستخدم Didit MCP في Lovable.

يضيف Didit التحقق من الهوية (KYC) والتحقق من العمر وفحص AML إلى تطبيق مبني في Lovable، وذلك بدالتين من جهة الخادم: الأولى تنشئ جلسة تحقق في Didit وتعيد رابطها، والثانية تستقبل webhook الموقّع من Didit وتحفظ النتيجة الخاصة بذلك المستخدم في قاعدة بياناتك.
يمكنك أيضاً ربط خادم Didit MCP بدردشة Lovable، فيتمكن وكيل Lovable من إنشاء سير العمل وجلسات الاختبار ووجهات webhook في حساب Didit الخاص بك أثناء بناء التطبيق.

تقدّم هذه الصفحة أمراً تنسخه في Lovable لكل خطوة، والكود الذي ينبغي أن ينتجه ذلك الأمر، حتى تتمكن من مراجعة ما كتبه Lovable.

***

## كيف يعمل

تُنفَّذ جميع العمليات التي تمسّ مفتاح Didit API الخاص بك على الخادم، في Supabase Edge Functions (الخلفية الخاصة بمشروع Lovable Cloud أو بمشروع متصل بـ Supabase).
لا يرى المتصفح المفتاح أبداً.

1. يضغط المستخدم الذي سجّل دخوله على **تحقّق من هويتي**. تستدعي الواجهة الأمامية الدالة `didit-create-session`.
2. تستدعي الدالة [`POST /v3/session/`](https://docs.didit.me/ar/sessions-api/create-session) مع معرّف سير العمل الخاص بك، ومعرّف المستخدم بوصفه `vendor_data`، ورابط الاستدعاء `callback`، ثم تعيد الرابط `url` الخاص بالجلسة. وإذا كانت الجلسة الأخيرة للمستخدم لم تكتمل بعد، تعيد الدالة رابط تلك الجلسة بدلاً من ذلك.
3. توجّه الواجهة الأمامية المستخدم إلى عنوان `url` هذا. تنفّذ صفحة Didit المستضافة فحوصات سير العمل الخاص بك، ثم تعيد توجيه المستخدم إلى رابط الاستدعاء `callback`.
4. يُرسل Didit [webhook](https://docs.didit.me/ar/integration/webhooks.md) من نوع `status.updated` إلى الدالة `didit-webhook`. تتحقق الدالة من التوقيع، وتقرأ قرار الجلسة الحالي من Didit، ثم تحفظ حالة الجلسة (`Approved` و`Declined` و`In Review` وغيرها) والقيمة `environment` (`live` أو `sandbox`) في جدول `user_verifications` لديك، ولا تردّ بالرمز `200` إلا بعد ذلك.
5. يقرأ تطبيقك الحالة من قاعدة بياناته الخاصة. ولا يثق أبداً بالحالة الواردة في عنوان إعادة التوجيه.

***

## قبل أن تبدأ

**1. إنشاء حساب Didit وسير عمل**

سجّل في [business.didit.me](https://business.didit.me). ضمن **Workflows**، أنشئ سير عمل من قالب، وانسخ **workflow ID** الخاص به. يحدد سير العمل ما يمر به المستخدم (راجع [اختر ما تريد التحقق منه](#اختر-ما-تريد-التحقق-منه)).

**2. نسخ مفتاح API**

ضمن **Developers**، ثم **API keys**، انسخ مفتاح API للتطبيق. راجع [مفاتيح API](https://docs.didit.me/ar/console/api-keys.md) لمنح المفتاح الصلاحيات التي يحتاجها فقط.

**3. وجود مستخدمين وخلفية في مشروع Lovable**

يحتاج مشروعك إلى تسجيل دخول (ليكون لكل مستخدم معرّف) وخلفية تشغّل Edge Functions. توفر لك Lovable Cloud الأمرين معًا، ويعمل مشروع Supabase متصل بالطريقة نفسها.

### اختر ما تريد التحقق منه

تحدد الفحوصات بحسب سير العمل الذي تختاره. لا يتغير الكود في هذه الصفحة؛ الذي يتغير هو معرّف سير العمل فقط.

| ما تحتاجه | سير العمل | ما يفعله المستخدم |
| - | - | - |
| KYC كامل | قالب **KYC** مع [التحقق من الهوية](https://docs.didit.me/ar/core-technology/id-verification/overview.md) و[كشف الحيوية](https://docs.didit.me/ar/core-technology/liveness/overview.md) و[مطابقة الوجه](https://docs.didit.me/ar/core-technology/face-match/overview.md) | يمسح مستند هوية، ويلتقط صورة سيلفي حية تُطابَق مع صورة المستند |
| التحقق من العمر | قالب **Adaptive Age Verification** ([تقدير العمر](https://docs.didit.me/ar/core-technology/age-estimation/overview.md)) | يلتقط صورة سيلفي؛ ولا يُطلب مستند الهوية إلا من المستخدمين القريبين من حد العمر الذي تحدده |
| KYC مع AML | قالب **KYC** مع إضافة [فحص AML](https://docs.didit.me/ar/core-technology/aml-screening/overview.md) | مثل KYC الكامل، ويفحص Didit الشخص أيضًا مقابل قوائم العقوبات وشخص معرض سياسياً (PEP) والأخبار السلبية |

راجع [سير العمل](https://docs.didit.me/ar/console/workflows.md) لكل القوالب والميزات، و[الأسعار](https://docs.didit.me/ar/getting-started/pricing.md) لمعرفة تكلفة كل فحص.

***

## الجزء 1: أضِف Didit إلى تطبيق Lovable

### الخطوة 1: احفظ أسرارك

أضفها كأسرار في مشروعك. في Lovable، اطلب منه إضافة سر، أو أضفه في إعدادات الأسرار في الخلفية. لا تضعها أبدًا في كود الواجهة الأمامية أو في متغير يبدأ بـ `VITE_`، لأن كل ما في الواجهة الأمامية مكشوف للجميع.

| السر | القيمة |
| - | - |
| `DIDIT_API_KEY` | مفتاح API من **Developers > API keys**. تستخدمه الدالتان كلتاهما |
| `DIDIT_WORKFLOW_ID` | معرّف سير العمل من **Workflows** |
| `DIDIT_WEBHOOK_SECRET` | سر التوقيع الخاص بوجهة webhook الخاصة بك (تنشئها في [الخطوة 4](#الخطوة-4-سجّل-الـ-webhook-في-didit)) |
| `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، لأن المستخدم قد يصل إليها قبل وصوله:

```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`)، تعيد الدالة رابط تلك الجلسة ولا تنشئ جلسة جديدة، فيبقى المستخدم الذي ينتظر مراجعة فريقك على الجلسة قيد المراجعة. تقرأ الدالة الحالة من Didit، لأن الـ webhook قد لا يكون قد وصل بعد. تنشئ جلسة جديدة فقط بعد `Declined` أو `Abandoned` أو `Expired` أو `Kyc Expired` أو موافقة في البيئة التجريبية، وتجيب بالرمز `409` بعد موافقة في بيئة الإنتاج. بالنسبة إلى سير عمل التحقق من المستخدمين (KYC)، يعيد Didit أيضًا الجلسة غير المكتملة الموجودة عند حدوث استدعاءين متزامنين، فلا يؤدي النقر المزدوج إلى إنشاء جلستين. أما سير عمل التحقق من الشركات (KYB) فينشئ جلسة جديدة مع كل استدعاء. إذا كان تطبيقك يقيّد **allowed domains**، فيجب أن يكون `callback` على أحدها. راجع [إنشاء جلسة](https://docs.didit.me/ar/sessions-api/create-session.md).

هل تفضّل إبقاء المستخدم داخل تطبيقك؟ افتح الـ `url` نفسه في النافذة المنبثقة (modal) من [JavaScript SDK](https://docs.didit.me/ar/integration/web-sdks/javascript-sdk.md) الخاص بـ Didit بدلًا من إعادة التوجيه.

### الخطوة 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.
```

ستبدو الدالة هكذا. وهي تتبع [التحقق من التوقيع](https://docs.didit.me/ar/integration/webhooks.md#التحقق-من-التوقيع) في صفحة Webhooks باستخدام `X-Signature`، أي HMAC للبايتات الدقيقة التي أرسلها Didit. يوجد `X-Signature-V2` للأطر التي تعيد ترميز الجسم قبل أن يصل إلى كودك. أما Edge Function فتقرأ البايتات كما هي عبر `req.arrayBuffer()`، لذا لا تحتاج إلى JSON بصيغة قياسية، لأن ذلك يتطلب إعادة إنتاج تنسيق الأرقام الخاص بـ 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]
>
> إيقاف التحقق من JWT صحيح لهذه الدالة فقط: لا يستطيع Didit إرسال رمز Supabase، لذا فإن توقيع HMAC هو ما يثبت أن الطلب صادر من Didit. أبقِ التحقق من JWT مفعّلًا للدالة `didit-create-session`.

ما الذي يحمي منه الكود:

* **التسليمات المتأخرة أو المكررة.** لا يضمن Didit [ترتيب التسليم](https://docs.didit.me/ar/integration/webhooks.md#ترتيب-التسليم)، ويعيد محاولة التسليم الفاشل. تعامل الدالة كل تسليم كإشارة، وتحفظ القرار الحالي للجلسة من [`GET /v3/session/{session_id}/decision/`](https://docs.didit.me/ar/sessions-api/retrieve-session)، كما توصي صفحة Webhooks، فلا يعيد التسليم المتأخر الحالة التي كان يحملها.
* **الجلسات الأخرى.** يطابق التحديث `session_id` المتعقَّب للمستخدم، فلا تحل نتيجة جلسة سابقة محل الجلسة التي بدأها المستخدم أخيرًا. وبدء جلسة جديدة يعيد الصف إلى `Not Started`.
* **هجمات إعادة التشغيل.** لا يُوقَّع `X-Timestamp` بذاته، لذا تشترط الدالة أيضًا أن يساوي `timestamp` في الجسم الموقَّع هذه القيمة، قبل أن تطبّق نافذة الـ 5 دقائق.
* **القرارات المفقودة.** تجيب الدالة بالرمز `200` فقط بعد حفظ القرار. يعيد الحفظ الفاشل الرمز `500`، ويعيد Didit [المحاولة](https://docs.didit.me/ar/integration/webhooks.md#سياسة-إعادة-المحاولة) مرتين خلال نحو 5 دقائق. بعد ذلك، أعد إرسال التسليم من تبويب **Deliveries** في الوجهة.

للاطلاع على الحمولة الكاملة، وكل قيم الحالة والأحداث الأخرى، راجع [Webhooks](https://docs.didit.me/ar/integration/webhooks.md).

### الخطوة 4: سجّل الـ webhook في Didit

1. في Business Console، انتقل إلى **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/ar/integration/webhooks)، أو أن تطلب من وكيل Lovable فعل ذلك عبر خادم Didit MCP ([الجزء 2](#الجزء-2-استخدام-didit-في-دردشة-lovable)).

### الخطوة 5: اختبر من البداية إلى النهاية

1. استخدم [تطبيق البيئة التجريبية](https://docs.didit.me/ar/integration/sandbox-testing.md) أثناء البناء، حتى لا تُحتسب أي فحوص حقيقية. مفتاح API الخاص به ومعرّف سير العمل وسر وجهة webhook هي قيم أسرارك في الوقت الحالي.
2. سجّل الدخول إلى تطبيقك، وانقر **Verify my identity**، ثم أكمل التدفق المستضاف.
3. عند عودتك إلى `/verification-complete`، تعرض الصفحة `Approved` أو `Declined` أو `In Review` بمجرد وصول الـ webhook، مع وسم النتيجة بأنها نتيجة اختبار لأن `environment` فيها هو `sandbox`. تتغير الجلسة في حالة `In Review` مرة أخرى عندما يتخذ فريقك القرار في Business Console، ويحدّث الـ webhook الصف مرة أخرى. وحتى ذلك الحين، يرى المستخدم أن التحقق من هويته قيد المراجعة.
4. قيّد الوصول إلى الميزات التي تحتاج مستخدمًا موثَّقًا بالشرط `status = 'Approved'` **و** `environment = 'live'`، واقرأه على الخادم أو عبر سياسة أمان على مستوى الصف، لا في الواجهة الأمامية وحدها. لا تفتح موافقة البيئة التجريبية هذه الميزات أبدًا.

### الخطوة 6: انتقل إلى بيئة الإنتاج

التطبيق التجريبي وتطبيق الإنتاج منفصلان، ولكل منهما مفتاح API وسير عمل ووجهات webhook خاصة بها، لذا بدّل الثلاثة معًا:

1. في تطبيق الإنتاج، انشر سير العمل الذي اختبرته وانسخ معرّفه.
2. انسخ مفتاح API من تطبيق الإنتاج.
3. أضف وجهة webhook في تطبيق الإنتاج بعنوان `didit-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`.

***

## الجزء 2: استخدام Didit في دردشة Lovable

يدعم وكيل Lovable خوادم MCP المخصصة. راجع صفحة [Custom MCP servers](https://docs.lovable.dev/integrations/custom-mcp) في Lovable لمعرفة من يمكنه إضافة خادم مخصص. أضف خادم Didit MCP المستضاف، وسيتمكن وكيل Lovable من قراءة حسابك في Didit وتعديله أثناء البناء: إنشاء سير العمل، وتسجيل وجهة webhook، وبدء جلسة اختبار.

> [!NOTE]
>
> يمنح اتصال MCP السياق لـ**دردشة** Lovable فقط. لا يكون جزءاً من تطبيقك المنشور أبداً، فهو يتواصل مع Didit عبر الدوال الواردة في [الجزء 1](#الجزء-1-أضِف-didit-إلى-تطبيق-lovable).

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**: يقبل الخادم المفتاح كـ token من نوع Bearer. راجع [Authentication](https://docs.didit.me/ar/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 تجريبياً يتضمن التحقق من الهوية وكشف الحيوية ومطابقة الوجه، وأعطني معرّف سير العمل."
* "سجّل وجهة webhook في Didit للحدث status.updated تشير إلى دالة Edge Function ‏didit-webhook الخاصة بي، وأخبرني أين أجد سر التوقيع الخاص بها."
* "أنشئ جلسة اختبار لمعرّف المستخدم الخاص بي، وأعطني رابط التحقق."

يشغّل Lovable أدوات القراءة فقط دون أن يسألك، لكنه يطلب موافقتك قبل أي أداة تُجري تغييراً.

### استكشاف الأخطاء وإصلاحها

* **يفشل تسجيل الدخول أو يتكرر.** سجّل الدخول أولاً عبر [business.didit.me](https://business.didit.me) في المتصفح نفسه، ثم اضغط **Add & authorize** مرة أخرى.
* **ترد إحدى الأدوات بالخطأ `missing_scope`.** دورك في تلك المؤسسة لا يملك الإذن المطلوب. راجع [الأدوار والأذونات](https://docs.didit.me/ar/integration/mcp/authentication.md#الأدوار-والأذونات).
* **تعيد دالة webhook الاستجابة `401`.** تأكد من أن `DIDIT_WEBHOOK_SECRET` هو سر الوجهة التي ترسل webhook، وأن الدالة منشورة مع `verify_jwt = false`، وأنها تقرأ جسم الطلب عبر `req.arrayBuffer()` قبل أن يحلّله أي شيء أو يعيد ترميزه. إذا ظهر الخطأ `401` في فحص الطابع الزمني، فهذا يعني أن الإرسال أقدم من خمس دقائق، أو أن ساعة الخادم غير دقيقة.
* **تعيد `didit-create-session` الاستجابة `409`.** يُبلغ Didit بأن الجلسة المتتبَّعة للمستخدم موافَق عليها في بيئة الإنتاج. تعيد الصفحة قراءة الصف، وهو الصف الذي يحدّثه webhook.
* **تعيد `didit-create-session` الاستجابة `502`.** تعذّر الوصول إلى Didit، أو أن جلسة غير مكتملة لا تملك رابطاً لاستئنافها. لم يُنشأ شيء جديد؛ حاول مرة أخرى.
* **يعيد طلب الجلسة الخطأ `400` في الحقل `callback`.** أضف عنوان تطبيقك إلى النطاقات المسموح بها للتطبيق، أو تحقق من القيمة `APP_URL`.

***

## Next steps

> [card] [webhooks](https://docs.didit.me/ar/integration/webhooks.md)
>
> كل حدث وحقل payload ورأس التوقيع.

> [card] [إنشاء الجلسة](https://docs.didit.me/ar/sessions-api/create-session.md)
>
> جميع حقول الطلب، مثل التفاصيل المتوقعة والبيانات الوصفية.

> [card] [مرجع أدوات MCP](https://docs.didit.me/ar/integration/mcp/tools.md)
>
> كل ما يمكن لوكيل Lovable استدعاؤه، أداة تلو الأخرى.

> [card] [الأسعار](https://docs.didit.me/ar/getting-started/pricing.md)
>
> تكلفة كل فحص في سير العمل الخاص بك.


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