# ربط الحساب خطوة بخطوة {#account-linking-step-by-step}

استخدم هذا الدليل حين يكون للعبتك حسابات خاصة بها وخادم خاص بها، وتريد أن يصل لاعب ZokoGames المسجَّل الدخول إلى حساب اللعبة الصحيح في كل تشغيل. وهو النسخة الكاملة من السيناريو 4 في [سيناريوهات دمج الحسابات](https://docs.zokogames.com/ar/requirements/accounts). وإن لم يكن للعبتك حسابات، أو كنت تحتاج إلى اسم وصورة رمزية فقط، فيكفي [حسابات اللاعبين وخادمك الخلفي](https://docs.zokogames.com/ar/guides/player-accounts).

الفكرة في سطر واحد: لا يثق خادمك إلا بـ**رمز تم التحقق منه**. يحمل الرمز `userId` ثابتًا؛ وتخزّن رابطًا من هذا `userId` إلى حسابك الخاص، ومن ثم تقرر هوية ZokoGames أي حساب يُحمَّل.

المصطلحات مثل الضيف والرمز موجودة في [المسرد](https://docs.zokogames.com/ar/getting-started/glossary). تفترض الأمثلة `const SDK = window.ZokoGames.SDK;`.

## ما الذي تحتاجه {#what-you-need}

- خادم تتحكم فيه ويستطيع الرد على طلبات HTTPS من اللعبة.
- معرّف لعبتك (يظهر في صفحة اللعبة في وحدة تحكم المطوّرين)، مخزَّنًا في إعدادات خادمك باسم `ZOKO_GAME_ID`.
- جدول يربط `zoko_user_id` بمعرّف حسابك الخاص. اجعل `zoko_user_id` فريدًا، كي لا يُربط لاعب ZokoGames واحد بحسابين أبدًا.

## التدفق {#the-flow}

```text
launch
  -> getUser()                         null: play as a guest, stop here
  -> getUserToken()  -> POST /session  server verifies the token, answers { linked }
        linked: true   -> load that game account (the ZokoGames identity wins)
        linked: false  -> showAccountLinkPrompt()
                              "yes" -> POST /link  server links userId to the game account
                              "no"  -> continue as a guest
```

يجب أن يستطيع الضيوف اللعب دائمًا. لا تحجب اللعبة أبدًا بانتظار تسجيل الدخول، ولا تفتح حوار تسجيل الدخول بنفسك عند البدء؛ راجع [اعرض تسجيل الدخول عند فعل من اللاعب](https://docs.zokogames.com/ar/guides/player-accounts#2-offer-sign-in-on-a-player-action).

## 1. اقرأ اللاعب واحصل على رمز {#1-read-the-player-and-get-a-token}

```js
await SDK.init();

async function token() {
  try {
    return await SDK.user.getUserToken();      // cached by the SDK, valid for one hour
  } catch (e) {
    if (e.code === "userNotAuthenticated") return null;   // a guest
    throw e;
  }
}

async function api(path, body = {}) {
  const t = await token();
  return fetch(`https://api.example.com${path}`, {
    method: "POST",
    headers: {
      "content-type": "application/json",
      ...(t ? { authorization: `Bearer ${t}` } : {}),
    },
    body: JSON.stringify(body),
  });
}
```

استدعِ `getUserToken()` قبل كل طلب بدل أن تحتفظ بالنص بنفسك: فالـ SDK تجدّده قبل انتهائه بدقيقة. ولا بأس باستخدام `getUser()` للاسم في واجهتك، لكن `__dangerousUserId` فيه يمكن تزويره في المتصفح، فلا ترسله إلى خادمك دليلًا على الهوية أبدًا.

## 2. تحقق من الرمز على خادمك {#2-verify-the-token-on-your-server}

رمز اللعبة هو JWT موقَّع بـ **RS256**. في ترويسته `alg: "RS256"` و`typ: "JWT"` و`kid`. ومطالباته هي:

| المطالبة | القيمة |
| --- | --- |
| `iss` | دائمًا `zokogames`. |
| `aud` | معرّف لعبتك. الرمز الصادر للعبة أخرى له `aud` مختلف. |
| `sub` و`userId` | معرّف اللاعب الثابت. استخدمه مفتاحًا للرابط. |
| `gameId` | معرّف لعبتك مرة أخرى. |
| `username` و`profilePictureUrl` | الاسم المعروض والصورة الرمزية وقت الإصدار. |
| `iat` و`exp` | وقت الإصدار والانتهاء، بينهما ساعة واحدة (ثوانٍ منذ 1970). |

تحقق من التوقيع مقابل المفاتيح العامة في `https://www.zokogames.com/.well-known/jwks.json` (وهو JWKS قياسي)، وافحص الجهة المُصدِرة والجمهور والانتهاء. ومع `jose` يكون ذلك استدعاءً واحدًا:

