# การเชื่อมบัญชีทีละขั้น {#account-linking-step-by-step}

ใช้คู่มือนี้เมื่อเกมของคุณมีบัญชีของตัวเองและเซิร์ฟเวอร์ของตัวเอง และคุณต้องการให้ผู้เล่น ZokoGames ที่ลงชื่อเข้าใช้ไปอยู่ในบัญชีเกมที่ถูกต้องทุกครั้งที่เปิดเกม นี่คือฉบับเต็มของสถานการณ์ที่ 4 ใน[สถานการณ์การผสานบัญชี](https://docs.zokogames.com/th/requirements/accounts) หากเกมของคุณไม่มีบัญชี หรือคุณต้องการแค่ชื่อและอวตาร[บัญชีผู้เล่นและแบ็กเอนด์ของคุณ](https://docs.zokogames.com/th/guides/player-accounts)ก็เพียงพอ

แนวคิดในบรรทัดเดียว: เซิร์ฟเวอร์ของคุณเชื่อถือเฉพาะ**โทเคนที่ตรวจสอบแล้ว** โทเคนมี `userId` ที่คงที่ คุณเก็บการเชื่อมจาก `userId` นั้นไปยังบัญชีของคุณเอง และจากนั้นตัวตน ZokoGames จะเป็นตัวตัดสินว่าบัญชีใดถูกโหลด

คำอย่างแขกและโทเคนอยู่ใน[อภิธานศัพท์](https://docs.zokogames.com/th/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/th/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()` ใช้ได้สำหรับชื่อใน HUD ของคุณ แต่ `__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/th/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 รันในโหมดโลคอลพร้อมผู้เล่นปลอม และทุกขั้นข้างต้นบังคับได้ด้วยสวิตช์ URL:

| เส้นทาง | สวิตช์ URL |
| --- | --- |
| แขก | `?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/th/preview)หรือบิลด์ที่ออนไลน์ รายการสวิตช์ทั้งหมดอยู่ใน[โมดูล user](https://docs.zokogames.com/th/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/th/engines/overview)และหน้าของแต่ละเอนจิน โค้ดฝั่งเซิร์ฟเวอร์ของคุณไม่เปลี่ยน

## เช็กลิสต์ {#checklist}

- แขกเล่นได้โดยไม่ต้องลงชื่อเข้าใช้ และ `getUserToken()` ที่ล้มเหลวด้วย `userNotAuthenticated` ไม่เคยแสดงข้อผิดพลาด
- เซิร์ฟเวอร์ตรวจสอบลายเซ็น `RS256` `iss` `aud` เวลาหมดอายุ และ `gameId` ในทุกคำขอที่ใช้ตัวตนนี้
- `zoko_user_id` ไม่ซ้ำในตารางการเชื่อมของคุณ
- ผู้เล่นที่เชื่อมแล้วโหลดบัญชีที่เชื่อมทุกครั้งที่เปิดเกม
- การปฏิเสธพรอมต์ปล่อยให้ผู้เล่นอยู่ในเกมในฐานะแขก

## ขั้นตอนถัดไป {#next-steps}

- [บัญชีผู้เล่นและแบ็กเอนด์ของคุณ](https://docs.zokogames.com/th/guides/player-accounts)
- [โมดูลผู้ใช้](https://docs.zokogames.com/th/sdk/user)
