# Account linking step by step

Use this guide when your game has its own accounts and its own server, and you want a signed-in ZokoGames player to land in the right game account on every launch. It is the full version of scenario 4 in [account integration scenarios](https://docs.zokogames.com/requirements/accounts). If your game has no accounts, or you only need a name and an avatar, [player accounts and your backend](https://docs.zokogames.com/guides/player-accounts) is enough.

The idea in one line: your server trusts only a **verified token**. The token carries a stable `userId`; you store a link from that `userId` to your own account, and from then on the ZokoGames identity decides which account loads.

Terms such as guest and token are in the [glossary](https://docs.zokogames.com/getting-started/glossary). Examples assume `const SDK = window.ZokoGames.SDK;`.

## What you need

- A server you control that can answer HTTPS requests from the game.
- Your game's id (shown on the game page in the developer console), stored in your server's configuration as `ZOKO_GAME_ID`.
- A table that maps `zoko_user_id` to your own account id. Make `zoko_user_id` unique, so one ZokoGames player can never be linked to two accounts.

## 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
```

Guests must always be able to play. Never block the game on sign-in, and never open the sign-in dialog by yourself at start; see [offer sign-in on a player action](https://docs.zokogames.com/guides/player-accounts#2-offer-sign-in-on-a-player-action).

## 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),
  });
}
```

Call `getUserToken()` before every request instead of keeping the string yourself: the SDK renews it a minute before it expires. `getUser()` is fine for the name in your HUD, but its `__dangerousUserId` can be faked in the browser, so never send it to your server as proof of identity.

## 2. Verify the token on your server

A game token is a JWT signed with **RS256**. Its header has `alg: "RS256"`, `typ: "JWT"` and a `kid`. Its claims are:

| Claim | Value |
| --- | --- |
| `iss` | Always `zokogames`. |
| `aud` | Your game id. A token minted for another game has a different `aud`. |
| `sub` and `userId` | The stable player id. Use it as the key of the link. |
| `gameId` | Your game id again. |
| `username`, `profilePictureUrl` | Display name and avatar at the time of issue. |
| `iat`, `exp` | Issue time and expiry, one hour apart (seconds since 1970). |

Verify the signature against the public keys at `https://www.zokogames.com/.well-known/jwks.json` (a standard JWKS), and check the issuer, the audience and the expiry. With `jose` that is one call:

```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` caches the keys and refetches them when it meets an unknown `kid`, so a key rotation needs no change on your side. If your JWT library only accepts a static key, fetch the same key as a PEM document from `https://www.zokogames.com/.well-known/public-key.json`, which answers `{ "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");
```

A static key stops working when the portal rotates its key. Refetch the document when verification fails with a `kid` you have not seen, or prefer the JWKS. Local mode (your own `localhost` page) issues unsigned test tokens that a correct verifier rejects; see [test every path locally](#5-test-every-path-locally). Verifiers for Python, C# and Go are in the [user module reference](https://docs.zokogames.com/sdk/user#verifying-on-your-server).

## 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) });
});
```

When `linked` is `true` the ZokoGames identity wins: load that account and ignore any local progress that belongs to a different one.

## 4. Offer the link, then store it

Only a player who is signed in and not yet linked sees the prompt. Ask at a calm moment, for example after the first session or on a settings screen, not in the middle of play.

```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();
```

On the server, link the **verified** `userId` and nothing the browser says about itself:

```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 });
});
```

Three rules keep this safe:

- Prefer linking to a **fresh account** over merging two accounts that both have progress. If a merge is unavoidable, let the player choose which progress to keep.
- Treat `userId` as the key and `username` as a label: refresh the label on every launch, never use it to find an account.
- Prove ownership of the game account yourself in `/link`. A token only proves who the ZokoGames player is.

## 5. Test every path locally

On your own `localhost` page the SDK runs in local mode with a fake player, and every step above can be forced with a URL switch:

| Path | URL switch |
| --- | --- |
| Guest | `?user_response=logged_out` |
| Signed in at launch | `?user_response=user1` |
| Player accepts the link | `?link_account_response=yes` |
| Player declines the link | `?link_account_response=no` |
| Token fails or is expired | `?token_response=logged_out` / `?token_response=expired_token` |

The local token is unsigned, so your verifier should reject it. Test the signed path with the [Preview tool](https://www.zokogames.com/preview) or a live build. The full list of switches is in the [user module](https://docs.zokogames.com/sdk/user#in-local-mode-as-a-guest-offline-or-ad-free).

## In an engine

The calls are the same in every engine; only the names change. In Unity, `User.GetUserToken(cb, ZokoSigningKeyType)` returns the token and `User.ShowAccountLinkPrompt(cb)` calls back `true` for yes. The mapping for Unity, GameMaker, Defold, Godot and others is in the [engine overview](https://docs.zokogames.com/engines/overview) and each engine page. Your server code does not change.

## Checklist

- Guests play without signing in, and a failed `getUserToken()` with `userNotAuthenticated` never shows an error.
- The server verifies signature, `RS256`, `iss`, `aud`, expiry and `gameId` on every request that uses the identity.
- `zoko_user_id` is unique in your link table.
- A linked player loads the linked account on every launch.
- Declining the prompt leaves the player in the game as a guest.

## Next steps

- [Player accounts and your backend](https://docs.zokogames.com/guides/player-accounts)
- [User module](https://docs.zokogames.com/sdk/user)
