Skip to content

Delete an account

Delete the account of the currently logged-in user.

Delete the in-memory session and stored tokens only when the account deletion request succeeds.

1. Call the account deletion method

Method

WithdrawPlayerAsync

Requests immediate deletion of the currently logged-in account. A deleted account cannot be recovered. All login methods linked to the account and the guest token are deleted with it, and if the user has a username account, the username and password are also deleted. Even if the user logs in again with the same login method after deletion, the previous account is not restored, and a new Player ID is issued.

Call this method when a logged-in user selects an account deletion button, such as one in your account management UI.

Note

Regardless of the login method (guest, username, or an external authentication provider such as Google or Apple), accounts are deleted only with this method.

Call parameters

Field name Type Required Description
context ApiCallContext Optional Per-call settings object that specifies the idempotency key, cancellation token, and request policy. If omitted, the default values are used.

Call example

For the result model and handling principles of common failures (Failure) that prevent the request from being performed, see Common error handling.

using Hive.Axyl.Auth;
using Hive.Axyl.Core;
using UnityEngine;

IAuthService auth = HiveCore.Resolve<IAuthService>();

AuthWithdrawPlayerResult result = await auth.WithdrawPlayerAsync();

switch (result)
{
    case AuthWithdrawPlayerResult.Success:
        // Server account deletion succeeded → continue to local cleanup (steps 2-3).
        break;

    case AuthWithdrawPlayerResult.PlayerNotFound:
        // Account information not found → check the server/product policy and handle it.
        break;

    case AuthWithdrawPlayerResult.TokenRevokeFailed:
        // The account was not deleted because revoking the login session failed → keep the saved credentials and guide the user to try again.
        // If the session has already ended, guide the user to log in again and then try again.
        break;

    // Handle common failures (network and server errors)
    case AuthWithdrawPlayerResult.Failure failure:
        HiveError err = failure.Problem;
        Debug.LogError($"[{err.Code}] {err.Message} (trace: {err.TraceId})");
        break;

    // Safety net: unhandled results and unknown new results (UnknownOutcome)
    default:
        Debug.LogWarning($"Unhandled result: {result.GetType().Name}");
        break;
}

Response data

No data is returned on success.

Response example

// AuthWithdrawPlayerResult.Success does not return any Data.

Response status

We recommend handling the response cases of AuthWithdrawPlayerResult with a switch statement.

Response case Description App client handling
Success The account deletion request was processed successfully. The success response contains no data. Delete the in-memory session and stored tokens in steps 2 and 3 below.
PlayerNotFound When the account information cannot be found Check the server and product policies, and then handle it.
TokenRevokeFailed When the account was not deleted because revoking the login session failed Keep the saved credentials and guide the user to try deleting the account again. If the session has already ended, guide the user to log in again and then try again.
AppIdMismatch When the app in the X-App-Id header does not belong to the project of the current token Check the App ID setting used during SDK initialization and the project of the logged-in account
InvalidGatewayContext When the authentication context is missing or invalid Check that you registered the session through session activation
AppNotFound When the app information cannot be found Check the app registration status in the console
TerminateService When the app's service has been terminated Check the service operation status
UnknownOutcome A new result that this SDK version does not know Log it and handle it conservatively
Failure Common Failure. Missing required parameters or format errors (invalid_parameter), missing required fields (missing_field), and a missing X-App-Id header (missing_app_id) also branch here, and the cause is contained in Failure.Problem.ExternalCode. See Common error handling. Handle it according to the common error handling guidelines

2. Delete the in-memory session

Method

ClearSession

When the WithdrawPlayerAsync() call succeeds, call ISessionManager.ClearSession() to reset the in-memory session of the app client. It resets all session fields to their default values and raises the OnSessionExpired event after cleanup. If there is no active session, it does nothing.

Call parameters

Field name Type Required Description
None - - No parameters. Get the session manager with HiveCore.Resolve<ISessionManager>() and call the method.

Call example

using Hive.Axyl.Core;

ISessionManager session = HiveCore.Resolve<ISessionManager>();

session.ClearSession();   // Reset the in-memory session → raises OnSessionExpired

Response data

No data is returned on success.

Response example

// ClearSession has no return value (void).
session.ClearSession();

Response status

ClearSession() does not return a result object. If there is no active session, it does nothing.

3. Delete stored tokens

Method

DeleteAsync

Call ISecureStorage.DeleteAsync() to delete items saved in secure storage key by key. Register the storage instance with AddSecureStorage as described in Register the secure storage module, and then get it with HiveCore.TryResolve<ISecureStorage>(out var storage). In environments where secure storage is not registered, such as the Unity Editor, this returns false; in that case there are no items to delete, so skip the deletion. Delete the tokens saved for automatic login or re-login with this method right after the account is deleted.

Call parameters

Field name Type Required Description
request SecureStorageDeleteRequest Required Request for the item to delete
cancellationToken CancellationToken Optional Cancellation token. If omitted, the default value is used.

SecureStorageDeleteRequest

Field name Type Required Description
Key string Required Key of the stored item to delete. This is the value the app chose when saving the token (the SDK does not define it).

Call example

using Hive.Axyl.Core;
using Hive.Axyl.Storage;
using UnityEngine;

// In environments without secure storage (such as the Editor), there is nothing to delete, so skip this step.
if (!HiveCore.TryResolve<ISecureStorage>(out var storage))
{
    return;
}

