Vai al contenuto
InstaPlay
Sezioni della guida

Ads in your game: interstitials and rewarded ads

On InstaPlay, ads are shown by the portal; the game only asks: “this is a good pause” or “the player wants a reward for watching”. Which network to call, whether an ad may be shown right now, how to pause the game and mute it — the portal decides. The game needs no ad SDKs, keys or contracts with networks of its own. SDK 1.3: InstaPlay.ads.interstitial(), InstaPlay.ads.rewarded(), InstaPlay.ads.available() (reference).

How it works

  1. The game calls ads.interstitial() in a natural pause or ads.rewarded() when the player presses a button.
  2. The portal checks frequency limits and asks its server which ad to show. Ad networks (Yandex Advertising Network, Google and others) are connected by the portal — the game needs no changes when that list changes.
  3. While the ad is on screen, the game gets the pause event with { reason: 'ad' } and mute; afterwards — resume and unmute. Sound that the player turned off themselves stays off.
  4. The promise returns the outcome: { shown } for an interstitial, { rewarded, grant } for a reward. If there was no ad, the outcome carries a reason.

There is nothing to turn on in the dashboard: where the portal shows ads, InstaPlay.isSupported('ads') returns true. No feature (outside the portal, ads turned off for the game by the portal) — false, and calls answer reason: 'disabled'; the game just goes on without ads.

Rules

  • Natural pauses only. Interstitials go between levels, after “Game over”, on the way to the menu; stop the round first (gameplay.stop()). During gameplay the portal shows no ad and answers gameplay_active.
  • Not right after loading. No interstitial in the first 60 seconds after ready (too_early). Do not ask for ads before ready: the build checks flag such a call with a warning.
  • Cooldowns and caps. By default at least 120 seconds between interstitials and 60 seconds after a rewarded ad; rewarded ads have their own 30-second cooldown; there are caps per run and per player per day (UTC). Going over them means cooldown or cap_reached, not an error. The portal owns the limits: do not build game logic on exact numbers — ask ads.available().
  • Rewarded only on the player's explicit choice. A “Watch an ad for +1 life” button in the game and the player's press; no automatic “rewarded” shows. The portal also shows its own card “Watch an ad for a reward?” — declining or 30 seconds without an answer give declined.
  • The reward only after watching to the end and server confirmation. rewarded: true arrives when the ad was watched and the portal server counted the impression. Closed early — dismissed, no reward. If your game has its own server, the server grants the reward — after checking the signature.
  • Your own ads are forbidden — below.

Between levels: interstitial

async function onLevelCleared() {
  InstaPlay.gameplay.stop() // before the ad: during gameplay the answer is gameplay_active
  const { shown, reason } = await InstaPlay.ads.interstitial({ placement: 'level_end', moment: 'next' })
  if (!shown) console.debug('no ad:', reason) // cooldown, too_early, no_fill… — not an error
  startNextLevel()
}
  • placement — your name for the place in the game ([a-z0-9_-], up to 32 characters): level_end, game_over. It shows where ads work better.
  • moment — what follows the ad: next (the game goes on), pause (the player opened the pause menu), browse (menu, level select).
  • The promise resolves when the ad is closed or there was none; continue the game either way.

For a reward: rewarded

// Show the “+1 life for an ad” button only when the portal is ready to show an ad.
const { available } = await InstaPlay.ads.available('rewarded')
extraLifeButton.visible = available

extraLifeButton.onClick = async () => {
  const { rewarded, reason, grant } = await InstaPlay.ads.rewarded({ placement: 'extra_life' })
  if (rewarded) {
    if (grant) await claimOnServer(grant.token) // a game with its own server: the server grants it
    else lives += 1
  } else {
    showToast(reason === 'declined' ? 'Maybe next time' : 'No ad right now, try later')
  }
}
  • rewarded: true — the player watched it, grant the reward. grant is the reward signed by the portal for your server: token (JWT), id (one impression — one reward), expiresAt (10 minutes).
  • grant can be null with rewarded: true — the portal did not sign the reward (preview, a stand without a signing key). A game without a server grants the reward itself and ignores grant; a game with its own server does not grant the reward on the server in that case.
  • Normal outcomes do not reject the promise: declined, dismissed, no_fill, cooldown are rewarded: false with a reason. Only a protocol error (rate_limited, timeout) rejects it — errors.
  • Do not hoard rewards: verify and redeem a grant right away — after 10 minutes the server rejects it.

What the game sees

What How
Pause the pause event with { reason: 'ad' }, then resume — the same handling as for a hidden tab
Sound mute during the ad, then unmute; if the player muted the game themselves, no unmute comes
Outcome { shown, reason } / { rewarded, reason, grant }; reasons are in the reference
Frame the portal draws the ad over the game; the game hides or rescales nothing

The game must stop its loop and sound on pause/mute anyway (events): a game that handles pause properly is ready for ads as is. Pause and sound during ads are the portal's job, not the game's.

Verifying a reward on your server

