# プレイヤーアカウントとバックエンド

このガイドでは、誰がプレイしているかの読み取り、サインインの提示、検証済みの識別情報の自前のバックエンドへの送信、既存のゲームアカウントの連携を、それぞれの[アカウントシナリオ](https://docs.zokogames.com/jp/requirements/accounts)に必要な最小限のコードで説明します。プレイヤーは、ZokoGames にサインインしているか、ゲストのどちらかで、ゲームは両方で動作する必要があります。例では、[SDK の概要](https://docs.zokogames.com/jp/sdk/introduction#loading)と同様に `const SDK = window.ZokoGames.SDK;` を前提としています。ゲストやトークンといった用語は[用語集](https://docs.zokogames.com/jp/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()` は非同期で、ゲストの場合は `null` で解決されます。プレイヤーがサインアウトすると、ポータルはゲームをゲストとして再起動します。

他の状況で見えるもの: オフラインの場合、プレイヤーはこの端末で最後にサインインした人、またはゲストです。子ども向けモードではサインイン自体がありません(`showAuthPrompt` は `userCancelled` で終わります)。ローカルモード(自分の `localhost` ページ)では、手順 5 のスイッチを使わない限り、プレイヤーは偽の `user1` です。

## 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` がゲームの ID と等しいことを確認します。Node.js、Python、C# の完全な検証コードは、[ユーザーモジュールのリファレンス](https://docs.zokogames.com/jp/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" });
  }
}
```

トークンの有効期間は 1 時間で、`userId`、`gameId`、`username`、`profilePictureUrl` を含みます。SDK はトークンを有効期限の 1 分前までキャッシュするため、バックエンドへのリクエストの前に毎回 `getUserToken()` を呼び出してください。ローカルモードは署名なしのトークンを発行し、正しい検証コードはそれを拒否します。

同じトークンを使って週間リーダーボードにスコアを送信する方法は、[リーダーボードの手順](https://docs.zokogames.com/jp/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
}
```

進行状況のある 2 つのアカウントを統合するより、新しいアカウントへの連携を優先し、常に検証済みの `userId` をキーとして扱ってください。サーバー側の例を含む完全な手順は、[アカウント連携の手順](https://docs.zokogames.com/jp/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/jp/guides/account-linking)
- [User モジュール](https://docs.zokogames.com/jp/sdk/user)
