In-game purchases
You can generate revenue by offering users the option to make in-game purchases. For example, they can buy extra time for completing a level or accessories for their character. To do this:
- Enable in-game purchases in the Yandex Games Console.
- Configure the SDK to work with purchases.
- Add a check for pending purchases.
- Test your purchases.
Alert
You can only test purchases after enabling their consumption. Otherwise, you might end up with unprocessed payments, making it impossible to pass moderation.
Portal currency
Players can use portal currency of the Yandex Games platform to pay for in-game purchases. This currency is stored on the player's account balance. A player can top up their balance with a bank card and use it for all their games. The exchange rate of the portal currency to rubles is dynamic.
Note
For international payments, the exchange rate of the portal currency to the national currency depends on the player's country.
Players can top up their balance:
- In the catalog header.
- In the player profile.
- When making an in-game purchase.
Users can also earn the portal currency as bonus rewards for participating in promos or purchasing fixed packages.
Both authorized and unauthorized Yandex users can make in-game purchases. Users can log in directly during the game, including at the time of making a purchase.
The introduction of the portal currency will not affect the terms and conditions for paying the licensing revenue to developers.
Conditions
After you added purchases and published the game draft, send the request to enable purchases to games-partners@yandex-team.com. Be sure to include your game's name and ID in the email.
After you receive the confirmation from games-partners@yandex-team.com saying that the purchases are enabled, you can configure and test them.
Initialization
To allow users to make in-game purchases, use the payments
object.
var payments = null;
ysdk.getPayments({ signed: true }).then(_payments => {
// Purchases are available.
payments = _payments;
}).catch(err => {
// Purchases are unavailable. Enable monetization in the Games Console.
// Make sure the Purchases tab in the Games Console features a table
// with at least one in-game product and the "Purchases are allowed" label.
})
signed: true
: Optional parameter. Returns the signature parameter in the methods payments.getPurchases()
and payments.purchase()
. It serves to protect the game from fraudulent activity.
Activating the purchase process
You can activate an in-game purchase using the following method:
payments.purchase({ id, developerPayload })
id
(string): Product ID set in the Games Console.developerPayload
(string): Optional parameter. Additional purchase data that you want to send to your server (transferred in the signature parameter).
The method opens a frame with a payment gateway. Returns Promise<Purchase>
.
Purchase
(object): Includes purchase details. It contains the following properties:
productID
(string): Product ID.purchaseToken
(string): A token for consuming the purchase.developerPayload
(string): Additional purchase data.signature
(string): Purchase data and the signature for player authentication.
After the player successfully makes a purchase, Promise
switches to the "resolved" state. If the player didn't make a purchase and closed the window, the Promise
state becomes "rejected".
Alert
Unstable internet connection may cause successful purchases not being registered by the game. To avoid this, use the methods described in the sections Checking for unprocessed purchases and Processing purchases and crediting in-game currency.
Failure to follow these instructions may result in the disabling of purchases in the app or in the app's depublishing.
If the player is not logged in to Yandex at the time of purchase, the log in window appears. You can also prompt the user to log in in advance.
Example
General:
payments.purchase({ id: 'gold500' }).then(purchase => {
// Purchase successful!
}).catch(err => {
// Purchase failed: no product with this id exists in the Games Console,
// the user didn't log in, changed their mind, and closed the payment window,
// the purchase timed out, there were insufficient funds, or for any other reason.
})
Using the optional developerPayload
parameter:
payments.purchase({ id: 'gold500', developerPayload: '{serverId:42}' }).then(purchase => {
// purchase.developerPayload === '{serverId:42}'
})
Getting a list of purchased items
To find out what purchases the player has already made, use the method:
payments.getPurchases()
The method returns Promise<Purchase[]>
.
Purchase[]
(array): The list of purchases made by the player. The list has the following property:
signature
(string): Purchase data and the signature for player authentication.
Each Purchase
purchase contains the following properties:
productID
(string): Product ID.purchaseToken
(string): A token for consuming the purchase.developerPayload
(string): Additional purchase data.
Example
var SHOW_ADS = true;
payments.getPurchases().then(purchases => {
if (purchases.some(purchase => purchase.productID === 'disable_ads')) {
SHOW_ADS = false;
}
}).catch(err => {
// Throws the USER_NOT_AUTHORIZED exception for logged off users.
})
Getting the catalog of all products
To get a list of available purchases and their cost, use the payments.getCatalog()
method.
The method returns Promise<Product[]>
.
Product[]
(object): The list of products available to the user. This list is generated from the table in the Purchases tab of the Games Console. Each Product
contains the following properties:
id
(string): Product ID.title
(string): Product name.description
(string): Product description.imageURI
(string): Image URL.price
(string): Product price in<price> <currency code>
format.priceValue
(string): Product price in<price>
format.priceCurrencyCode
(string): Currency code.
Product.getPriceCurrencyImage(size)
— method to obtain the currency icon address.
-
size
— string — optional parameter. Possible values:-
small
(by default) - getting a small icon. -
medium
— obtaining an icon of medium size. -
svg
— obtaining the icon in vector format.
-
The method returns a string — the address of the icon, for example //yastatic.net/s3/games-static/static-data/images/payments/sdk/currency-icon-s@2x.png
.
Example
var gameShop = []
payments.getCatalog().then(products => {
gameShop = products;
});
Portal currency display
To display the name and icon of the portal currency in the game, use the SDK features:
Product.price
(string): Price with the currency code.Product.priceCurrencyCode
(string): Currency code.Product.getPriceCurrencyImage()
(string): URL of the currency icon.
For more details on the Product
object, see Getting the catalog of all products.
Processing purchases and crediting in-game currency
There are two types of purchases: non-consumables (such as for disabling ads) and consumables (such as for buying in-game currency).
To process non-consumable purchases, use the method payments.getPurchases()
.
To process consumable purchases, use the method payments.consumePurchase()
.
payments.consumePurchase()
The method returns a Promise
in the "resolved" state (if the processing is successful) or "rejected" state (if an error occurs).
Alert
After calling the payments.consumePurchase()
method, the processed purchase is permanently deleted. To account for this, you should first modify the player data using the player.setStats()
or player.incrementStats()
method and then process the purchase.
Example
payments.purchase({ id: 'gold500' }).then(purchase => {
// Purchase successful!
// Adding 500 gold to the account and consuming the purchase.
addGold(500).then(() => payments.consumePurchase(purchase.purchaseToken));
});
function addGold(value) {
return player.incrementStats({ gold: value });
// To learn more, see Player data.
}
purchaseToken
(string): A token returned by the payments.purchase()
and payments.getPurchases()
methods.
Checking for unprocessed purchases
If the user loses internet connection when making an in-game purchase, or your server becomes unavailable, the purchase might remain unprocessed. To avoid this, check for unprocessed purchases using the method payments.getPurchases()
(e.g., each time the game is launched).
Alert
Before adding purchases, please configure unprocessed payments verification.
This verification is mandatory for passing moderation, so it's crucial to set it up even for test purchases. If you add purchases to the game and test them before configuring consumption, unprocessed payments could remain after the tests, making passing moderation impossible.
Example for a game whose data is stored on the Yandex server
payments.getPurchases().then(purchases => purchases.forEach(consumePurchase));
function consumePurchase(purchase) {
if (purchase.productID === 'gold500') {
player.incrementStats({ gold: 500 }).then(() => {
payments.consumePurchase(purchase.purchaseToken)
});
}
}
Example for a game whose data is stored on the developer's server
payments.getPurchases().then(purchases => {
fetch('https://your.game.server?purchase', {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
body: purchases.signature
});
});
Fraud prevention
To protect yourself from game metrics fraud, use the serverPurchase(signature)
function for processing purchases instead of player.setStats()
or player.incrementStats()
.
Alert
The serverPurchase(signature)
function requires that you configure saving of the game data on the developer's server and initialize purchases with the signed: true
parameter.
// Make sure that purchases are initialized with the { signed: true } parameter
payments.purchase({ id: 'gold500' }).then(purchase => {
// Purchase successful!
// Adding 500 gold on the server...
serverPurchase(purchase.signature.slice(1)); // fail: Check the signature.
serverPurchase(purchase.signature); // ok: Purchase confirmed.
serverPurchase(purchase.signature); // fail: Make sure the purchase is unique.
});
function serverPurchase(signature) {
return fetch('https://your.game.server?purchase', {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
body: signature
});
}
The signature
parameter of the request delivered to the server contains purchase data and the signature. It's two strings in base64
encoding:<signature>.<JSON with the purchase data>
.
Signature example
hQ8adIRJWD29Nep+0P36Z6edI5uzj6F3tddz6Dqgclk=.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZEF0IjoxNTcxMjMzMzcxLCJyZXF1ZXN0UGF5bG9hZCI6InF3ZSIsImRhdGEiOnsidG9rZW4iOiJkODVhZTBiMS05MTY2LTRmYmItYmIzOC02ZDJhNGNhNDQxNmQiLCJzdGF0dXMiOiJ3YWl0aW5nIiwiZXJyb3JDb2RlIjoiIiwiZXJyb3JEZXNjcmlwdGlvbiI6IiIsInVybCI6Imh0dHBzOi8veWFuZGV4LnJ1L2dhbWVzL3Nkay9wYXltZW50cy90cnVzdC1mYWtlLmh0bWwiLCJwcm9kdWN0Ijp7ImlkIjoibm9hZHMiLCJ0aXRsZSI6ItCR0LXQtyDRgNC10LrQu9Cw0LzRiyIsImRlc2NyaXB0aW9uIjoi0J7RgtC60LvRjtGH0LjRgtGMINGA0LXQutC70LDQvNGDINCyINC40LPRgNC1IiwicHJpY2UiOnsiY29kZSI6IlJVUiIsInZhbHVlIjoiNDkifSwiaW1hZ2VQcmVmaXgiOiJodHRwczovL2F2YXRhcnMubWRzLnlhbmRleC5uZXQvZ2V0LWdhbWVzLzE4OTI5OTUvMmEwMDAwMDE2ZDFjMTcxN2JkN2EwMTQ5Y2NhZGM4NjA3OGExLyJ9fX0=
JSON
format)
Example of transmitted purchase data (in Note that the data format of the signature
parameter used in the serverPurchase(signature)
function is different from the format used in the payments.getPurchases()
method.
In the payments.getPurchases()
method, the signature
parameter contains an array of purchase objects in the data
field. In the serverPurchase(signature)
function, it's the purchase object.
{
"algorithm": "HMAC-SHA256",
"issuedAt": 1571233371,
"requestPayload": "qwe",
"data": {
"token": "d85ae0b1-9166-4fbb-bb38-6d2a4ca4416d",
"status": "waiting",
"errorCode": "",
"errorDescription": "",
"url": "https://yandex.ru/games/sdk/payments/trust-fake.html",
"product": {
"id": "noads",
"title": "No ads",
"description": "Disable ads in the game",
"price": {
"code": "YAN",
"value": "49"
},
"imagePrefix": "https://avatars.mds.yandex.net/get-games/1892995/2a0000016d1c1717bd7a0149ccadc86078a1/"
},
"developerPayload": "TEST DEVELOPER PAYLOAD"
}
}
Secret key example
t0p$ecret
The secret key for signature verification is unique for the game. It is generated automatically when creating purchases in the Games Console. You can find it under the purchase table.
Example of signature verification on the server
import hashlib
import hmac
import base64
import json
usedTokens = {}
key = 't0p$ecret' # Keep the key secret.
secret = bytes(key, 'utf-8')
signature = 'hQ8adIRJWD29Nep+0P36Z6edI5uzj6F3tddz6Dqgclk=.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZEF0IjoxNTcxMjMzMzcxLCJyZXF1ZXN0UGF5bG9hZCI6InF3ZSIsImRhdGEiOnsidG9rZW4iOiJkODVhZTBiMS05MTY2LTRmYmItYmIzOC02ZDJhNGNhNDQxNmQiLCJzdGF0dXMiOiJ3YWl0aW5nIiwiZXJyb3JDb2RlIjoiIiwiZXJyb3JEZXNjcmlwdGlvbiI6IiIsInVybCI6Imh0dHBzOi8veWFuZGV4LnJ1L2dhbWVzL3Nkay9wYXltZW50cy90cnVzdC1mYWtlLmh0bWwiLCJwcm9kdWN0Ijp7ImlkIjoibm9hZHMiLCJ0aXRsZSI6ItCR0LXQtyDRgNC10LrQu9Cw0LzRiyIsImRlc2NyaXB0aW9uIjoi0J7RgtC60LvRjtGH0LjRgtGMINGA0LXQutC70LDQvNGDINCyINC40LPRgNC1IiwicHJpY2UiOnsiY29kZSI6IlJVUiIsInZhbHVlIjoiNDkifSwiaW1hZ2VQcmVmaXgiOiJodHRwczovL2F2YXRhcnMubWRzLnlhbmRleC5uZXQvZ2V0LWdhbWVzLzE4OTI5OTUvMmEwMDAwMDE2ZDFjMTcxN2JkN2EwMTQ5Y2NhZGM4NjA3OGExLyJ9fX0='
sign, data = signature.split('.')
message = base64.b64decode(data)
purchaseData = json.loads(message)
result = base64.b64encode(hmac.new(secret, message, digestmod=hashlib.sha256).digest())
if result.decode('utf-8') == sign:
print('Signature check ok!')
if not purchaseData['data']['token'] in usedTokens:
usedTokens[purchaseData['data']['token']] = True; # Use database.
print('Double spend check ok!')
print('Apply purchase:', purchaseData['data']['product'])
# You can safely apply purchases here.
const crypto = require('crypto');
const usedTokens = {};
const key = 't0p$ecret'; // Keep the key secret.
const signature = 'hQ8adIRJWD29Nep+0P36Z6edI5uzj6F3tddz6Dqgclk=.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZEF0IjoxNTcxMjMzMzcxLCJyZXF1ZXN0UGF5bG9hZCI6InF3ZSIsImRhdGEiOnsidG9rZW4iOiJkODVhZTBiMS05MTY2LTRmYmItYmIzOC02ZDJhNGNhNDQxNmQiLCJzdGF0dXMiOiJ3YWl0aW5nIiwiZXJyb3JDb2RlIjoiIiwiZXJyb3JEZXNjcmlwdGlvbiI6IiIsInVybCI6Imh0dHBzOi8veWFuZGV4LnJ1L2dhbWVzL3Nkay9wYXltZW50cy90cnVzdC1mYWtlLmh0bWwiLCJwcm9kdWN0Ijp7ImlkIjoibm9hZHMiLCJ0aXRsZSI6ItCR0LXQtyDRgNC10LrQu9Cw0LzRiyIsImRlc2NyaXB0aW9uIjoi0J7RgtC60LvRjtGH0LjRgtGMINGA0LXQutC70LDQvNGDINCyINC40LPRgNC1IiwicHJpY2UiOnsiY29kZSI6IlJVUiIsInZhbHVlIjoiNDkifSwiaW1hZ2VQcmVmaXgiOiJodHRwczovL2F2YXRhcnMubWRzLnlhbmRleC5uZXQvZ2V0LWdhbWVzLzE4OTI5OTUvMmEwMDAwMDE2ZDFjMTcxN2JkN2EwMTQ5Y2NhZGM4NjA3OGExLyJ9fX0=';
const [sign, data] = signature.split('.');
const purchaseDataString = Buffer.from(data, 'base64').toString('utf8');
const hmac = crypto.createHmac('sha256', key);
hmac.update(purchaseDataString);
const purchaseData = JSON.parse(purchaseDataString);
if (sign === hmac.digest('base64')) {
console.log('Signature check ok!');
if (!usedTokens[purchaseData.data.token]) {
usedTokens[purchaseData.data.token] = true; // Use database.
console.log('Double spend check ok!');
console.log('Apply purchase:', purchaseData.data.product);
// You can safely apply purchases here.
}
}
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:
signed: true
: Optional parameter. Returns the signature
parameter in the methods payments.getPurchases()
and payments.purchase()
. It serves to protect the game from fraudulent activity.
signature
(string): Purchase data and signature for player authentication.
id
(string): Product ID set in the Games Console.
developerPayload
(string): Optional parameter. Additional purchase data that you want to send to your server (transferred in the signature
parameter).
The signature
parameter in the request sent to the server contains the purchase data and the signature. It's two strings in base64
encoding:<signature>.<JSON with the purchase data>
.
purchaseToken
(string): A token returned by the payments.purchase()
and payments.getPurchases()
methods.