Player data

You can save the player's game state data (such as completed levels, experience, or in-game purchases) on the Yandex server or send this data to your 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.
    });

When initializing the Player object:

  • The user ID is passed.

  • The logged-in users are asked for the access to:

    • Their profile picture and name.
    • Their purchase data on the platform (only for users from the Russian Federation and if you offer in-game purchases).

    Sample consent for a logged-in user: "I hereby consent to the game using the photo and name from my Yandex account as well as sharing the data on purchases made with in-game currency with the game developer."

  • Users from the Russian Federation who aren't logged in are asked to provide access to their purchase data on the platform (only for games that feature purchases).

If you need the ID without the username and profile picture, use the optional scopes: false parameter. In this case, the dialog box requesting access 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 use the optional signed: true parameter and the fetch() method to log the user in and save their 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 for sending data. 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.

Limitations on the number of requests

  • player.setData(), player.getData(): 100 requests in five minutes.
  • player.setStats(), player.getStats(): 60 requests per minute.
  • player.incrementStats(): 60 requests per minute.

Note

If you need more requests for your project, message us in the chat.

User profile data

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

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

    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() (string): Returns the user's name.

  • player.getPhoto(size) (string): Returns the URL of the user's profile picture.

    • size (string): Required size. Supported values are: small, medium, large.
  • player.getPayingStatus() (string): Returns the four possible values depending on the user's purchase frequency and amount:

    • paying: The user purchased the portal currency for more than ₽500 in the last month.
    • partially_paying: The user purchased the portal currency with real money at least once in the last year.
    • not_paying: The user didn't purchase the portal currency with real money in the last year.
    • unknown: The user is not from the Russian Federation or didn't give their consent to share this information with the developer.

    Sample use:

    const ysdk = await YaGames.init(); // Initializing the SDK.
    const player = await ysdk.getPlayer(); // Retrieving the player.
    const payingStatus = player.getPayingStatus(); // Fetching the user's payment activity status on the platform.
    
    if (payingStatus === 'paying' || payingStatus === 'partially_paying') {
        // Offer in-app goods at startup or instead of ads.
    }
    

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