SecureStorageDeleteResult result =
    await storage.DeleteAsync(new SecureStorageDeleteRequest { Key = "hive.axyl.auth.access_token" });

switch (result)
{
    case SecureStorageDeleteResult.Success:
        // Deletion completed (also treated as Success when the key did not exist).
        break;

    case SecureStorageDeleteResult.AccessDenied:
        // Storage access denied — check the device security settings/permissions.
        break;

    case SecureStorageDeleteResult.DataCorrupted:
        // Stored data is corrupted — consider a full cleanup (ClearAsync).
        break;

    // Safety net: unhandled results and unknown new results (UnknownOutcome)
    default:
        Debug.LogWarning($"Unhandled result: {result.GetType().Name}");
        break;
}

Response data

No data is returned on success.

Response example

// Success branch example
// SecureStorageDeleteResult.Success does not return any Data.

Response status

Response case Description App client handling
Success Deletion completed. The result is Success even when the key did not exist. Proceed to delete the next key.
AccessDenied Storage access denied Check the device security settings/permissions.
DataCorrupted Stored data is corrupted Consider a full cleanup (ClearAsync).
Failure Common Failure. See Common error handling. Handle it according to the common error handling guidelines
UnknownOutcome Unknown new result As a safety net, log it and handle it conservatively.

Full flow example

Example code that handles account deletion, in-memory session deletion, and stored token deletion in order. It cleans up the in-memory session and stored tokens together only when the account deletion succeeds.

Note

This example gets secure storage with HiveCore.TryResolve<ISecureStorage>(out var storage). This is because secure storage is not registered in the Unity Editor, so HiveCore.Resolve<ISecureStorage>() throws RegistrationNotFoundException. For the supported scope, see Register the secure storage module.

using Hive.Axyl.Auth;
using Hive.Axyl.Core;
using Hive.Axyl.Storage;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;

public class DeleteAccountFlow
{
    private readonly IAuthService _auth = HiveCore.Resolve<IAuthService>();
    private readonly ISessionManager _session = HiveCore.Resolve<ISessionManager>();

    public async Task<bool> DeleteAccountAsync(CancellationToken ct = default)
    {
        var result = await _auth.WithdrawPlayerAsync();

        switch (result)
        {
            case AuthWithdrawPlayerResult.Success:
                _session.ClearSession();   // Remove the in-memory session → raises OnSessionExpired
                await DeleteStoredTokensAsync(ct);
                return true;

            case AuthWithdrawPlayerResult.PlayerNotFound:
                Debug.LogWarning("Account information not found. Check the server or product policy.");
                return false;

            case AuthWithdrawPlayerResult.TokenRevokeFailed:
                // The account was not deleted because revoking the login session failed → keep the saved credentials and guide the user to try again.
                return false;

            case AuthWithdrawPlayerResult.Failure failure:
                HiveError err = failure.Problem;
                Debug.LogError($"[{err.Code}] {err.Message} (trace: {err.TraceId})");
                return false;

            default:
                Debug.LogWarning($"Unhandled result: {result.GetType().Name}");
                return false;
        }
    }

    private async Task DeleteStoredTokensAsync(CancellationToken ct)
    {
        // In environments without secure storage (such as the Editor), there is nothing to delete, so skip this step.
        if (!HiveCore.TryResolve<ISecureStorage>(out var storage))
        {
            return;
        }

        // The keys below are examples of values the app chose when saving the tokens (the SDK does not define them).
        await storage.DeleteAsync(new SecureStorageDeleteRequest { Key = "hive.axyl.auth.access_token" }, ct);
        await storage.DeleteAsync(new SecureStorageDeleteRequest { Key = "hive.axyl.auth.refresh_token" }, ct);
        await storage.DeleteAsync(new SecureStorageDeleteRequest { Key = "hive.axyl.auth.player_id" }, ct);
        await storage.DeleteAsync(new SecureStorageDeleteRequest { Key = "hive.axyl.auth.expires_at" }, ct);
        await storage.DeleteAsync(new SecureStorageDeleteRequest { Key = "hive.axyl.auth.guest_token" }, ct);
        await storage.DeleteAsync(new SecureStorageDeleteRequest { Key = "hive.axyl.auth.guest_player_id" }, ct);
    }
}

This example uses the storage retrieved with HiveCore.TryResolve<ISecureStorage>(out var storage). When account deletion completes, it explicitly deletes the saved token keys right after calling ClearSession().

Stored items and how to handle them when deleting an account

ISessionManager manages only the in-memory session. Because the session cannot be restored with the account after the account is deleted, when you delete an account, you must handle in-memory session cleanup and storage cleanup together instead of separately.

Stored item Purpose Recommended handling when deleting an account
accessToken, refreshToken, playerId, expiresAtSec Automatic login session restoration Delete right after the account is deleted.
deviceKey Device identification Keep.
guestToken, guestPlayerId Guest session identification Delete right after the account is deleted.

Implementation checklist

  • Before calling account deletion, inform the user that the action cannot be undone
  • Confirm that account deletion succeeded, and then clean up the in-memory session and stored tokens
  • Decide on follow-up handling for the PlayerNotFound response after checking the server and product policies
  • If you use automatic login, verify that no stored tokens remain right after account deletion
  • Verify that guestToken and guestPlayerId are deleted right after account deletion