Player data

You can save game data (completed levels, experience, in-app purchases, etc.) on the Yandex server or send it to your server, and also personalize the game using data from the user's Yandex profile, such as their name.

To work with user data, use the Player object.

Initialization

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

1const ysdk = await YaGames.init();
2
3try {
4    const player = await ysdk.getPlayer();
5} catch (e) {
6    // Error initializing the Player object.
7}

When initializing a Player object, the following data is passed:

  • User ID — for all players.
  • Avatar and name — for authorized players.
  • Platform purchase data (only for games with in-app purchases) — for players from Russia.

For more information about these parameters, see User profile data.

Access to user data depends on settings in their profile. If a player restricts access to personal data, only the ID will be included in the response.

To authorize a user and save game state data on your server, you can use the optional signed: true parameter and the fetch() method. This allows you to use the signature to verify player authenticity and prevent potential fraud.

 1const ysdk = await YaGames.init();
 2
 3try {
 4    const player = await ysdk.getPlayer({ signed: true });
 5
 6    // Use player.signature for authorization on your server.
 7    const authData = await fetch('https://your.game.server/auth', {
 8        method: 'POST',
 9        headers: { 'Content-Type': 'text/plain' },
10        body: player.signature
11    });
12} catch (e) {
13    // Error initializing the Player object or during authorization.
14}

The signature parameter of the request sent to the server contains user data from the Yandex profile and the signature. The parameter represents two strings in base64 encoding:

<signature>.<profile data>

For more information, see Fraud prevention.

Note

Requests can be sent no more than 20 times within 5 minutes, otherwise they will be rejected with an error.

User authorization

Verifying authorization

To check if a player is authorized in Yandex, use the Player object method player.isAuthorized(). The method returns true | false.

Alert

The player.getMode(): 'lite' | '' method is deprecated and will be removed from the interface later.

Calling the authorization dialog box

To call the authorization window, use the ysdk.auth.openAuthDialog() method.

Tip

Inform the user about the advantages of authorization. If the user doesn't understand why it's needed, they will most likely refuse to authorize and exit the game.

 1const ysdk = await YaGames.init();
 2
 3try {
 4    let player = await ysdk.getPlayer();
 5
 6    // Player is not authorized.
 7    if (!player.isAuthorized()) {
 8        try {
 9            // Opening the authorization window.
10            await ysdk.auth.openAuthDialog();
11
12            const authorizedPlayer = await ysdk.getPlayer();
13
14            player = authorizedPlayer;
15        } catch (e) {
16            // Error during player authorization or re-initialization of the Player object.
17        }
18    }
19    // Player successfully authorized.
20} catch (err) {
21    // Error initializing the Player object.
22}

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 per player is 200 KB.

Method signature:

function setData(data: object, flush: boolean) => Promise<void> {}

Accepts parameters:

Parameter

Type

Description

data

object

An object containing key-value pairs.

flush

boolean

Determines the order of data transmission:

  • true — data will be sent to the server immediately.
  • false (default value) — the data transmission request will be 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.

Note

Requests can be sent no more than 100 times within 5 minutes, otherwise they will be rejected with an error.

Example

1const ysdk = await YaGames.init();
2
3const player = await ysdk.getPlayer();
4
5await player.setData({
6    achievements: ['trophy1', 'trophy2', 'trophy3'],
7})
8
9console.log('data is set');

player.getData(keys)

Asynchronously returns in-game user data stored in the Yandex database.

Method signature:

function getData(keys?: Array<string>) => Promise<object> {}

Accepts parameter:

Parameter

Type

Description

keys

Array<string>

A list of keys to be returned. If the keys parameter is missing, the method returns all in-game user data.

The method returns Promise<object>, which contains key-value pairs.

Note

Requests can be sent no more than 100 times within 5 minutes, otherwise they will be rejected with an error.

player.setStats(stats)

Saves the user's numeric data. The maximum numeric data size per player is 10 KB.

Tip

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

Method signature:

function setStats(stats?: object) => Promise<void> {}

