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

  1. Open your page in My pages and go to the Cloud saves tab.
  2. Tick Turn on cloud saves and note your App ID.
  3. Optional: tick Only for owners of the full version. Players who have not bought it are then refused.
  4. 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();
}

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();

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);

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.

  1. 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.
  2. 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.
  3. 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);

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.

  1. Open the page in Dashboard, Apps and games, and go to the Ads tab.
  2. 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.
  3. 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.
  4. 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 }]

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.

  1. 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.
  2. Tick Turn on the leaderboard.
  3. 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 }

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:

HTTP API

For engines without JavaScript. Send Authorization: Bearer TOKEN with every call. Replies are JSON, apart from reading a save.

Getting a token is standard OAuth with PKCE (S256):

  1. Send the player to https://synkrown.org/api/connect?app=ID&redirect_uri=URL&state=RANDOM&code_challenge=CHALLENGE.
  2. They come back to URL?code=...&state=..., or ?error=....
  3. Within 5 minutes, POST /api/v1/token with JSON { "code", "code_verifier", "redirect_uri" }. The reply is { "token", "expires_at" }.