# บัญชีผู้เล่นและแบ็กเอนด์ของคุณ {#player-accounts-and-your-backend}

คู่มือนี้แสดงวิธีอ่านว่าใครกำลังเล่น เสนอการลงชื่อเข้าใช้ ส่งตัวตนที่ยืนยันแล้วไปยังแบ็กเอนด์ของคุณ และเชื่อมบัญชีเกมที่มีอยู่ ด้วยโค้ดขั้นต่ำสำหรับแต่ละ[สถานการณ์บัญชี](https://docs.zokogames.com/th/requirements/accounts) ผู้เล่นเป็นผู้ที่ลงชื่อเข้าใช้ ZokoGames หรือแขก และเกมของคุณต้องใช้ได้กับทั้งสอง ตัวอย่างสมมติว่ามี `const SDK = window.ZokoGames.SDK;` ตามที่ระบุใน[บทนำ SDK](https://docs.zokogames.com/th/sdk/introduction#loading) ศัพท์เช่นแขกและโทเคนอยู่ใน[อภิธานศัพท์](https://docs.zokogames.com/th/getting-started/glossary)

## 1. แสดงว่าใครกำลังเล่น {#1-show-who-is-playing}

```js
await SDK.init();
const user = await SDK.user.getUser();            // null for guests
if (user) hud.setName(user.username, user.profilePictureUrl);

SDK.user.addAuthListener((u) => hud.setName(u.username, u.profilePictureUrl));
```

ลิสเทนเนอร์การยืนยันตัวตนทำงานด้วยเมื่อผู้เล่นลงชื่อเข้าใช้ผ่านเฮดเดอร์ของพอร์ทัลเองขณะที่เกมของคุณเปิดอยู่ `getUser()` เป็นแบบอะซิงโครนัสและ resolve `null` สำหรับแขก เมื่อผู้เล่นออกจากระบบ พอร์ทัลรีสตาร์ตเกมของคุณเป็นแขก

สิ่งที่คุณเห็นในสถานการณ์อื่น: เมื่อออฟไลน์ ผู้เล่นคือคนล่าสุดที่ลงชื่อเข้าใช้บนอุปกรณ์นี้ หรือแขก ในโหมดเด็กไม่มีการลงชื่อเข้าใช้เลย (`showAuthPrompt` จบเป็น `userCancelled`) ในโหมดโลคอล (หน้า `localhost` ของคุณเอง) ผู้เล่นคือ `user1` ปลอม เว้นแต่คุณใช้สวิตช์ในขั้นตอนที่ 5

## 2. เสนอการลงชื่อเข้าใช้เมื่อผู้เล่นกระทำ {#2-offer-sign-in-on-a-player-action}

```js
if (SDK.user.isUserAccountAvailable && !user) signInButton.hidden = false;
signInButton.onclick = async () => {
  try { await SDK.user.showAuthPrompt(); }
  catch (e) { if (e.code !== "userCancelled") console.warn(e.code); }
};
```

อย่าเปิดพรอมต์โดยอัตโนมัติตอนเริ่ม

## 3. ส่งตัวตนที่ยืนยันแล้วไปยังเซิร์ฟเวอร์ของคุณ {#3-send-a-verified-identity-to-your-server}

เบราว์เซอร์โกหกเรื่อง `__dangerousUserId` ได้ โทเคนปลอมแปลงไม่ได้

```js
async function callBackend(path, body) {
  let token = null;
  try { token = await SDK.user.getUserToken(); } catch (e) { /* userNotAuthenticated: guest */ }
  return fetch("https://api.example.com" + path, {
    method: "POST",
    headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) },
    body: JSON.stringify(body),
  });
}
```

บนเซิร์ฟเวอร์ ตรวจสอบลายเซ็นด้วยคีย์สาธารณะของพอร์ทัล ตรวจวันหมดอายุ และตรวจว่า `gameId` เท่ากับรหัสเกมของคุณ ตัวตรวจสอบที่สมบูรณ์ใน Node.js, Python และ C# อยู่ใน[เอกสารอ้างอิงโมดูล user](https://docs.zokogames.com/th/sdk/user#verifying-on-your-server) มิดเดิลแวร์ Express:

```js
import { createRemoteJWKSet, jwtVerify } from "jose";
const JWKS = createRemoteJWKSet(new URL("https://www.zokogames.com/.well-known/jwks.json"));

export async function zokoAuth(req, res, next) {
  const raw = (req.headers.authorization || "").replace(/^Bearer /, "");
  if (!raw) { req.player = null; return next(); }            // guest
  try {
    const { payload } = await jwtVerify(raw, JWKS, {
      algorithms: ["RS256"],
      issuer: "zokogames",
      audience: process.env.ZOKO_GAME_ID,
      clockTolerance: 5,
    });
    if (payload.gameId !== process.env.ZOKO_GAME_ID) throw new Error("wrong game");
    req.player = { id: payload.userId, name: payload.username };
    next();
  } catch {
    res.status(401).json({ error: "invalid_token" });
  }
}
```

โทเคนมีอายุหนึ่งชั่วโมงและมี `userId`, `gameId`, `username`, `profilePictureUrl` SDK แคชโทเคนไว้จนถึงหนึ่งนาทีก่อนหมดอายุ จึงเรียก `getUserToken()` ก่อนทุกคำขอไปยังแบ็กเอนด์ โหมดโลคอลออกโทเคนที่ไม่ได้เซ็นซึ่งตัวตรวจสอบที่ถูกต้องจะปฏิเสธ

หากต้องการส่งคะแนนไปยังกระดานผู้นำรายสัปดาห์จากโทเคนเดียวกัน ดู[กระดานผู้นำทีละขั้นตอน](https://docs.zokogames.com/th/guides/leaderboard-setup)

## 4. เชื่อมบัญชีเกมที่มีอยู่ (การผสานเต็มรูปแบบ) {#4-link-an-existing-game-account-full-integration}

```js
async function onSignedIn() {
  const { linked } = await (await callBackend("/session", {})).json();
  if (linked) return;                                           // userId already linked: load that account
  const { response } = await SDK.user.showAccountLinkPrompt();
  if (response === "yes") await callBackend("/link", {});       // server links the verified userId to this game account
}
```

เลือกการเชื่อมกับบัญชีใหม่แทนการรวมสองบัญชีที่มีความคืบหน้าทั้งคู่ และถือ `userId` ที่ยืนยันแล้วเป็นคีย์เสมอ ขั้นตอนฉบับเต็มพร้อมตัวอย่างฝั่งเซิร์ฟเวอร์อยู่ใน[การเชื่อมบัญชีทีละขั้นตอน](https://docs.zokogames.com/th/guides/account-linking)

## 5. ทดสอบทุกเส้นทางในเครื่อง {#5-test-every-path-locally}

| เส้นทาง | สวิตช์ URL |
| --- | --- |
| แขก | `?user_response=logged_out` |
| ลงชื่อเข้าใช้ตอนเริ่ม | `?user_response=user1` |
| ลงชื่อเข้าใช้บนปุ่ม | `?user_response=logged_out&show_auth_prompt_response=user2` |
| ผู้เล่นยกเลิก | `?show_auth_prompt_response=user_cancelled` |
| ยอมรับ / ปฏิเสธการเชื่อม | `?link_account_response=yes` / `no` |
| โทเคนล้มเหลว / หมดอายุ | `?token_response=logged_out` / `expired_token` |
| ไม่มีบัญชีเลย | `?user_account_available=false` |

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

- [การเชื่อมบัญชีทีละขั้น](https://docs.zokogames.com/th/guides/account-linking)
- [โมดูลผู้ใช้](https://docs.zokogames.com/th/sdk/user)