Accepts parameter:

Parameter

Type

Description

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.

Note

Requests can be sent no more than 60 times per minute, otherwise they will be rejected with an error.

player.incrementStats(increments)

Changes the user's numeric data. The maximum numeric data size per player is 10 KB.

Method signature:

function incrementStats(increments: object) => Promise<object> {}

Accepts parameter:

Parameter

Type

Description

increments

object

An object containing key-value pairs, where each value must be a number.

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

Note

Requests can be sent no more than 60 times per minute, otherwise they will be rejected with an error.

player.getStats(keys)

Asynchronously returns the user's numeric data.

Method signature:

function getStats(keys?: Array<string>) => Promise<object> {}

Accepts parameter:

Parameter

Type

Description

keys

Array<string>

A list of keys to be returned. If the keys parameter is missing, the method returns all numerical user data.

The method returns Promise<object>, which contains key-value pairs.

Note

Requests can be sent no more than 60 times per minute, otherwise they will be rejected with an error.

User profile data

To get data from the user's Yandex profile, use the Player object methods.

player.getUniqueID()

Returns the user's permanent unique ID.

Method signature:

function getUniqueID() => string {}

Note

The player.getID() method is deprecated but will continue to work with a warning in the error console.

The values of player.getID() and player.getUniqueID() generally do not match for the same Player object, but they might be the same for some users. If the values differ and the game previously linked any data to the player.getID() value, migrate this data by linking it to the value of player.getUniqueID(). To migrate the data for all users at once, contact support.

player.getIDsPerGame()

Alert

The request is available only for authorized users. For information on how to check authorization status and call the login dialog, see User authorization.

Before sending the request, check method availability using ysdk.isAvailableMethod('player.getIDsPerGame'). The method returns Promise<Boolean>.

The method returns an array of objects with user IDs for all of the developer's games in which the user has explicitly granted access to their personal data.

Method signature:

function getIDsPerGame() => Promise<Array<{ appID: number, userID: string }>> {}

player.getName()

Returns the user's name.

Method signature:

function getName() => string {}

player.getPhoto()

Returns the URL of the user's avatar depending on the requested image size.

Method signature:

function getPhoto(size: 'small' | 'medium' | 'large') => string {}

player.getPayingStatus()

Returns a value depending on the user's purchase frequency and amount.

Method signature:

function getPayingStatus() => EPayingStatus {}

EPayingStatus takes one of the following values:

Value

Description

paying

The user has purchased platform currency for more than 500 rubles in the last month.

partially_paying

The user has made at least one purchase of platform currency with real money in the last year.

not_paying

The user has not made any purchases of platform currency with real money in the last year.

unknown

The user is not from Russia or has not allowed such information to be shared with the developer.

Example

1const ysdk = await YaGames.init(); // Initialize the SDK.
2const player = await ysdk.getPlayer(); // Get the player.
3const payingStatus = player.getPayingStatus(); // Get the user's payment activity status on the platform.
4
5if (payingStatus === 'paying' || payingStatus === 'partially_paying') {
6    // Offer in-app goods at startup or instead of ads.
7}

Method limitations

Method

Description

Limit

ysdk.getPlayer()

Initializes the Player object

20 requests per 5 minutes

player.setData()

Saves the user data

100 requests per 5 minutes

player.getData()

Asynchronously returns in-game user data

player.setStats()

Saves the numerical user data

60 requests per 1 minute

player.getStats()

Asynchronously returns the numerical user data

player.incrementStats()

Changes the numerical user data

Progress loss on iOS

If you use your own domain for game integration, 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:

1const ysdk = await YaGames.init();
2
3const safeStorage = await ysdk.getStorage();
4
5safeStorage.setItem('key', 'safe storage is working');
6console.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.

1const ysdk = await YaGames.init();
2
3const safeStorage = await ysdk.getStorage();
4
5Object.defineProperty(window, 'localStorage', { get: () => safeStorage });
6
7localStorage.setItem('key', 'safe storage is working');
8console.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 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