Skip to content

SDK reference

@playium/sdk speaks the store's embed protocol for you: the handshake, origin checks, renewing the token, retrying once after a 401, and telling the store when a call ended or was refused. It ships with the store's addresses (listed at the end of this page), so it needs no settings.

Playium.init(options?)

Connects and resolves with the client once the first play token has arrived. Also exported as init. It rejects with a PlayiumError:

  • not_on_platform: the page was opened on its own, or framed by a page that is not the store. error.detail starts with standalone: or framed:. Opened on its own, or framed by a page whose origin the browser names (Chrome, Safari), it rejects at once; otherwise after handshakeTimeoutMs (10 seconds), so show your title screen meanwhile.
  • The store's own code when it could not give a token: purchase_required when the trial of a paid game is over; anything else (unauthorized, game_unavailable, ...) is a failure to show. error.detail holds the store's English message, for logs.
  • wrong_backend: the token points outside the addresses below.
  • In dev mode: dev_key_not_allowed, invalid_dev_key or origin_not_allowed.

You may call init() again after it rejected, for example on a Try again button: a failed init() keeps no listener or timer, and the next one starts a new handshake. With no client yet, your game cannot hear unblocked for a refusal of the first token; after the player bought the game in the store, the next init() gets a token.

OptionDefaultMeaning
languagesnoneYour game's languages (['en', 'zh-CN']), the first one the default. client.locale is the closest to the store's lang.
devKeynoneA dev key, used only on localhost or 127.0.0.1 outside the store. See Testing.
backendUrlproductionWhere dev mode gets tokens.
handshakeTimeoutMs10000How long to wait for the store’s first answer.
tokenTimeoutMs10000How long to wait for a renewed token.
callTimeoutMs60000How long a call may wait: the whole call for chat() and saves, the headers for fetch() and chatStream(). 0 for no limit.
storeOriginsSTORE_ORIGINSStore origins to accept tokens from. For tests only.
backendOriginsBACKEND_ORIGINSOrigins a token's gateway and API may be on; null turns the check off. For tests only.
fetchthe browser’sThe fetch to use. For tests only.
import { Playium, PlayiumError } from '@playium/sdk';

// The title screen can use the same language before init() resolves:
showTitle(Playium.pickLocale(['en', 'zh-CN'])); // the same choice as client.locale

async function connect() {
  try {
    return await Playium.init({ languages: ['en', 'zh-CN'] });
  } catch (error) {
    if (error instanceof PlayiumError && error.code === 'not_on_platform') {
      Playium.renderNotOnPlatform(document.body, { gameSlug: 'your-game' }); // links to your store page
    } else {
      showTryAgain(Playium.describeError(error), connect); // init() may be called again
    }
    return null;
  }
}

The client

MemberWhat it is
player{ id }: the player's pseudonymous id in your game, the token's sub. Stable for your game, different in every other game. Never the name or the email address.
modelive, preview or dev: how the token was obtained.
gameIdYour game’s id on the platform.
defaultModelThe model calls use unless they name another.
access{ owned, trial, can_play }; trial is set only for a paid game the player does not own.
localeThe language to show the game in: the store's lang, matched to languages.
gatewayBaseUrl, storeOrigin, versionThe gateway’s address, the store origin that answered (null in dev mode), the SDK version.
chat(request)One chat completion. Resolves with { text, message, finish_reason, usage, model, raw }.
chatStream(request)The same, streamed: iterate it with for await; each item is { text, chunk }.
openaiOptions()Options for new OpenAI(...): the gateway, a fetch that always sends a fresh token, and maxRetries: 0.
fetch(path, init?)fetch for the gateway, for anything chat() does not cover. The token never leaves the platform.
saveCloud saves: get, set, delete, list. See Cloud saves.
achievements, leaderboardsachievements.unlock(id), list(); leaderboards.submit(id, score), top(id), aroundMe(id). See Achievements and leaderboards.
token()The current play token, for your own server. See Players on your server.
describe(error)A sentence for the player about any error, in client.locale when it is one of the store's ten languages (English, Simplified and Traditional Chinese, Japanese, Korean, Spanish (Latin America), Portuguese (Brazil), German, French and Russian); English otherwise.
on(event, listener), off(...)Listens to the events below; on() returns a function that stops listening.
reportModelCall(), reportBlocked(reason)For calls made without the SDK’s fetch: tell the store a call ended, or was refused.
close()Stops listening to the store. Calls made after it reject with aborted.