```js
// zoko-auth.js
import { createRemoteJWKSet, jwtVerify } from "jose";

const GAME_ID = process.env.ZOKO_GAME_ID;
const JWKS = createRemoteJWKSet(new URL("https://www.zokogames.com/.well-known/jwks.json"));

/** Returns { userId, username } for a valid token, or throws. */
export async function verifyZokoToken(raw) {
  const { payload } = await jwtVerify(raw, JWKS, {
    algorithms: ["RS256"],       // never accept anything else
    issuer: "zokogames",
    audience: GAME_ID,           // a token for another game fails here
    requiredClaims: ["exp", "iat", "aud"],
    clockTolerance: 5,           // seconds of clock drift
  });
  if (payload.gameId !== GAME_ID || payload.sub !== payload.userId) {
    throw new Error("malformed token");
  }
  return { userId: String(payload.userId), username: String(payload.username) };
}

/** Express middleware: req.player is null for a guest, 401 for a token that does not verify. */
export async function zokoAuth(req, res, next) {
  const raw = (req.headers.authorization || "").replace(/^Bearer /, "");
  if (!raw) {
    req.player = null;
    return next();
  }
  try {
    req.player = await verifyZokoToken(raw);
    next();
  } catch {
    res.status(401).json({ error: "invalid_token" });
  }
}
```

تخزّن `createRemoteJWKSet` المفاتيح مؤقتًا وتعيد جلبها حين تصادف `kid` مجهولًا، فلا يحتاج تدوير المفاتيح إلى أي تغيير من جانبك. وإن كانت مكتبة JWT لديك لا تقبل إلا مفتاحًا ثابتًا فاجلب المفتاح نفسه بصيغة PEM من `https://www.zokogames.com/.well-known/public-key.json` الذي يجيب `{ "alg": "RS256", "kid": "…", "publicKey": "-----BEGIN PUBLIC KEY-----…" }`:

```js
import { importSPKI, jwtVerify } from "jose";

const doc = await (await fetch("https://www.zokogames.com/.well-known/public-key.json")).json();
const key = await importSPKI(doc.publicKey, doc.alg);
const { payload } = await jwtVerify(raw, key, { algorithms: ["RS256"], issuer: "zokogames", audience: GAME_ID });
if (payload.gameId !== GAME_ID || payload.sub !== payload.userId) throw new Error("wrong game or subject");
```