If your server grants the reward (currency, items, server-side progress), do not trust a rewarded flag from the client: a player can call your API directly. Send grant.token — the reward signed by the portal — to your server and verify it like the player token: an ES256 JWT, the same JWKS keys and caching rules (keys and cache).

Field Value
header typ ip-reward+jwt — a player token (ip-player+jwt) does not pass as a reward
iss the portal address, https://instaplay.ru
aud reward:<game id> — not the game id as in the player token
sub, kind the player — the same pseudonym as the sub of their player token
jti the impression id: one reward per impression — keep jti until exp and never accept it twice
plc the placement the game passed — which reward to grant (optional)
vrf how the impression was confirmed: client (portal), frame, s2s (network)
iat, exp issued and expires: exp = iat + 600

Required checks: the algorithm is strictly ES256; typ is ip-reward+jwt; iss is the portal; aud is reward: plus your game id; exp with at most 30 seconds of leeway; sub is the player your server knows from their player token; jti has not been seen before (a store shared by all server instances: SET jti NX EX in Redis or a unique index in the database). The reward carries no IP, no country and no network.

Node.js

// Node.js 22 (jose >= 5) — verifying an InstaPlay ad reward on your game server (ADR-0022 §7).
// Keys and addresses are the same as for the player token; the emulator and tests substitute theirs.
import { createRemoteJWKSet, jwtVerify } from 'jose'

const ISSUER = process.env.INSTAPLAY_ISSUER ?? 'https://instaplay.ru'
const JWKS_URL = process.env.INSTAPLAY_JWKS_URL ?? `${ISSUER}/.well-known/instaplay-jwks.json`
const TTL_MS = Number(process.env.INSTAPLAY_JWKS_TTL ?? 600) * 1000 // ≤ 10 min
const JWKS = createRemoteJWKSet(new URL(JWKS_URL), {
  cacheMaxAge: TTL_MS,
  cooldownDuration: 30_000, // unknown kid → refetch, at most once every 30 s
})
const AUDIENCE = `reward:${process.env.INSTAPLAY_GAME_ID}` // not the game id: a player token won't pass as a reward
const seen = new Map() // jti → exp; in production — a shared store (Redis SET NX EX, a unique DB index)

export async function rewardFrom(token, playerId) {
  const { payload } = await jwtVerify(token, JWKS, {
    issuer: ISSUER,
    audience: AUDIENCE,
    typ: 'ip-reward+jwt',
    algorithms: ['ES256'],
    clockTolerance: 30,
  })
  if (payload.sub !== playerId) throw new Error('other player') // playerId — sub from the player token
  const now = Math.floor(Date.now() / 1000)
  for (const [jti, exp] of seen) if (exp < now - 30) seen.delete(jti)
  if (seen.has(payload.jti)) throw new Error('replay') // one reward per impression
  seen.set(payload.jti, payload.exp)
  return { id: payload.jti, placement: payload.plc ?? null, verified: payload.vrf }
}

Ruby

# Ruby (gem "jwt" >= 2.7) — verifying an InstaPlay ad reward on your game server (ADR-0022 §7).
# Keys and addresses are the same as for the player token; CI tests substitute the emulator.
require 'jwt'; require 'net/http'; require 'json'
ISSUER = ENV.fetch('INSTAPLAY_ISSUER', 'https://instaplay.ru')
JWKS_URL = URI(ENV.fetch('INSTAPLAY_JWKS_URL', "#{ISSUER}/.well-known/instaplay-jwks.json"))
JWKS_TTL = Integer(ENV.fetch('INSTAPLAY_JWKS_TTL', '600'))   # ≤ 10 min
JWKS_LOADER = lambda do |opts|
  age = @jwks_at ? Time.now - @jwks_at : Float::INFINITY
  if age > JWKS_TTL || (opts[:kid_not_found] && age > 30)   # unknown kid → refetch, at most once every 30 s
    @jwks = JWT::JWK::Set.new(JSON.parse(Net::HTTP.get(JWKS_URL)))
    @jwks_at = Time.now
  end
  @jwks
end
REWARD_AUD = "reward:#{ENV.fetch('INSTAPLAY_GAME_ID')}"   # not the game id: a player token won't pass as a reward
SEEN = {}   # jti => exp; in production — a shared store (Redis SET NX EX, a unique DB index)
def reward_from(token, player_id)
  payload, header = JWT.decode(token, nil, true, algorithms: ['ES256'], jwks: JWKS_LOADER,
    iss: ISSUER, verify_iss: true, aud: REWARD_AUD, verify_aud: true, leeway: 30)
  raise 'bad typ' unless header['typ'] == 'ip-reward+jwt'
  raise 'other player' unless payload['sub'] == player_id   # player_id — sub from the player token
  now = Time.now.to_i
  SEEN.delete_if { |_, exp| exp < now - 30 }
  raise 'replay' if SEEN.key?(payload['jti'])   # one reward per impression
  SEEN[payload['jti']] = payload['exp']
  payload
end

Python

