Developer API: cloud saves, in-app purchases, ads and leaderboards
Let players sign in to your game or app with their Synkrown Hub account and keep their saves in the cloud. It works for builds hosted here and for games and apps on your own website.
1. Turn it on
- Open your page in My pages and go to the Cloud saves tab.
- Tick Turn on cloud saves and note your App ID.
- Optional: tick Only for owners of the full version. Players who have not bought it are then refused.
- Only if your game runs on another website: add the address players come back to after signing in, for example
https://mygame.com/play. For testing,http://localhost:8080/works too.
2. Add the script
<script src="https://synkrown.org/js/synkrown.js"></script>Use this full address for builds hosted here too.
3. Sign players in
const hub = SynKrown.init({ app: 123 }); // your App ID
await hub.ready;
if (hub.user) {
console.log('Signed in as', hub.user.display_name);
} else if (hub.error === 'no_access') {
// They need the full version.
} else {
signInButton.onclick = () => hub.signIn();
}- Hosted here: players who are signed in on the hub are signed in straight away.
hub.errorislogin_requiredwhen they are not, and the player bar shows a sign in link. - Your own website:
hub.signIn()takes the player to the hub to sign in and agree, then back to your page.hub.readyfinishes the sign in when they return. The sign in is kept for 30 days. Sign in from a title screen, since the page reloads.
4. Save and load
await hub.saves.put('slot1', { level: 3, coins: 120 });
const save = await hub.saves.get('slot1'); // null when empty
console.log(save.data.level, save.version);
// Projects and other files: pass a Blob, File, ArrayBuffer or typed array.
await hub.saves.put('project', projectBlob);
const project = await hub.saves.get('project'); // project.data is a Blob
const list = await hub.saves.list(); // [{ slot, content_type, bytes, version, updated_at }]
await hub.saves.remove('slot1');
hub.signOut();- Plain values and objects are saved as JSON and come back the same. Files and binary data are saved as they are and come back as a
Blob. - Up to 90 MB per save and 20 saves per player. For a bigger project, split it over several slots.
- Each player has 500 MB of cloud save space (more with a storage plan), shared by every game they use. When it runs out, saving fails with
storage_fulland the player is shown a popup with a link to their storage page, where they can see what is using the space and free some up. A save that does not get bigger is always allowed. To show your own message instead, useSynKrown.init({ app: 123, storagePopup: false }).await hub.saves.usage()gives{ used, limit }in bytes, if you want to show a meter. - Slot names use letters, numbers,
.,-and_, up to 64 characters. - To avoid one device overwriting another, pass the version you loaded:
hub.saves.put('slot1', data, { version: save.version }). If the save changed in the meantime this fails withversion_conflict. Use{ version: 0 }for "only if empty".
5. KrownOS desktop (optional)
Every member has a desktop at KrownOS. Your game or app can put things there, so players see their work and saves next to everything else.
// Show a save as an icon on their desktop. Opening it opens your game.
await hub.saves.put('slot1', data, { desktop: 'My castle' });
// Save a file to their desktop, or to a folder there named after it.
const file = await hub.desktop.save('Song.json', song, { folder: 'My songs' });
const files = await hub.desktop.list(); // only the files your app made
const loaded = await hub.desktop.load(file.id); // { data, version }
await hub.desktop.update(file.id, newSong, { version: loaded.version });
await hub.desktop.remove(file.id);
// Opened from an icon on the desktop?
if (hub.launch && hub.launch.file) openSong(await hub.desktop.load(hub.launch.file));
if (hub.launch && hub.launch.save) loadSlot(hub.launch.save);- Files work like saves: JSON comes back as the value, anything else as a
Blob. Up to 25 MB each. - Desktop files count towards the same cloud save space as saves.
- Your app only ever sees the files it made. Players can rename, move and delete them like any other file.
hub.launchis set for builds hosted here, when a player opens your app from one of its icons.
6. In-app purchases (optional)
Sell coins, extra lives, unlocks and anything else from inside your game or tool. Synkrown Hub takes the payment through Stripe, so you never handle card details, and keeps a record of every purchase for you and the player.
- Open your page in My pages and go to the Items tab. Cloud saves must be turned on, since purchases use the same sign in.
- Add an item. Its sku is the name your game asks for, like
coins_100.Consumable items can be bought again and again. Permanent items are bought once and kept. - Members sell through their own Stripe account, connected on the Selling page, the same way as the full version. The money goes straight to them, less any site fee.
// What is on sale. Permanent items say whether the player owns them.
const items = await hub.store.items();
// [{ sku, name, description, kind, price, price_cents, currency, owned }]
// From a click or tap, so the browser lets the payment tab open.
buyButton.onclick = async () => {
const purchase = await hub.store.buy('coins_100');
if (purchase) await deliver(purchase); // null when the player did not finish
};
// Hand the item over, then mark it as used.
async function deliver(purchase) {
if (purchase.kind === 'consumable') {
addCoins(100 * purchase.quantity);
await saveGame();
await hub.store.consume(purchase.id);
} else {
unlock(purchase.sku);
}
}
// When the game starts: anything paid for while it was closed.
for (const purchase of await hub.store.purchases()) await deliver(purchase);hub.store.buy(sku)opens Stripe's payment page in a new tab and waits until the payment is recorded. The game keeps running meanwhile. On builds hosted here, the player page shows a small box with a Continue to payment button first, since the build's sandbox cannot open payment pages itself.- Pass
{ quantity: 5 }to buy up to 99 of a consumable at once, and{ signal }(anAbortSignal) to stop waiting early. hub.store.purchases()lists consumables you have not marked as used yet, and every permanent item the player owns. Always check it when the game starts: the player may have closed the game before the payment finished.hub.store.consume(id)marks a consumable as handed over, so it stops showing inpurchases(). Give the item first, then consume it. Calling it twice is safe: the reply'salready_consumedistruewhen it was used before, so do not give the item again.- Prices start at 0.50, the lowest a card payment can be. Sell small amounts as packs, for example 100 coins for 0.99.
- A full refund removes a permanent item from
purchases(). Consumables that were already handed over stay with the player. - Players see everything they bought under In-game purchases in My account.
- On your own website, if your game runs inside an iframe, the iframe needs
allow-popups allow-popups-to-escape-sandboxfor the payment tab to work.
7. Ads (optional)
Show ads in a game or tool, and put extras behind an ad wall: the player watches a short ad and unlocks a bonus level, gets an hour of double coins or an extra life. Ads are only available on the site owner's own pages.
- Open the page in Dashboard, Apps and games, and go to the Ads tab.
- Tick Show ads and save. Google AdSense is picked for you, as it is the easiest to set up, and the site's publisher ID from Dashboard, Settings is used unless the tab names another. With no publisher ID at all and test mode on, the game shows built-in test ads, so you can build everything straight away.
- Add a reward for each thing behind an ad. Its key is the name your game asks for, like
bonus_level. It can be unlocked for good, for some hours (up to 30 days), or given every time, with an optional limit per player per day. - Follow the steps on the tab, then turn test mode off once Google approves your site. To use another network instead, see below.
const hub = SynKrown.init({
app: 123,
// Optional: pause and mute your game while an ad plays.
ads: { pause: () => game.pause(), resume: () => game.resume() },
});
await hub.ready;
if (await hub.ads.ready) showAdButtons(); // false when ads are off
// An ad wall
if (await hub.ads.unlocked('bonus_level')) openBonusLevel();
watchButton.onclick = async () => {
const result = await hub.ads.watch('bonus_level');
if (result.rewarded) openBonusLevel();
// otherwise result.reason is 'declined', 'skipped', 'no_ad' or 'busy'
};
// Something given every time, not kept by the hub
lifeButton.onclick = async () => {
if ((await hub.ads.watch('extra_life')).rewarded) lives += 1;
};
// An ad between levels
await hub.ads.break('level_done');
// A banner, and how to take it away again
const removeBanner = hub.ads.banner(document.getElementById('ad-box'));
const rewards = await hub.ads.rewards();
// [{ key, name, description, kind, hours, daily_limit, unlocked, expires_at, left_today }]hub.ads.watch(key)asks the player in a small box first, then plays the ad. Call it from a tap or click. Pass{ ask: false }when your own button already says what they get.- For signed in players the hub keeps the unlock, so
unlocked()stays true on every device. That needs cloud saves turned on, since it is the same sign in. Signed out players still see the ad andrewardedis stilltrue; only the keeping is skipped. result.rewardis the kept reward withunlockedandexpires_at, ornullwhen nothing was kept.hub.ads.break()shows an ad at most as often as the gap set on the Ads tab, and resolves totruewhen one was shown.- Banners use the ad unit ID from the Ads tab, or Google's auto ads if you switch them on in AdSense.
- Google only shows real ads on websites you own and have added to AdSense, so real AdSense ads show when your game runs on your own website. Test ads work everywhere, builds hosted here included.
- Ad networks tell your game, not the hub, that an ad was watched. The hub checks what it can, but someone could fake it, so keep anything worth real money as an item on the Items tab.
Another ad network (CrazyGames, Poki, GameDistribution, AppLixir and so on): pick Another ad network on the Ads tab, add that network's script as its docs say, and tell the hub how to show its ads. Rewards, limits and unlocks then work just the same.
const hub = SynKrown.init({
app: 123,
ads: {
// Resolve to true only when the ad was watched to the end.
rewarded: () => new Promise((done) => {
myNetwork.showRewardedAd({ onFinished: () => done(true), onSkipped: () => done(false), onError: () => done(false) });
}),
interstitial: () => new Promise((done) => myNetwork.showInterstitial({ onClose: done })),
banner: (element) => myNetwork.showBanner(element), // may return a function that removes it
},
});8. Leaderboard (optional)
Keep each signed in player's best score and show the top players, in your game or anywhere else.
- Open your page in My pages and go to the Leaderboard tab. Cloud saves must be turned on too, since scores use the same sign in.
- Tick Turn on the leaderboard.
- Set Most points per second: the fastest a really good player can earn points, with some room to spare. Set the Highest possible score too if your game has one.
// Anyone can see the board, signed in or not. null when it is off.
const top = await hub.scores.top(10);
// [{ rank, name, username, score, achieved_at }]
// Signed in players: start a run, check in as the score changes, post once.
const { run } = await hub.scores.start();
hub.scores.progress(run, score); // whenever the score changes
const result = await hub.scores.submit(run, finalScore);
// { score, best, rank, new_best }
const mine = await hub.scores.me(); // { score, rank, achieved_at }- Only the player's best score is kept. Equal scores go to whoever got there first.
- Call
progress()every time the score changes. It only reaches the hub every few seconds, always with the latest score, so calling it often costs nothing. The hub uses these check ins to make sure the score never climbs faster than your points per second allow. Time spent paused or away only counts for 60 seconds, so points cannot be saved up and posted later. - A score that climbs too fast, or goes over the highest possible score, ends the run with
too_fastortoo_high. Start a new run for the next game. - A run can be posted once, within a week. If your game lets players stop and carry on later, keep
runwith your own save. - A game runs on the player's device, so no check can stop every cheat. These make it slow and pointless, and the Leaderboard tab shows how long each run took so odd scores stand out. You can remove a score there, or hide a player: they still see their own score but are left off the board.
Your data stays yours
Saves are stored per app and per player. The app is taken from the player's sign in, never from the request, so another developer using the same slot names, or even your App ID, can never read or overwrite your players' saves. Players can disconnect an app, and delete its saves, from My account.
Errors
Failed calls throw an error with a code:
login_required,invalid_token: sign in again.no_access: the player needs the full version.access_denied: the player said no.version_conflict: the save changed;error.versionis the current version.storage_full: the player is out of space;error.usedanderror.limitare in bytes.too_large,too_many_slots,bad_slot,rate_limited.popup_blocked:buy()was not called from a click or tap.unknown_item: no item with that sku is on sale.already_owned: the player has that permanent item.email_unconfirmed: the player must confirm their email before buying;error.manage_urlleads there.not_for_sale,payments_unavailable: payments are not set up for this page right now.unknown_reward: no reward with that key on the Ads tab.already_unlocked: the player has unlocked it for good already.daily_limit: they have watched as many ads for it as they can today.scores_off: the leaderboard is not turned on.unknown_run: the run was already posted, ended or is over a week old.too_fast,too_high: the score broke the page's limits and the run was ended.
HTTP API
For engines without JavaScript. Send Authorization: Bearer TOKEN with every call. Replies are JSON, apart from reading a save.
GET /api/v1/me: the player and your app.GET /api/v1/saves: every save, without the data, plusstorage(space used and the limit).GET /api/v1/saves/SLOT: the save itself, exactly as it was sent, with itsContent-Type. The version and last change time are in theX-Save-VersionandX-Save-Updatedheaders.PUT /api/v1/saves/SLOT?version=N: the body is the save, any type, withContent-TypeandContent-Lengthset.versionis optional.DELETE /api/v1/saves/SLOTPUT /api/v1/saves/SLOT?desktop=NAME: also shows the save on the player's KrownOS desktop.GET /api/v1/files: the desktop files your app made, plusstorage.POST /api/v1/files?name=NAME&folder=FOLDER: a new desktop file. The body is the file;folderis optional. The reply is{ "id", "name", "version" }.GET /api/v1/files/ID,PUT /api/v1/files/ID?version=NandDELETE /api/v1/files/IDwork like the save calls.GET /api/v1/store: the items on sale.POST /api/v1/checkoutwith JSON{ "sku", "quantity" }: starts a payment. The reply is{ "id", "url", "expires_at" }; openurlin a browser.GET /api/v1/checkout/ID:{ "status" }isopen,expiredorcomplete(with thepurchase). Ask every few seconds.GET /api/v1/purchases: unused consumables and owned permanent items.POST /api/v1/purchases/ID/consume: marks a consumable as handed over.GET /api/v1/ads/config?app=ID: the page's ad settings and rewards. Needs no token.GET /api/v1/ads/rewards: every reward and where this player stands on it.POST /api/v1/ads/startwith JSON{ "key" }just before the ad plays: the reply is{ "ticket" }.POST /api/v1/ads/claimwith JSON{ "ticket" }once it was watched to the end keeps the reward. A ticket works once, for 15 minutes.GET /api/v1/scores?app=ID&limit=10: the best scores, up to 50. Needs no token. The reply is{ "enabled", "scores" }.GET /api/v1/scores/me: the player's best score and rank.POST /api/v1/scores/start: starts a run. The reply is{ "run", "expires_at" }.POST /api/v1/scores/progresswith JSON{ "run", "score" }: a check in. Send one every few seconds while the score changes, and at least once a minute.POST /api/v1/scores/submitwith JSON{ "run", "score" }: the final score, once per run. The reply is{ "score", "best", "rank", "new_best" }.
Getting a token is standard OAuth with PKCE (S256):
- Send the player to
https://synkrown.org/api/connect?app=ID&redirect_uri=URL&state=RANDOM&code_challenge=CHALLENGE. - They come back to
URL?code=...&state=..., or?error=.... - Within 5 minutes,
POST /api/v1/tokenwith JSON{ "code", "code_verifier", "redirect_uri" }. The reply is{ "token", "expires_at" }.