Jugadores e inicio de sesión
Cuentas de invitado que sobreviven a los reinicios, nombres visibles y vinculación de invitados a correo o Google.
Los comentarios del código y los nombres de la API se mantienen en inglés para que coincidan con los SDK.
Inicio de sesión como invitado#
Llama a esto una vez al iniciar. Restaura la sesión guardada (y la renueva si hace falta) o crea un invitado nuevo, para que el mismo jugador conserve su progreso.
var signIn = await Majacloud.Auth.SignInAnonymouslyAsync();
if (signIn.Ok)
{
var player = signIn.Value;
Debug.Log(player.PlayerId + " " + player.DisplayName + " guest: " + player.IsGuest);
}var signed_in := await Majacloud.auth.sign_in_anonymously()
if signed_in.ok:
var player: Dictionary = signed_in.value
print(player.player_id, " ", player.display_name, " ", player.auth_type)const signIn = await mc.auth.signInAnonymously();
if (signIn.ok) {
const player = signIn.value;
console.log(player.player_id, player.display_name, player.auth_type);
}curl -X POST https://majacloud.majanite.com/v1/auth/guest -H "X-Project-ID: $PROJECT_ID" -H "X-Client-Key: $CLIENT_KEY" \
-H "Content-Type: application/json" -d '{"device_id": "install-7f2c"}'
# Before the access token expires (1 hour), rotate the session:
curl -X POST https://majacloud.majanite.com/v1/auth/refresh -H "X-Project-ID: $PROJECT_ID" -H "X-Client-Key: $CLIENT_KEY" \
-H "Content-Type: application/json" -d '{"refresh_token": "<refresh_token>"}'Nombres visibles#
Los invitados reciben un nombre generado, como Guest 4821. Los jugadores pueden elegir el suyo; las tablas de clasificación lo muestran.
var renamed = await Majacloud.Auth.SetDisplayNameAsync("Nova");
if (!renamed.Ok) Debug.Log(renamed.Error.Message); // e.g. Validation: too longvar renamed := await Majacloud.auth.set_display_name("Nova")
if not renamed.ok:
print(renamed.message) # e.g. validation: too longconst renamed = await mc.auth.setDisplayName('Nova');
if (!renamed.ok) console.log(renamed.error.message); // e.g. validation: too longcurl -X PATCH https://majacloud.majanite.com/v1/players/me -H "X-Project-ID: $PROJECT_ID" -H "X-Client-Key: $CLIENT_KEY" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" -d '{"display_name": "Nova"}'Vincular a correo o Google#
La vinculación abre una página web segura en tu servidor MAJACLOUD donde el jugador inicia sesión o se registra con correo y contraseña o con Google. El progreso del invitado (puntuaciones, guardados, billetera) pasa a esa cuenta y el juego recibe la nueva sesión, en cualquier dispositivo.
// Opens the sign-in page, waits for the player, then switches the session
var linked = await Majacloud.Auth.LinkAccountAsync(new MajacloudLinkOptions { ReturnUrl = "mygame://auth" });
if (linked.Ok) Debug.Log("Signed in as " + linked.Value.DisplayName);
// WebGL: browsers only open tabs from a click, so start first and open inside the handler
var flow = await Majacloud.Auth.StartLinkAsync(new MajacloudLinkOptions { OpenBrowser = false });
linkButton.onClick.AddListener(() => flow.Value.OpenInBrowser());
var result = await flow.Value.WaitForCompletionAsync();# Opens the sign-in page, waits for the player, then switches the session
var linked := await Majacloud.auth.link_account("mygame://auth")
if linked.ok:
print("Signed in as ", linked.value.display_name)
# Or step by step (e.g. to open the page from a button)
var started := await Majacloud.auth.start_link()
var flow: MajacloudLinkFlow = started.value
flow.open_in_browser()
var result := await flow.wait_for_completion()// Call it from a click handler: the browser only allows the new tab after a user gesture
document.querySelector('#link').addEventListener('click', async () => {
const linked = await mc.auth.linkAccount();
if (linked.ok) console.log('Signed in as ' + linked.value.display_name);
});# 1. Start (send the guest's Bearer token so its progress is merged)
curl -X POST https://majacloud.majanite.com/v1/auth/link/start -H "X-Project-ID: $PROJECT_ID" -H "X-Client-Key: $CLIENT_KEY" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" -d '{"code_challenge": "<base64url(sha256(verifier))>", "code_challenge_method": "S256"}'
# 2. Open auth_url for the player, then poll until status is "completed"
curl "https://majacloud.majanite.com/v1/auth/link/status?flow_id=<flow_id>&flow_token=<flow_token>" -H "X-Project-ID: $PROJECT_ID" -H "X-Client-Key: $CLIENT_KEY"
# 3. Exchange for the new session
curl -X POST https://majacloud.majanite.com/v1/auth/link/exchange -H "X-Project-ID: $PROJECT_ID" -H "X-Client-Key: $CLIENT_KEY" \
-H "Content-Type: application/json" -d '{"flow_id": "<flow_id>", "exchange_code": "<exchange_code>", "code_verifier": "<verifier>"}'Cómo funciona la vinculación#
- El SDK crea un secreto de un solo uso (PKCE) e inicia un flujo de inicio de sesión.
- El jugador termina en la página web; mientras tanto, el SDK consulta el estado hasta que el flujo se completa.
- El SDK canjea el flujo por una sesión usando el secreto, así que un enlace robado no sirve de nada.
- Los flujos caducan a los 15 minutos (el plazo se amplía mientras la página está abierta).
Volver al juego#
Sin una URL de retorno, la página indica a los jugadores que vuelvan al juego. Para devolverlos automáticamente, añade tu esquema de URL personalizado (por ejemplo, mygame) en Claves de API ▸ URL de retorno del inicio de sesión de jugadores y pasa mygame://auth como URL de retorno.
Eventos#
Reacciona cuando cambia el jugador, cuando cierra sesión o cuando la sesión ya no se puede renovar:
Majacloud.Auth.PlayerChanged += player => nameLabel.text = player?.DisplayName;
Majacloud.Auth.SignedOut += () => ShowTitleScreen();
Majacloud.Auth.SessionExpired += () => ShowSignIn();Majacloud.auth.player_changed.connect(func(player): $NameLabel.text = player.get("display_name", ""))
Majacloud.auth.signed_out.connect(show_title_screen)
Majacloud.auth.session_expired.connect(show_sign_in)mc.auth.on('playerChanged', (player) => render(player));
mc.auth.on('signedOut', () => showTitleScreen());
mc.auth.on('sessionExpired', () => showSignIn());Cerrar sesión#
Al cerrar sesión, la sesión se revoca en el servidor y se olvida en el dispositivo. El siguiente inicio de sesión crea un invitado nuevo.
await Majacloud.Auth.SignOutAsync(); // revokes the session on the server
Majacloud.Auth.ClearLocalSession(); // or only forget it on this deviceawait Majacloud.auth.sign_out() # revokes the session on the server
Majacloud.auth.clear_local_session() # or only forget it on this deviceawait mc.auth.signOut(); // revokes the session on the server
mc.auth.clearLocalSession(); // or only forget it on this devicecurl -X POST https://majacloud.majanite.com/v1/auth/logout -H "X-Project-ID: $PROJECT_ID" -H "X-Client-Key: $CLIENT_KEY" \
-H "Content-Type: application/json" -d '{"refresh_token": "<refresh_token>"}'Leer jugadores desde tu servidor#
Con la clave secreta, tu servidor puede leer cualquier jugador, incluidos el correo y los saldos de la billetera:
// Node.js, created with secretKey
const found = await admin.server.getPlayer('player_3f9c…');
if (found.ok) console.log(found.value.player.email, found.value.player.wallets);curl https://majacloud.majanite.com/v1/players/player_3f9c… \
-H "X-Project-ID: $PROJECT_ID" -H "X-Secret-Key: $SECRET_KEY"En el panel#
La página Jugadores muestra todos los jugadores con su método de inicio de sesión, puntuaciones, guardados y billetera. Desde ahí puedes renombrar o desactivar un jugador, cerrar su sesión en todas partes, enviarle un enlace para restablecer la contraseña o eliminarlo.