يتوقف المفتاح الثابت عن العمل حين تدوّر البوابة مفتاحها. أعد جلب المستند حين يفشل التحقق مع `kid` لم تره من قبل، أو فضّل JWKS. يُصدر الوضع المحلي (صفحة `localhost` الخاصة بك) رموز اختبار غير موقَّعة يرفضها أي مدقّق صحيح؛ راجع [اختبر كل مسار محليًا](#5-test-every-path-locally). مدقّقات Python وC# وGo في [مرجع وحدة user](https://docs.zokogames.com/ar/sdk/user#verifying-on-your-server).

## 3. أجب عن "هل هذا اللاعب مربوط؟" {#3-answer-is-this-player-linked}

```js
// server.js
import express from "express";
import { zokoAuth } from "./zoko-auth.js";
import { db } from "./db.js";   // your own data layer

const app = express();
app.use(express.json());
app.use(zokoAuth);

app.post("/session", async (req, res) => {
  if (!req.player) return res.json({ guest: true, linked: false });
  const row = await db.links.findByZokoUser(req.player.userId);
  if (!row) return res.json({ guest: false, linked: false });
  // Keep the display data fresh, then load the account the link points to.
  await db.accounts.update(row.accountId, { displayName: req.player.username });
  res.json({ guest: false, linked: true, profile: await db.accounts.load(row.accountId) });
});
```

حين تكون `linked` مساوية `true` تكون الغلبة لهوية ZokoGames: حمّل ذلك الحساب وتجاهل أي تقدم محلي يعود إلى حساب مختلف.

## 4. اعرض الربط ثم خزّنه {#4-offer-the-link-then-store-it}

لا يرى النافذة إلا لاعب مسجَّل الدخول وغير مربوط بعد. اطلب في لحظة هادئة، مثل ما بعد الجلسة الأولى أو في شاشة الإعدادات، لا في منتصف اللعب.

```js
async function onSignedIn() {
  const res = await (await api("/session")).json();
  if (res.guest || res.linked) return res.profile ?? null;

  try {
    const { response } = await SDK.user.showAccountLinkPrompt();
    if (response === "yes") {
      const out = await api("/link", { gameAccountId: currentAccountId() });
      if (out.status === 409) showMessage("That ZokoGames player is already linked to another account.");
    }
    // "no": stay a guest, the question can be asked again later
  } catch (e) {
    if (e.code !== "userNotAuthenticated" && e.code !== "showAccountLinkPromptInProgress") throw e;
  }
}

SDK.user.addAuthListener(onSignedIn);   // also runs when the player signs in from the portal header
onSignedIn();
```

على الخادم اربط الـ `userId` **المتحقَّق منه** ولا شيء مما يقوله المتصفح عن نفسه:

```js
app.post("/link", async (req, res) => {
  if (!req.player) return res.status(401).json({ error: "sign_in_required" });
  const accountId = String(req.body.gameAccountId || "");
  // Your own proof that the caller controls this game account (session cookie, password, device secret...).
  if (!(await db.accounts.callerOwns(req, accountId))) return res.status(403).json({ error: "not_your_account" });
  try {
    await db.links.insert({ zokoUserId: req.player.userId, accountId });   // zoko_user_id is UNIQUE
  } catch (e) {
    if (e.code === "unique_violation") return res.status(409).json({ error: "already_linked" });
    throw e;
  }
  res.json({ linked: true });
});
```

ثلاث قواعد تُبقي هذا آمنًا:

- فضّل الربط بـ**حساب جديد** على دمج حسابين لكل منهما تقدم. وإن كان الدمج لا مفر منه فدع اللاعب يختار أي تقدم يحتفظ به.
- عامل `userId` بوصفه المفتاح و`username` بوصفه تسمية: حدّث التسمية في كل تشغيل، ولا تستخدمها أبدًا للعثور على حساب.
- أثبت بنفسك ملكية حساب اللعبة في `/link`. فالرمز لا يثبت إلا من هو لاعب ZokoGames.

## 5. اختبر كل مسار محليًا {#5-test-every-path-locally}

في صفحة `localhost` الخاصة بك تعمل SDK في الوضع المحلي مع لاعب وهمي، ويمكن فرض كل خطوة أعلاه بمفتاح في العنوان:

| المسار | مفتاح العنوان |
| --- | --- |
| ضيف | `?user_response=logged_out` |
| مسجَّل الدخول عند التشغيل | `?user_response=user1` |
| اللاعب يقبل الربط | `?link_account_response=yes` |
| اللاعب يرفض الربط | `?link_account_response=no` |
| فشل الرمز أو انتهاء صلاحيته | `?token_response=logged_out` / `?token_response=expired_token` |

الرمز المحلي غير موقَّع، فيجب أن يرفضه مدقّقك. اختبر المسار الموقَّع بـ[أداة المعاينة](https://www.zokogames.com/ar/preview) أو ببناء منشور. والقائمة الكاملة للمفاتيح في [وحدة user](https://docs.zokogames.com/ar/sdk/user#in-local-mode-as-a-guest-offline-or-ad-free).

## في محرك {#in-an-engine}

الاستدعاءات هي نفسها في كل محرك؛ تتغير الأسماء فقط. في Unity تُرجع `User.GetUserToken(cb, ZokoSigningKeyType)` الرمز وتستدعي `User.ShowAccountLinkPrompt(cb)` رد النداء بـ `true` للموافقة. والمطابقة لـ Unity وGameMaker وDefold وGodot وغيرها في [نظرة عامة على المحركات](https://docs.zokogames.com/ar/engines/overview) وصفحة كل محرك. ولا تتغير شيفرة خادمك.

## قائمة التحقق {#checklist}

- يلعب الضيوف دون تسجيل دخول، ولا يُظهر فشل `getUserToken()` بالرمز `userNotAuthenticated` أي خطأ أبدًا.
- يتحقق الخادم من التوقيع و`RS256` و`iss` و`aud` والانتهاء و`gameId` في كل طلب يستخدم الهوية.
- ‏`zoko_user_id` فريد في جدول الربط لديك.
- يحمّل اللاعب المربوط الحساب المربوط في كل تشغيل.
- رفض النافذة يترك اللاعب في اللعبة بوصفه ضيفًا.

## الخطوات التالية {#next-steps}

- [حسابات اللاعبين وخادمك الخلفي](https://docs.zokogames.com/ar/guides/player-accounts)
- [وحدة المستخدم](https://docs.zokogames.com/ar/sdk/user)
