# In-game purchases

**Purpose:** the store module (`SDK.store`) lets a signed-in player buy items from inside your game. A game is the whole product you uploaded; an item here is one product you sell inside it. You define products in the developer console, the portal shows its own checkout dialog, and the purchased items land in the player's inventory, where your game reads and consumes them.

> [!IMPORTANT]
> **Real money is not available yet** (status: in testing, no real money yet; see [feature status](https://docs.zokogames.com/business/faq#feature-status)). Real-money sales are switched off on the portal for now (the payment provider is integrated, but the portal team has not switched real money on), so every purchase today is a **test purchase** in sandbox mode: no money moves and players see a "Test purchase" badge. Build and test your whole flow now; the code does not change when real payments are switched on. See [provider not connected](#provider-not-connected).

## At a glance

Every member of `SDK.store`, with its signature and the SDK version that added it. The sections below describe each call's errors and how it behaves in local mode, for guests and offline.

| Signature | Resolves to | Can fail with | Since |
| --- | --- | --- | --- |
| `readonly isAvailable: boolean` | `true` when this game can sell items here. Synchronous. | Throws `sdkNotInitialized` or `sdkDisabled`. | 1.1.0 |
| `getCatalogItems(options?: StorePageOptions): Promise<StoreItem[]>` | One page of active products. | `invalidArgument`, `requestInProgress`, `catalogFetchFailed`, `unexpectedError`, `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.1.0 |
| `getPlayerInventory(options?: StorePageOptions): Promise<InventoryItem[]>` | One page of what the signed-in player owns. | `invalidArgument`, `requestInProgress`, `userNotAuthenticated`, `inventoryFetchFailed`, `unexpectedError`, `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.1.0 |
| `buyItem(itemId: string): Promise<{ itemId: string }>` | `{ itemId }` once the order is paid. No timeout. | `invalidArgument`, `purchaseInProgress`, `userNotAuthenticated`, `purchaseInitFailed`, `purchaseCancelled`, `unexpectedError`, `sdkNotInitialized`, `sdkDisabled`. | 1.1.0 |
| `consumeItem(sku: string, quantity: number): Promise<void>` | Nothing, when the units were removed. | `invalidArgument`, `requestInProgress`, `userNotAuthenticated`, `itemNotInInventory`, `itemNotConsumable`, `insufficientItemQuantity`, `consumeItemFailed`, `unexpectedError`, `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.1.0 |
| `setSandbox(sandbox: boolean): void` | Nothing. | Throws `invalidArgument` (not a boolean), `sdkNotInitialized`, `sdkDisabled`. | 1.1.0 |
| `getPurchaseToken(): Promise<string>` | A signed RS256 token listing the player's items and orders. Not cached. | `userNotAuthenticated`, `rateLimited`, `unexpectedError`, `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.1.0 |

`StorePageOptions` is `{ limit?: number; offset?: number }`. The types `StoreApi`, `StoreItem` and `InventoryItem` are in the declaration file described in the SDK introduction.

## How it works

1. You enable the store and add products in the console.
2. Your game checks `SDK.store.isAvailable`, lists the catalogue with `getCatalogItems()` and starts a purchase with `buyItem(sku)`.
3. The portal opens a checkout dialog over the game, charges the payment provider and fulfils the order.
4. Your game reads `getPlayerInventory()`, grants what the player bought and calls `consumeItem()` for consumables it has used up.
5. For anything that matters (progress on your own backend, items worth real value) your server verifies a signed [purchase token](#verifying-a-purchase-on-your-server) instead of trusting the browser.

Purchases need a signed-in player, because an order must belong to an account. Guests can browse the catalogue but get `userNotAuthenticated` for everything else. See the [user module](https://docs.zokogames.com/sdk/user#sign-in-prompt) for `showAuthPrompt`.

## Lifecycle

```text
init() resolves
  -> SDK.store.isAvailable?  no -> hide every purchase button
  -> (optional) setSandbox(true) before the first store call
  -> getCatalogItems()            shop list, works for guests
  -> getPlayerInventory()         signed-in players only
  -> player presses buy -> buyItem(sku)     checkout dialog; resolves when paid
  -> getPlayerInventory()         refresh, grant the effect
  -> consumeItem(sku, qty)        consumables only, after the effect is granted
  -> (your server) getPurchaseToken() -> verify -> grant once per order id
```

## Enable the store and sandbox mode

Open your game in the developer console and go to the **Store** page. Owners and admins can change it; other roles see it read only.

| Setting | Meaning |
| --- | --- |
| **Store enabled** | Master switch for your game. When on **and** at least one product is active, `SDK.store.isAvailable` is `true`. |
| **Payment mode** | **Sandbox (test purchases)** settles orders instantly without money. **Real money** is selectable only once the portal switches real-money sales on, which is not the case yet; until then the console shows "Payment provider not connected" and saving it fails with "Real-money mode needs a connected payment provider" (code `providerNotConnected`). |

The store is off by default for a new game, and the portal can also switch purchases off for every game at once; the page then shows "Disabled by the portal" and keeps your settings.

A game marked **Made for children** never sells: the Store page says so instead of "Selling to players", players are refused and `SDK.store.isAvailable` is `false`. Your products are kept if you untick the box later.

Players can buy only in a game that is live. Members of your studio can test earlier, in preview, using the same store.

> [!NOTE]
> `isAvailable` is read once when the game starts. If you enable the store or add your first product while the game is open, reload the game.

The **In-game purchases** badge on your game's cards and game page does not come from this page or from SDK calls. It follows **Contains in-game purchases** under **Video and multiplayer extras** on the **Technical** step, which you tick yourself whenever players can spend real money in the game; when the game has store products and the box is not ticked, the console suggests ticking it. A game made for children never shows the badge, and the box cannot be ticked for it. On a card the badge appears only when the card shows no other badge.

## Create products

On the **Store** page choose **New product**.

| Field | Rules |
| --- | --- |
| **Sku** | 1 to 64 characters: lowercase letters, digits, `.`, `-`, `_`, starting with a letter or digit. This is the id your game uses in `buyItem` and `consumeItem`; pass it exactly as saved, in lowercase (the console lowercases capitals you type, your game's code does not). Unique per game. After saving, the product's row in the table has a copy button that puts `await SDK.store.buyItem("your-sku");` on your clipboard. |
| **Name** | English name required (80 characters). Add translations with a locale code such as `de` or `pt-BR`. Players see the closest match to their language, then English. |
| **Description** | Optional, 500 characters per language. |
| **Type** | **Consumable** or **Durable**, see [below](#consumables-and-durables). |
| **Price and currency** | A price above zero, entered as a normal amount such as `1.99`. Currencies: USD, EUR, GBP, CAD, AUD, BRL, MXN, PLN, SEK, NOK, DKK, CHF, TRY, INR, JPY and KRW. JPY and KRW have no decimals. |
| **Units per purchase** | 1 to 100,000. How many units one purchase adds to the inventory. A durable item is always 1. |
| **Image URL** | Optional `https` image shown in the checkout and returned as `imageUrl`. |
| **Order** | 0 to 9,999. Items are listed by this number, then by sku. |
| **Active** | Inactive products are hidden from the catalogue and cannot be bought. Players keep what they already own. |

A game can list up to 200 products; the Products table shows how many you use and **New product** is disabled at the limit. Subscriptions do not exist. Once a product has any order, its sku cannot change and it cannot be deleted: deactivate it instead.

**Editing and deleting products.**

Only the studio's owners and admins can create, edit, activate, deactivate or delete products; other roles see the table read only. Every change is written to the studio's audit trail. There is no bulk import or export of products: add them one at a time in the console (the **Orders** table has its own CSV export).

- **Checks.** The form validates when you press **Save product** and puts the cursor on the first field to fix; the server checks again. Capitals in a sku are lowercased when saving. For JPY, KRW and portal coins the price is a whole number.
- **The sku is the product's id.** Your game's `buyItem` and `consumeItem` calls and every order and inventory row use it. It can be changed only while the product has no orders. After the first order, to retire a sku you deactivate it and add a new product.
- **Other fields can be edited at any time.** Names, description, image, order and active apply at once to the catalogue. Orders already placed keep the amount they were charged. Players keep every unit they own.
- **Changing the type of a product that has been sold changes how the units already owned behave** (a durable cannot be consumed with `consumeItem`; a consumable can be bought again). Add a new product instead of changing the type of one that has sold.
- **Deactivate or delete.** Deactivating hides the product from `getCatalogItems()` and a `buyItem` for it fails; owned units stay in inventories and `consumeItem` still works on them. Deleting is possible only for a product with no orders, and cannot be undone. A deleted sku behaves like one that never existed (`itemNotInInventory`, or a failed `buyItem`).

## Consumables and durables

| | Consumable | Durable |
| --- | --- | --- |
| Examples | Coins, gems, extra lives. | Remove ads, a character, a level pack. |
| Can be bought again | Yes, quantities add up. | No. A second purchase fails with a message that the player already owns it. |
| `consumeItem` | Allowed. | Fails with `itemNotConsumable`. |
| Inventory `quantity` | Total units owned. | `1`. |

## SDK reference

The module is `SDK.store`. Each call returns a promise and rejects with an error whose `code` is one of the [error codes](#error-codes).

```ts
readonly isAvailable: boolean
getCatalogItems(options?: { limit?: number; offset?: number }): Promise<StoreItem[]>
getPlayerInventory(options?: { limit?: number; offset?: number }): Promise<InventoryItem[]>
buyItem(itemId: string): Promise<{ itemId: string }>
consumeItem(sku: string, quantity: number): Promise<void>
setSandbox(sandbox: boolean): void

interface StoreItem {
  sku: string;
  name: string;
  description: string;
  imageUrl: string;            // "" when the product has no image
  consumable: boolean;
  price: { amount: number; currency: string } | null;   // amount in major units, e.g. 1.99
}

interface InventoryItem {
  sku: string;
  name: string;
  description: string;
  imageUrl: string;
  quantity: number | null;
}
```

`price` is `null` when the item has no price for this player, so check it before you read `amount`. `quantity` is `null` when the provider does not count the item; the portal's own store always returns a number.

Paging: `limit` is a whole number from 1 to 50 (default 50) and `offset` a whole number of 0 or more (default 0). Anything else (including `options` that is not an object) rejects with `invalidArgument`. Names and descriptions come back in the player's language when you provided a translation.

### isAvailable

`true` when the store is enabled for this game, has at least one active product and the page can show the checkout. It does not say whether the player is signed in. Hide every purchase button when it is `false`, and always check it before calling the other methods.

### getCatalogItems

Lists active products, ordered as set in the console. It works for guests. Only one catalogue request may run at a time; a second one rejects with `requestInProgress`.

<!-- docs-sample: uses shop -->
```js
if (SDK.store.isAvailable) {
  const items = await SDK.store.getCatalogItems();
  for (const i of items) {
    const price = i.price ? `${i.price.amount} ${i.price.currency}` : "";
    shop.add(i.sku, i.name, price, i.consumable);
  }
}
```

### getPlayerInventory

Lists what the signed-in player owns, totalled per sku (empty stacks are left out). Guests get `userNotAuthenticated`. One request at a time (`requestInProgress`). Read it at start and after every purchase.

### buyItem

Starts a purchase for one sku (a non-empty string, `invalidArgument` otherwise) and opens the [checkout dialog](#the-checkout-dialog). It resolves with `{ itemId }` (the sku you passed) once the order is paid and the items are in the inventory, and rejects otherwise. There is no timeout while the player decides. Only one purchase can run at a time (`purchaseInProgress`).

<!-- docs-sample: uses refreshInventory, showMessage -->
```js
async function buy(sku) {
  try {
    await SDK.store.buyItem(sku);
    await refreshInventory();
  } catch (e) {
    if (e.code === "purchaseCancelled") return;          // the player closed the dialog
    if (e.code === "userNotAuthenticated") return SDK.user.showAuthPrompt().catch(() => {});
    showMessage("The purchase did not go through.");
  }
}
```

### consumeItem

Removes `quantity` units (a whole number of 1 or more; `invalidArgument` for a non-integer, zero or a negative; the `sku` must be a non-empty string) of a consumable from the inventory, oldest purchase first. It is all or nothing: if the player owns fewer units than asked, nothing is removed.

<!-- docs-sample: uses wallet -->
```js
await SDK.store.consumeItem("coins-100", 1);
wallet.add(100);
```

Call it **after** you have granted the effect, or grant and consume in a way you can recover from if the page closes between the two. Consuming makes the units unavailable to every later `getPlayerInventory` and token.

### setSandbox

```ts
setSandbox(sandbox: boolean): void
```

Routes later store calls to the sandbox ledger (test payments) when `true`. It is synchronous and throws `invalidArgument` unless the argument is a boolean. The default is `false`, meaning real money. While the store's payment mode in the console is **Sandbox**, which is the only possible mode today, every call is sandbox whatever you pass. Once real money exists, only members of your studio may use `setSandbox(true)` on a live store; anyone else gets an error, so players cannot take items for free. Call it once before your first store call, for example when your own debug flag is on.

### The purchase token

```ts
SDK.store.getPurchaseToken(): Promise<string>
```

Returns a signed token that lists the player's items, for your server to verify. `SDK.user.getXsollaUserToken()` still works as a deprecated alias that returns the same token, so existing code keeps running; use `getPurchaseToken()` in new code. Use `userNotAuthenticated` to detect guests. The token follows the `sandbox` value of the most recent catalogue, inventory, buy or consume call (`setSandbox` itself sends nothing until one of those runs, so call `setSandbox` before the first store call and not just before the token). It is not cached: call it when you need a fresh one. See the next section.

## Verifying a purchase on your server

The browser can be tampered with. If a purchase unlocks anything on your own backend, send it the purchase token and verify it there.

The token is an RS256 JWT, valid for one hour, signed with the same key set as the [player token](https://docs.zokogames.com/sdk/user#tokens). Fetch the keys from:

```text
https://www.zokogames.com/.well-known/jwks.json
```

Check the signature and expiry, then check these:

| Claim | Value |
| --- | --- |
| `iss` | Always `zokogames:store`. A player token has a different issuer, so one can never pass as the other. **Reject anything else.** |
| `aud` | Your game's id. Reject a token for another game. |
| `typ` | `purchase`. |
| `sub` and `userId` | The player's stable id, the same one as in the [player token](https://docs.zokogames.com/sdk/user#tokens). |
| `gameId` | Your game's id, again. |
| `sandbox` | `true` when the token reflects test purchases. **Never grant real value for `true`.** |
| `items` | The inventory: `[{ "sku": "coins-100", "quantity": 3 }]`. |
| `orders` | The player's 20 most recent settled orders, newest first: `{ id, sku, quantity, status, amountMinor, currency, fulfilledAt }`. `status` is `fulfilled` or `consumed`; `amountMinor` is in the currency's smallest unit; `fulfilledAt` is Unix seconds. |

```js
const token = await SDK.store.getPurchaseToken();
await fetch("https://api.example.com/purchases/sync", {
  method: "POST",
  headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
});
```

:::tabs
== Node.js
<!-- docs-sample: fragment -->
```js
import { createRemoteJWKSet, jwtVerify } from "jose";

const JWKS = createRemoteJWKSet(new URL("https://www.zokogames.com/.well-known/jwks.json"));
const GAME_ID = process.env.ZOKO_GAME_ID;

export async function verifyPurchaseToken(token) {
  const { payload } = await jwtVerify(token, JWKS, {
    issuer: "zokogames:store",
    audience: GAME_ID,
    clockTolerance: 5,
  });
  if (payload.typ !== "purchase") throw new Error("not a purchase token");
  return payload; // userId, sandbox, items, orders
}
```
== Python
```python
import os
import jwt  # PyJWT >= 2.8, with the "crypto" extra

jwks_client = jwt.PyJWKClient("https://www.zokogames.com/.well-known/jwks.json", cache_keys=True)
GAME_ID = os.environ["ZOKO_GAME_ID"]

def verify_purchase_token(token: str) -> dict:
    signing_key = jwks_client.get_signing_key_from_jwt(token)
    claims = jwt.decode(
        token,
        signing_key.key,
        algorithms=["RS256"],
        issuer="zokogames:store",
        audience=GAME_ID,
        options={"require": ["exp", "iat", "iss", "aud"]},
        leeway=5,
    )
    if claims.get("typ") != "purchase":
        raise ValueError("not a purchase token")
    return claims
```
== C#
```csharp
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;

public sealed class ZokoPurchaseVerifier
{
    private static readonly HttpClient Http = new();
    private JsonWebKeySet? _keys;
    private DateTime _fetched = DateTime.MinValue;

    public async Task<JwtSecurityToken> VerifyAsync(string token, string gameId)
    {
        if (_keys is null || DateTime.UtcNow - _fetched > TimeSpan.FromHours(1))
        {
            var json = await Http.GetStringAsync("https://www.zokogames.com/.well-known/jwks.json");
            _keys = new JsonWebKeySet(json);
            _fetched = DateTime.UtcNow;
        }

        var parameters = new TokenValidationParameters
        {
            IssuerSigningKeys = _keys.GetSigningKeys(),
            ValidateIssuer = true,
            ValidIssuer = "zokogames:store",
            ValidateAudience = true,
            ValidAudience = gameId,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.FromSeconds(5),
        };

        new JwtSecurityTokenHandler().ValidateToken(token, parameters, out var validated);
        var jwt = (JwtSecurityToken)validated;
        if (jwt.Claims.FirstOrDefault(c => c.Type == "typ")?.Value != "purchase")
            throw new SecurityTokenException("not a purchase token");
        return jwt;
    }
}
```
== Go
```go
package zoko

import (
	"errors"
	"os"
	"time"

	"github.com/MicahParks/keyfunc/v3"
	"github.com/golang-jwt/jwt/v5"
)

var jwks, _ = keyfunc.NewDefault([]string{"https://www.zokogames.com/.well-known/jwks.json"})

func VerifyPurchaseToken(raw string) (jwt.MapClaims, error) {
	claims := jwt.MapClaims{}
	_, err := jwt.ParseWithClaims(raw, claims, jwks.Keyfunc,
		jwt.WithValidMethods([]string{"RS256"}),
		jwt.WithExpirationRequired(),
		jwt.WithIssuer("zokogames:store"),
		jwt.WithAudience(os.Getenv("ZOKO_GAME_ID")),
		jwt.WithLeeway(5*time.Second),
	)
	if err != nil {
		return nil, err
	}
	if claims["typ"] != "purchase" {
		return nil, errors.New("not a purchase token")
	}
	return claims, nil
}
```
:::

### Granting exactly once

Treat the order `id` in `orders` as your idempotency key. Keep a table of order ids you have already granted, and grant an order only when its id is new. Then the same token (or an overlapping one) can be sent as often as you like, after a crash, a retry or a second device, and nothing is granted twice. Portal side, a purchase is just as safe: a retried payment for the same order never charges or grants twice, and the SDK's checkout retries use a fresh order only after the previous one failed.

Use `items` for "what does the player own right now" (durable unlocks, current stock) and `orders` for "what happened" (granting a delivery once). Only the 20 newest settled orders are listed, so sync often enough that an order is seen before 20 newer ones push it out.

> [!WARNING]
> There are no fulfilment webhooks for purchases. Fulfilment is pull-based: your server learns about a purchase from the token the player's game sends it.

## The checkout dialog

`buyItem` opens the portal's own dialog on top of the game, so you never handle payment details.

1. **Confirm purchase** shows the item, its price and **Buy for {price}**, with **Cancel**. In sandbox it carries a **Test purchase** badge and the note that no money is charged, plus a **Simulate a declined payment** link for rehearsing a failure.
2. **Processing** while the order is paid and fulfilled.
3. **Purchase complete** says the item was added to the player's items. The promise resolves at this point; the player dismisses the dialog with **Continue**, so refresh your UI immediately and expect the dialog to still be on screen for a moment.
4. **Purchase failed** says nothing was charged and offers **Try again** (creates a new order) and **Close**.

Escape, the backdrop, **Cancel** and **Close** reject `buyItem` with `purchaseCancelled`. The dialog needs the portal page around your game: when a game runs somewhere without it, `buyItem` rejects with `purchaseInitFailed` ("Checkout is not available on this page") and `isAvailable` is `false`.

## Refunds in sandbox

In the console, **Store > Orders** lists every order with its status (`created`, `paid`, `fulfilled`, `consumed`, `refunded`, `failed`), mode, player, amount and date. You can filter by status, mode, sku and dates, and export CSV. Choose **Refund** on a **test** order to mark it refunded and remove whatever is left of its items from the player's inventory. Units the player already consumed are not restored. Refunded orders also drop out of the token's `orders` list, so they stop counting on your server the next time you sync. Real-money orders cannot be refunded from the console.

## Testing locally

Open your game on `localhost` (or with `useLocalSdk=true`) and the SDK runs in [local mode](https://docs.zokogames.com/getting-started/local-testing). The store is always available there and is a mock held in memory, so nothing you do is saved between page loads:

- The catalogue is fixed: `local-coins-100` (consumable, 0.99 USD), `local-gems-50` (consumable, 2.99 USD) and `local-no-ads` (durable, 4.99 USD). Your own skus do not exist in local mode.
- The inventory starts with 3 `local-coins-100` and 1 `local-no-ads`.
- `buyItem` succeeds at once with a toast, no dialog. Buying an owned durable fails with `purchaseInitFailed`.
- `consumeItem` enforces the same rules, with `itemNotInInventory`, `itemNotConsumable` and `insufficientItemQuantity`.
- The purchase token is a fake string, not a JWT. Your verifier will correctly reject it, so for local backend work add a test-only bypass that cannot be enabled in production.

**To test a purchase without money, with your real skus and the real dialog**, use the game's Preview in the console. The steps:

1. On the **Store** page, switch **Store enabled** on and keep **Payment mode** on **Sandbox (test purchases)**.
2. Create a product and leave **Active** ticked. The page's top line changes to "On, in sandbox mode" when this is right.
3. Open the game from the **Open this game in Preview** link on the Store page (the game's **Preview** tab, the same tool as the [Preview tool](https://www.zokogames.com/preview)), signed in with a studio account. Reload the game after changing the store settings, because `isAvailable` is read once at start.
4. Call `SDK.store.buyItem("your-sku")`. The checkout dialog carries the **Test purchase** badge; use **Simulate a declined payment** to rehearse a failure.
5. Open **Store > Orders**. The test order shows **Sandbox** next to its status, and **Refund** removes what is left of its items. Your own test orders never count as sales.

## Provider not connected

"Payment provider not connected" is shown in the console while real-money sales are switched off on the portal, which is the case today: the payment provider is integrated, but **real money cannot be charged** until the portal team switches it on. Until then:

- the payment mode is locked to sandbox;
- every order, whoever places it, is a test order shown with the "Test purchase" badge;
- test items are not worth anything and tokens carry `sandbox: true`.

We will announce the change in the [changelog](https://docs.zokogames.com/business/changelog). Real-money sales will also need an agreement with us; see [revenue share](https://docs.zokogames.com/business/revenue-share). Do not add your own payment links, donation buttons or external checkouts to a game ([quality guidelines](https://docs.zokogames.com/requirements/quality)).

**Common mistakes.** The ones QA and the Preview tool report most often:

| Mistake | Result | Fix |
| --- | --- | --- |
| Purchase buttons are shown without checking `SDK.store.isAvailable` | Every call fails (`catalogFetchFailed`, `purchaseInitFailed`) | Hide the shop when it is `false`, and in kids mode and the Android app it always is. |
| `getPlayerInventory`, `buyItem` or `consumeItem` is called for a guest | `userNotAuthenticated` | Offer `SDK.user.showAuthPrompt()` when a guest presses buy. |
| The reward is granted from the result of `buyItem` only | Lost on a closed page, forged by a modified client | Refresh `getPlayerInventory()` and, for anything that matters, verify the purchase token on your server. |
| `purchaseCancelled` is shown as a failure | An error message after the player pressed Cancel | Return quietly on `purchaseCancelled`. |
| A second `buyItem` is started while the dialog is open | `purchaseInProgress` | Disable buy buttons until the promise settles. |
| `consumeItem` is called before the effect is granted | A lost item if the page closes in between | Grant first, or grant and consume in a way you can recover from. |
| A durable item is consumed or bought twice | `itemNotConsumable`, or a "you already own it" failure | Check `consumable` in the catalogue and `quantity` in the inventory. |
| The `sandbox` token is trusted on the server | Free items for test purchases | Reject a token whose `sandbox` claim is `true` for real value. |
| `price` is read without a check | A `TypeError` when it is `null` | Test `item.price` before reading `amount`. |
| Two catalogue or inventory requests run at once | `requestInProgress` | Wait for the first to finish. |
| Local-mode skus are shipped | `itemNotInInventory`, `purchaseInitFailed` on the portal | Local mode has its own fixed catalogue; use your real skus in the Preview tool. |

## Errors per call

| Call | Codes it can reject with (besides the [general ones](https://docs.zokogames.com/sdk/introduction#errors)) |
| --- | --- |
| `getCatalogItems` | `invalidArgument`, `requestInProgress`, `catalogFetchFailed`, `unexpectedError` |
| `getPlayerInventory` | `invalidArgument`, `requestInProgress`, `userNotAuthenticated`, `inventoryFetchFailed`, `unexpectedError` |
| `buyItem` | `invalidArgument`, `purchaseInProgress`, `userNotAuthenticated`, `purchaseInitFailed`, `purchaseCancelled`, `unexpectedError` |
| `consumeItem` | `invalidArgument`, `requestInProgress`, `userNotAuthenticated`, `itemNotInInventory`, `itemNotConsumable`, `insufficientItemQuantity`, `consumeItemFailed`, `unexpectedError` |
| `getPurchaseToken` | `userNotAuthenticated`, `rateLimited`, `unexpectedError` |
| `setSandbox` (throws) | `invalidArgument` |

## When the player is a guest, offline or ad-free

| Situation | Behaviour |
| --- | --- |
| Guest | `getCatalogItems` works. Inventory, `buyItem`, `consumeItem` and `getPurchaseToken` fail with `userNotAuthenticated`. Offer `SDK.user.showAuthPrompt()` when the guest presses buy. |
| Offline | The store needs the portal; calls fail with the failure code of that call. Hide the shop while `SDK.game.isOffline` is `true`. |
| Ad blocker or ad-free member | No effect on purchases. |
| Basic launch | Players can buy in any live game, basic launch included, when the store is on and a product is active (sandbox mode only today). |
| Local mode | A fixed mock store; see [testing locally](#testing-locally). |
| Inside the Android app | Purchases are off. `SDK.store.isAvailable` is `false`, as for a game without a store: `getCatalogItems` rejects with `catalogFetchFailed`; for a signed-in player `getPlayerInventory` rejects with `inventoryFetchFailed`, `buyItem` with `purchaseInitFailed`, `consumeItem` with `consumeItemFailed` and `getPurchaseToken` with `unexpectedError`; guests get `userNotAuthenticated`. The portal also refuses real-money payments from the app with `purchaseInitFailed`. Your game is not told why: check `isAvailable` and hide every shop button. |

**Kids mode.** `SDK.store.isAvailable` is `false`, `getCatalogItems` rejects with `catalogFetchFailed`, and `getPlayerInventory`, `buyItem`, `consumeItem` and `getPurchaseToken` reject with `userNotAuthenticated`. Check `isAvailable` instead of the codes; see [kids mode](https://docs.zokogames.com/guides/kids-mode#calls-in-kids-mode).

## Error codes

| Code | When |
| --- | --- |
| `userNotAuthenticated` | The player is a guest (inventory, buy, consume, token). |
| `invalidArgument` | A wrong argument: empty sku, `limit` outside 1 to 50, a non-integer `quantity` and so on. |
| `catalogFetchFailed` | The catalogue could not be loaded, or the store is not enabled. |
| `inventoryFetchFailed` | The inventory could not be loaded. |
| `purchaseInitFailed` | The order could not be created or paid: unknown or inactive sku, durable already owned, payment declined, no checkout on this page, store off. The message for an unknown sku and for an inactive one is the same, `No item with sku "...".`, so when you see it check that the sku is typed exactly as in the console (lowercase) and that the product is **Active**. |
| `purchaseInProgress` | Another `buyItem` is still running. |
| `purchaseCancelled` | The player closed the dialog, or the order was cancelled. |
| `consumeItemFailed` | The consume call failed or the store is off. |
| `itemNotConsumable` | The sku is a durable. |
| `itemNotInInventory` | The player owns none of that sku, or the sku does not exist. |
| `insufficientItemQuantity` | The player owns fewer units than `quantity`. |
| `requestInProgress` | The same kind of request is already running. |
| `unexpectedError` | Anything else, including a failed token request. |
| `other` | Something the SDK could not classify, for example an answer from the portal that was not an error object. Treat it like `unexpectedError`. |

The general codes `sdkNotInitialized`, `sdkDisabled` and `timeout` apply too. Calls are rate limited: a call over the game page's [call limits](https://docs.zokogames.com/sdk/introduction#call-limits) fails with `requestInProgress`, and a call the store server limits per player fails with the failure code of that call.

## FAQ

**Can I sell real items today?** No. Only sandbox purchases work, see [provider not connected](#provider-not-connected).

**Why is `isAvailable` false?** The store is off in the console, no product is active, the portal switched purchases off, or the game runs without portal checkout (for example a local page that does not use local mode). Inside the portal's Android app it is always `false`.

**Do guests see the shop?** They can read the catalogue. Ask them to sign in with `showAuthPrompt` when they press buy.

**Do sandbox and real purchases share an inventory?** No. They are separate ledgers; test items never become real ones.

**What happens if the player closes the tab mid-purchase?** An unpaid order is abandoned and nothing is charged. If it was paid, the items are in the inventory at the next start.

**Can I price in several currencies?** One price and currency per product.

**Can I give items for free?** Not through the store. Grant free rewards in your own game state.

**Are there fulfilment webhooks?** No. Verify the [purchase token](#verifying-a-purchase-on-your-server). The studio [webhooks](https://docs.zokogames.com/guides/webhooks) cover builds and reviews, not purchases.

## Next steps

- [Analytics](https://docs.zokogames.com/sdk/analytics)
- [Webhooks](https://docs.zokogames.com/guides/webhooks)
