Player data

You can save game state data (completed levels, experience, in-game purchases and such) on the Yandex server or transmit them to your own server. You can also provide a more personalized experience by using data from the user's Yandex profile — for example, their name.

To work with user data, use the Player object.

Initialization

To initialize the Player object, use the ysdk.getPlayer() method.

var player;

ysdk.getPlayer().then(_player => {
     player = _player;
  }).catch(err => {
     // Error initializing the Player object.
  });

Upon initialization of the Player object, the authorized player sees a dialog box requesting access to their personal data. Access is requested only for the avatar and username, the user ID is always transmitted automatically. Example text: "The game is requesting access to your Yandex avatar and username".

If you only need the ID and not the username or avatar, use the optional scopes: false parameter. In this case, the dialog box is not displayed.

Settings for calling the dialog box:

  • ysdk.getPlayer() or ysdk.getPlayer({ scopes: true }): The authorized user sees a dialog box requesting access. If the user denies access, you only get their ID.
  • ysdk.getPlayer({ scopes: false }): Dialog box isn't displayed. You only get the user ID.

You can apply the optional signed: true parameter and the fetch method to log the user in and save game state data on your server. This enables you to use a signature to authenticate the user and prevent fraud.

var player;

ysdk.getPlayer({ signed: true }).then(_player => {
        player = _player;

        // Use player.signature for authorization on your server.
        fetch('https://your.game.server?auth', {
            method: 'POST',
            headers: { 'Content-Type': 'text/plain' },
            body: player.signature
        });
    }).catch(err => {
        // Error initializing the Player object.
    });

The signature parameter of the request sent to the server contains user data from the Yandex profile and the signature. It comprises two Base64-encoded strings:

<signature>.<profile data>

For more information, see Fraud prevention.

User login

Verifying authorization

To check whether the player is logged in to Yandex, use the Player object method — player.getMode(). If the player isn't logged in, this method returns the lite string.

Calling the login dialog box

If the player isn't logged in, you can use the ysdk.auth.openAuthDialog() method to call the authorization window.

Tip

Inform the user about the advantages of logging in. If the user is not aware of the associated benefits, they will most likely refuse to log in and then exit the game.

var player;

function initPlayer() {
    return ysdk.getPlayer().then(_player => {
            player = _player;

            return player;
        });
}

initPlayer().then(_player => {
        if (_player.getMode() === 'lite') {
            // The player isn't logged in.
            ysdk.auth.openAuthDialog().then(() => {
                    // The player is logged in
                    initPlayer().catch(err => {
                        // Error initializing the Player object.
                    });
                }).catch(() => {
                    //  Player not logged in.
                });
        }
    }).catch(err => {
        // Error initializing the Player object.
    });

In-game data

To work with the user's in-game data, use the Player object methods:

  • player.setData(data, flush): Saves the user data. The maximum data size must not exceed 200 KB.

    • data: Object, an object containing key-value pairs.
    • flush: Boolean, determines the order data is sent in. If the value is "true", the data is immediately sent to the server. If it's "false" (default), the request to send data is queued.

    The method returns a Promise that indicates whether the data was saved or not.

    At flush: false, the returned result only shows the data validity (the data has been queued and will be sent later). At the same time, the player.getData() method will return the data set by the last player.setData() call, even if it has not been sent yet.

    player.setData({
            achievements: ['trophy1', 'trophy2', 'trophy3'],
        }).then(() => {
            console.log('data is set');
        });
    
    
  • player.getData(keys): Asynchronously returns in-game user data stored in the Yandex database.

    • keys: Array<string>, the list of keys to return. If the keys parameter is missing, the method returns all in-game user data.

    The method returns Promise<Object>, where the object contains key-value pairs.

  • player.setStats(stats): Saves the user's numeric data. The maximum data size must not exceed 10 KB.

    • stats: Object, an object containing key-value pairs, where each value must be a number.

    The method returns a Promise that indicates whether the data was saved or not.

    Tip

    For frequently changing numeric values (points, experience, in-game currency) use this method instead of player.setData().

  • player.incrementStats(increments): Changes in-game user data. The maximum data size must not exceed 10 KB.

    • increments: Object, an object containing key-value pairs, where each value must be a number.

    The method returns Promise<Object>, where the object contains modified and added key-value pairs.

  • player.getStats(keys): Asynchronously returns the user's numeric data.

    • keys: Array<string>, the list of keys to return. If the keys parameter is missing, the method returns all in-game user data.

    The method returns Promise<Object>, where the object contains key-value pairs.

User profile data

To get data from the Yandex user profile, use the Player object methods:

  • player.getUniqueID(): Returns the user's unique permanent ID (string type).

    Note

    The previously used player.getID() method has been deprecated but still supported for now, throwing a warning in the error console.

    The values of player.getID() and player.getUniqueID() are generally not the same for a given Player object, but they might be the same for some users. If the values differ and the game itself already linked some data to the player.getID() value, you need to migrate this data and link it to the value of player.getUniqueID(). To migrate the data for all users at once, contact support.

  • player.getIDsPerGame(): Returns a Promise<Array> with the user IDs for all of the developer's games in which they have explicitly granted access to their personal data. For example:

    [
        { appID: 103915, userID: "tOpLpSh7i8QG8Voh/SuPbeS4NKTj1OxATCTKQF92H4c=" },
        { appID: 103993, userID: "bviQCIAAuVmNMP66bZzC4x+4oSFzRKpteZ/euP/Jwv4=" }
    ]
    

    Alert

    The request is available only for authorized users. If necessary, use authorization.

    To check whether the method is available for the user, you can use the ysdk.isAvailableMethod('player.getIDsPerGame') method. It returns Promise<Boolean>, where the boolean value indicates the method's availability.

  • player.getName(): Returns the user's name (string type).

  • player.getPhoto(size): returns the URL of the user's avatar (string type).

    • size: String, the required size. Acceptable values: small, medium, large.

Progress loss on iOS

If the game is integrated via iframe, localStorage may often reset on new iOS versions, causing players to lose their progress. To avoid this, use safeStorage, which has the same interface as localStorage:

ysdk.getStorage().then(safeStorage => {
        safeStorage.setItem('key', 'safe storage is working');
        console.log(safeStorage.getItem('key'))
    })

To avoid manually changing the code, override localStorage globally.

Alert

Make sure that localStorage isn't used before you override it.

ysdk.getStorage().then(safeStorage => Object.defineProperty(window, 'localStorage', { get: () => safeStorage }))
    .then(() => {
        localStorage.setItem('key', 'safe storage is working');
        console.log(localStorage.getItem('key'))
    })

If you are uploading the source code as an archive, you don't need to do anything: a special wrapper in the SDK automatically makes localStorage reliable.


Note

Our support team can help publish finished games or WebApps on Yandex Games. If you have any questions about development or testing, ask them in the Discord channel.

If you are facing an issue or have a question regarding the use of Yandex Games SDK, please contact support:

Write to chat