Account dei giocatori e il tuo backend
Questa guida mostra come leggere chi sta giocando, offrire l'accesso, inviare un'identità verificata al tuo backend e collegare un account di gioco esistente, con il codice minimo per ogni scenario di account. I giocatori sono connessi a ZokoGames oppure ospiti, e il tuo gioco deve funzionare per entrambi. Gli esempi presuppongono const SDK = window.ZokoGames.SDK; come nell'introduzione all'SDK; termini come ospite e token sono nel glossario.
1. Mostra chi sta giocando#
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));Il listener di autenticazione scatta anche quando il giocatore accede dall'intestazione del portale mentre il tuo gioco è aperto. getUser() è asincrono e si risolve con null per un ospite. Quando il giocatore esce, il portale riavvia il tuo gioco come ospite.
Cosa vedi in altre situazioni: offline, il giocatore è l'ultimo connesso su questo dispositivo, oppure un ospite. Nella modalità bambini non esiste alcun accesso (showAuthPrompt termina come userCancelled). In modalità locale (la tua pagina su localhost) il giocatore è un finto user1, a meno che tu non usi gli interruttori del passo 5.
2. Offri l'accesso a seguito di un'azione del giocatore#
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); }
};Non aprire mai il prompt automaticamente all'avvio.
3. Invia un'identità verificata al tuo server#
Il browser può mentire su __dangerousUserId; un token non si può falsificare.
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),
});
}Sul server, verifica la firma con le chiavi pubbliche del portale, controlla la scadenza e che gameId sia uguale all'id del tuo gioco. Un verificatore completo in Node.js, Python e C# è nel riferimento del modulo user. Middleware Express:
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" });
}
}I token durano un'ora e portano userId, gameId, username, profilePictureUrl. L'SDK mette in cache un token fino a un minuto prima della scadenza, quindi chiama getUserToken() prima di ogni richiesta al backend. La modalità locale emette token non firmati che un verificatore corretto rifiuta.
Per inviare i punteggi della classifica settimanale con lo stesso token, vedi le classifiche passo per passo.
4. Collega un account di gioco esistente (integrazione completa)#
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
}Preferisci collegare a un account nuovo piuttosto che unire due account che hanno entrambi dei progressi, e tratta sempre lo userId verificato come chiave. Una guida completa con un esempio lato server è nel collegamento degli account passo per passo.
5. Prova ogni percorso in locale#
| Percorso | Interruttore nell'URL |
|---|---|
| Ospite | ?user_response=logged_out |
| Connesso all'avvio | ?user_response=user1 |
| Accesso con un pulsante | ?user_response=logged_out&show_auth_prompt_response=user2 |
| Il giocatore annulla | ?show_auth_prompt_response=user_cancelled |
| Collegamento accettato / rifiutato | ?link_account_response=yes / no |
| Il token fallisce / scaduto | ?token_response=logged_out / expired_token |
| Nessun account | ?user_account_available=false |