# Python (PyJWT[crypto] >= 2.8) — verifying an InstaPlay ad reward on your game server (ADR-0022 §7).
# Keys and addresses are the same as for the player token; CI tests substitute the emulator.
import os, time, urllib.request, jwt
ISSUER = os.environ.get("INSTAPLAY_ISSUER", "https://instaplay.ru")
JWKS_URL = os.environ.get("INSTAPLAY_JWKS_URL", f"{ISSUER}/.well-known/instaplay-jwks.json")
TTL = int(os.environ.get("INSTAPLAY_JWKS_TTL", "600"))      # ≤ 10 min
_jwks, _jwks_at = {}, float("-inf")
def signing_key(kid):
    global _jwks, _jwks_at
    age = time.monotonic() - _jwks_at
    if age > TTL or (kid not in _jwks and age > 30):         # unknown kid → refetch, at most once every 30 s
        with urllib.request.urlopen(JWKS_URL, timeout=5) as res:
            _jwks = {k.key_id: k.key for k in jwt.PyJWKSet.from_json(res.read().decode()).keys}
        _jwks_at = time.monotonic()
    return _jwks[kid]
REWARD_AUD = "reward:" + os.environ["INSTAPLAY_GAME_ID"]   # not the game id: a player token won't pass as a reward
_seen = {}   # jti -> exp; in production — a shared store (Redis SET NX EX, a unique DB index)
def reward_from(token: str, player_id: str) -> dict:
    header = jwt.get_unverified_header(token)
    if header.get("typ") != "ip-reward+jwt":
        raise ValueError("bad typ")
    payload = jwt.decode(token, signing_key(header.get("kid")), algorithms=["ES256"],
                         issuer=ISSUER, audience=REWARD_AUD, leeway=30)
    if payload["sub"] != player_id:                          # player_id — sub from the player token
        raise ValueError("other player")
    now = time.time()
    for jti in [j for j, exp in _seen.items() if exp < now - 30]:
        del _seen[jti]
    if payload["jti"] in _seen:                              # one reward per impression
        raise ValueError("replay")
    _seen[payload["jti"]] = payload["exp"]
    return payload

Environment variables are the same as for the player token: INSTAPLAY_GAME_ID — the game id from the dashboard (required), INSTAPLAY_ISSUER and INSTAPLAY_JWKS_URL — the portal or the emulator, INSTAPLAY_JWKS_TTL — the key cache lifetime. These three examples run in our tests against the emulator's signer: a reward is accepted; the same reward a second time is rejected; a player token presented as a reward is rejected; a token with a foreign aud (the game id without reward:, another game) is rejected; another player's reward is rejected.

Emulator and preview

instaplay dev ./folder (CLI) shows test ads: a full-screen “Test ad” placeholder with a timer, the “Watch an ad for a reward?” card, pause and mute — as on the portal. The “Ads” section of the emulator panel:

Setting What it does
fill an ad is there, “no ad” (no_fill), a network error, a network timeout
video, “allow closing early” the video length; whether it can be closed before the end (rewarded — dismissed)
card always — the card before every reward; auto — no card on a fresh player press outside gameplay
verification client or s2s (the network confirmation comes with a delay — the outcome waits for it)
limits “no limits” (default) or “strict ad limits” — frequency as on the portal

Below the panel is a log of impressions. The emulator signs rewards with its dev key: JWKS — http://localhost:4300/_emu/jwks.json, iss — the emulator origin, aud — reward: plus the player token aud from the terminal hint (reward:<--game-id> or reward:dev:<game address>). Pass these values to your local game server, as for the player token.

  • Preview (preview link) shows the same test ads without limits; the reward comes unsigned (grant: null), no statistics are written.
  • Portal build checks answer any ad call with no_fill right away — the game must not hang when there is no ad. instaplay test shows ads like the emulator (default panel settings).
  • Engines in the editor — stubs with a choice of outcome (engines).

Engines

Engine Calls
Unity InstaPlay.Ads.Interstitial(placement, onDone), InstaPlay.Ads.Rewarded(placement, onDone), InstaPlay.Ads.Available(type, onDone)
Godot await InstaPlay.ads_interstitial(placement), await InstaPlay.ads_rewarded(placement), await InstaPlay.ads_available(type)
Construct 3 InstaPlayC3.adsInterstitial(placement), InstaPlayC3.adsRewarded(placement), InstaPlayC3.adsAvailable(type)

Ads come with engine wrappers since 1.2.0. In the Unity and Godot editors and in the Construct preview a stub works: the outcome (“shown”, “no ad”, “closed early”, “declined”, “disabled”) and the length are configurable, and “shown” pauses and mutes the game — a way to test pause handling.

Statistics

The game's “Statistics” tab in the dashboard has an “Ads” block: impressions, fill (impressions to requests), impressions per player and per run, ad rewards per player, a breakdown by type; days are UTC (statistics). Only impressions marked by the portal server count. There is no revenue in the block yet — it comes with payouts.

Your own ads are forbidden

Your own ad SDKs, banners and links to ad networks in the game are forbidden — it is the external_monetization rejection reason (moderation); ad network addresses do not pass into the game network either. All ads go through InstaPlay.ads: the portal picks the network, respects the player's consent and limits, and the game gets the impressions in its statistics.