Events

EventWhen
blockedThe gateway refused a call for a reason the player can fix in the store: insufficient_credits, purchase_required or session_limit_reached. The store shows its own prompt; keep your game as it is. Emitted before the call rejects with the same error.
unblockedThe player fixed it: added credits, bought the game, started a new session or lifted the limit. Let the player try again.
token-errorRenewing the token failed. The call that needed it rejects with the same error, so a game that handles rejections needs nothing more; the event is for logging. The next call asks the store again.
accessA new token brought a different access: the player bought the game, or used a trial play.
playium.on('blocked', ({ reason }) => pauseGame(reason));
playium.on('unblocked', () => enableTryAgain());

A refused call does both: blocked fires, then the call rejects (error.blocked is true). Handling the rejection alone is enough. Never send the call again by yourself: wait for the player's Try again, or for unblocked.

Errors

Everything the SDK rejects with is a PlayiumError: a stable code, the HTTP status (0 when there was no answer), an English message and detail for logs, blocked for the three refusals the store can help with, and describe(locale), a sentence for the player in the store's ten languages. The SDK never retries a call by itself, except once with a new token after a 401: every attempt is charged, so retrying is the player's decision.

try {
  const reply = await playium.chat({ messages, max_tokens: 100 });
  show(reply.text);
} catch (error) {
  showMessage(playium.describe(error)); // in client.locale, one of the store's ten languages
}

The gateway's codes are on Model calls, the cloud-save codes on Cloud saves. The SDK's own:

CodeWhat happenedWhat your game does
timeoutNo answer within callTimeoutMs. The gateway may still have finished the call, so it may have been charged; the SDK tells the store to read the balance again.Let the player try again.
networkNo answer at all (nothing was charged), or a stream was cut off (charged for what was generated).Let the player try again.
abortedYou cancelled the call (signal, stream.abort(), close()).Nothing.
bad_responseThe answer could not be read.Let the player try again.
not_on_platformNot in the store.The notice below, or your own screen.
store_unreachableThe store did not answer a token renewal, and the token in hand had expired.Let the player try again.
wrong_backendA token or URL points outside the trusted addresses.Check how you call fetch().
invalid_save_key, invalid_save_value, saves_unavailableA bad save key, a value that is not JSON, or a token without cloud saves.Fix the call, or keep progress locally.
dev_key_not_allowed, invalid_dev_key, origin_not_allowedDev mode.See Testing.
invalid_requestNo max_tokens (checked before sending), or the gateway refused the request as malformed.Fix the request.

Any other code comes from a newer platform or from the store; describe() gives a generic sentence for it.

The notice outside the store

Playium.renderNotOnPlatform(document.getElementById('app'), {
  gameSlug: 'your-game', // shown next to the title in the console; links to the store page
  title: 'Your Game',
});
OptionMeaning
gameSlugLinks to https://playium.games/games/<slug>. Your game's slug is shown next to its title in the console.
storeUrlAny http(s) address to link to instead. Without either, the notice links to the store’s front page.
titleYour game’s title, shown above the notice.
localeThe language: by default the same as client.locale would be. The notice speaks the store's ten languages; others get English.

The notice has its own neutral look, light or dark with the player's system, and cannot be restyled. For your own look, draw your own screen and link to Playium.storePageUrl('your-game').

Trusted addresses

The SDK takes play tokens only from these store origins, and sends the token only to these backend origins. A game therefore works without options in the store, in the developer preview, and in a local copy of the platform. Any other store, such as a staging or preview deployment, gets no answer: init() rejects with not_on_platform. The SDK exports both lists as STORE_ORIGINS and BACKEND_ORIGINS.

Origins
Storehttps://playium.games, https://www.playium.games, https://ai-game-platform-web-eight.vercel.app, http://localhost:3000, http://127.0.0.1:3000
Backendhttps://api.playium.games, https://platformbackend-production-e04dbbd2.up.railway.app, http://localhost:8787, http://127.0.0.1:8787

The protocol underneath

The SDK speaks ai-game-platform/embed version 1 over postMessage, with two additions: ready carries the SDK version as sdk, and the store sends unblocked. Games that speak the protocol by hand, or use the older drop-in file, keep working.

Next: Model calls