HTML5 / JavaScript API

Issues with this document? Submit a pull request to the website repository please.

Downloading the API

You can either download the zip or if you're a git user clone the repository.

Initializing the API

Before using the API you must initialize it with your public and private keys. Your keys need to be created in your database.

Playtomic.initialize(publickey, privatekey, apiurl);

Your apiurl will be in the format http://your-application-name.herokuapp.com/ or similar.

Examples

Each API has an extensive test library in the source code that demonstrates how to use every part in a variety of ways.

Newsletter subscription

Please note this requires additional setup you can read about here.

You can subscribe players to your newsletter mailinglist. By default this uses double-opt in so when a player registers for it they are sent an email and then confirm their intention.

You can collect additional data with your subscriptions but you must set it up first at MailChimp.

Playtomic.Newsletter.subscribe(options, callback);

Subscription options

Property Type Description
email String The player's email address
firstname String The player's first name
lastname String The player's last name
fields Object Container for custom MERGE tag name and values defined in your MailChimp list.

Subscribing a player

var subscription = {
	email: "[email protected]",
	firstname: "fred",
	lastname: "bloggs",
	fields: {
		FIRSTPLAYED: "2013-05-20",
		PLATFORM: "as3-web",
		GAMEVERSION: 1.08,
		RESOLUTION: "800x400"
	}
};

// note that these example MERGE fields must be created in your MailChimp
// dashboard, they do not exist by default.

Playtomic.Newsletters.subscribe(subscription, function(response) {

    if(response.success) {
    }
    else {
      // response failed because of response.errormessage
    }
});

Achievements

The Achievements API gives you two powerful ways to add social, cross-platform achievements to your game.

Achievements have to be configured in your database first in the 'achievements' collection with the structure:

{ achievement: "the name", achievementkey: "secret key used when awarding" }

You can include any additional properties you want and have them returned in your game such as image urls, descriptions etc.

Achievement structure

Property Type Description
playername String The player name. This can be by the player or provided by any 3rd party
playerid String Facebook or other userids, used for filtering by friends.
achievement String The name of the achievement.
source String The website or device the achievement occurred on
fields Object Any additional data you want to (or have) attached to an achievement like difficulty - that would mean for each achievement you automatically have 'easy', 'normal', 'hard' and can differentiate between them when retrieving the achievements.
Properties set by the API server
player Object When listing if a playerid is provided their details are included here when they have the achievement
friends Array When listing if a friendslist is provided any friends who have the achievement are included in this array.
Saving details
achievementkey String The secret key used when saving achievements by players
overwrite Boolean If the player already has the achievement save over it
allowduplicates Boolean If the player already has the achievement give it again

Saving achievements

To save an achievement you must know the achievement name and key and they must match what you configure in your database. This means if you want you can provide separate keys for each achievement so players can't easily cheat.

Playtomic.Achievements.save(achievement, callback);

A full example:

var achievement = {
  achievement: "Punched Tass",
  achievementkey: "abcdefgh",
  playerid: "1",
  playername: "ben",
  fields: {
    difficulty: "easy"
  }
}

Playtomic.Achievements.save(achievement, function(response) {

  if(response.success) {
    // note that we could still have a failure errorcode here when the player
    // already has an achievement
  }
  else {
    // response failed because of response.errormessage
  }

})

Listing achievements

Achievement lists can be requested that include just the achievement information or also incorporate the player and friends.

Playtomic.Achievements.list(options, callback);

Listing options

Property Type Description
playerid String Facebook or other userids, used for filtering by friends.
friendslist Array Friends' playerids
filters object Any additional filtering information from the 'fields'

Some examples:

// just the achievements
Playtomic.Achievements.list({}, function(achievements, response) {
  if(response.success) {
    for(var i=0; i<achievements.length; i++) {
      console.log(JSON.stringify(achievements[i]));
      // will output something { achievement: "Punched Tass" }
    }
  }
});

// my friends and i
var options = {
  playerid: "1",
  friendslist: ["2", "3", "4"]
};

Playtomic.Achievements.list(options, function(achievements, response) {
  if(response.success) {
    for(var i=0; i<achievements.length; i++) {
      console.log(JSON.stringify(achievements[i]));
      //{
      //  achievement: "Punched Tass",
      //  player: {
      //    playerid: "1",
      //    playername: "ben",
      //    date: Date(),
      //    rdate: "Just now",
      //    fields: {
      //      difficulty: "easy"
      //    }
      //  },
      //  friends: [
      //    {
      //      // same as player object but for any friends with the achievement
      //    }
      //  ]
      //}
    }
  }
});

Activity stream

You can also get achievements represented as an activity stream of each award.

Playtomic.Achievements.stream(options, callback);

Streaming options

Property Type Description
group Boolean If 'true' each person is only included once with their most recent award. If false it will include every award.
playerid String Facebook or other userids, used for filtering by friends.
friendslist Array Friends' playerids
filters object Any additional filtering information from the 'fields'
page int Page number to return (default is 1)
perpage int Results per page (default is 20)
mode string today, last7days, last30days
source string Device or website if you save that information

Award data

When you 'stream' the messages are returned in this format. This is the same format used when you include player or friend information in 'list'.

playername String The player name. This can be by the player or provided by any 3rd party
playerid String Facebook or other userids, used for filtering by friends.
date Date The date of the the achievement was awarded
rdate String The relative date of the achievement was awarded eg "7 minutes ago"
source string Device or website if you save that information
fields Object Any additional data you want to (or have) attached to an achievement like difficulty - that would mean for each achievement you automatically have 'easy', 'normal', 'hard' and can differentiate between them when retrieving the achievements.

Example streams

// show all the hard achievements by my friends and i as a stream
var options = {
  playerid: "1",
  friendslist: ["2", "3", "4", "5"],
  group: true,
  filters: {
    difficulty: "hard"
  }
}

Playtomic.Achievements.stream(options, function(achievements, numachievements, response) {

  if(response.success) {

        console.log(achievements.length + " achievements returned out of " + numachievements);

        for(var i=0; i<achievements.length; i++) {
            console.log(JSON.stringify(achievements[i]));
            // {
            //  playerid: "1",
            //  playername: "ben",
            //  date: Date(),
            //  rdate: "Just now",
            //  fields: {
            //     difficulty: "hard" }
            //  },
            //  awarded: {
            //    achievement: "Punched tass"
            //  }
            // }
        }
  } else {
    // request failed because of response.errormessage
  }


});

Leaderboards

The Leaderboards API gives you very flexible high and low score leaderboards. They can be created in your game dynamically or set up in the edit leaderboards page.

Score structure

Property Type Description
playername String The player name. This can be by the player or provided by any 3rd party
playerid String Facebook or other userids, used for filtering by friends.
points number The player's score
source String The website or device the score occurred on
fields Object Any additional data you want to (or have) attached to a score.
Properties set by the API server
date Date The date of the score
rdate String The relative date of the score eg "7 minutes ago"
rank int The rank based on your listing parameters.
Table detais
table String The name of the score table
highest Boolean The sort ordering by highest or lowest
allowduplicates Boolean Create duplicates, or override or reject scores if they're not the best

Submitting scores

Score submission is handled by:

Playtomic.Leaderboards.save(score, callback);
function submitScore() {
    // basic score
    var score = {
    playername: "ben",
    points: 173000,
    table: "highscores",
    allowduplicates: true
  };

    Playtomic.Leaderboards.save(score, submitComplete);

    // another score
    var score2 = {
    playername: "ben",
    points: 173000,
    table: "highscores",
    allowduplicates: true,
    fields: {
      character: "barbarian",
      level: 7,
      kills: 18
    }
  };

    Playtomic.Leaderboards.save(score2, submitComplete);
}

function submitComplete(response) {
    if(response.success) {
        console.log("Score saved!");
    } else {
        // submission failed because of response.errormessage with response.errorcode
    }
}

Showing scores

Scores are loaded via a simple method that returns an array of scores to your function where you can display the data in your leaderboard.

Playtomic.Leaderboards.list(options, callback);
Property Type Description
table String The name of the score table
highest Boolean The sort ordering by highest or lowest
allowduplicates Boolean Reject scores if they're not the player's best (default false) or allow multiple scores per player
filters Object Additional properties to filter by from the 'save' fields
source String The website or device the score occurred on
friendslist String[] Array of friend's playerids
playerid String A specific playerid
excludeplayerid Boolean For excluding the playerid as a filter when SaveAndListing
mode String Time limits, 'last7days', 'last30days', 'alltime' (default), 'today' and 'newest' which returns latest unsorted scores.
Pagination
page int Page number to return (default is 1)
perpage int Results per page (default is 20)
function showScores() {
  // table options
  var table = {
    table: "highscores",
    page: 1,
    perpage: 10,
    highest: true
  };

    Playtomic.Leaderboards.list(table, listComplete);
}

function listComplete(scores, numscores, response) {
    if(response.success) {
        console.log(scores.length + " scores returned out of " + numscores);

        for(var i=0; i<scores.length; i++) {
            var score = scores[i];
            console.log(" - " + score.name + " got " + score.points + " on " + score.sdate);

            // including custom data?  score.fields.property
        }
    } else {
        // score listing failed because of response.errormessage with response.errorcode
    }
}

Save and list

You can submit scores and at the same time return the leaderboard page that that score is on. This combines the Save and List approaches from above:

Playtomic.Leaderboards.saveAndList(score, callback)

Note: If you pass a 'playerid' to be saved you can exclude it from filtering the returned scores via the additional option, excludeplayerid = true

You don't specify a 'page', you specify the 'perpage' (default 20) and it will automatically decide which page to return based on the submitted score's rank. If you submit the 1187th best score at 30 per page then it will show you page 39, scores #1170 - #1200.

Ranks are returned so you are not viewing the top N scores you are viewing the top N scores from rank X onwards.

Level sharing

The level sharing API provides a way to store and retrieve user-generated content for your game. It can operate anonymously or authenticated via any 3rd party service you're already using.

Level structure

Saving and listing levels uses this class to represent a level.

Property Type Description
name String The level name.
playername String The player name.
playerid String Facebook or other userids, used for filtering by friends.
data string The created level data as a string
source String The website or device the score occurred on
fields Object Any additional data you want to (or have) attached to a level.

Saving levels

Playtomic.PlayerLevels.save(level, callback);

Example saving level:

function saveLevel() {
    var level = {
    name: "My level",
    data: "obj1=cannon&obj1x=120&obj1y=180",
    playername: "Ben"
  }

    PlayerLevels.save(level, saveComplete);
}

function saveComplete(level, response) {
    if(response.success) {
        console.log("Level saved successfully, the level id is " + level.levelid);
    } else {
        // failed because of response.errormessage with response.errorcode
    }
}

Rating levels

Levels can be rated 1 - 10 by players. Rating can be done anonymously with some protection against repeat voting, or bound to playerids if you specify them.

Playtomic.PlayerLevels.rate(levelid, rating, callback);

Example rating level:

function rate() {
  PlayerLevels.rate(level.levelid, 8, rateComplete);
}

function rateComplete(response) {
    if(response.success) {
        console.log("Rating complete"");
    } else {
        // Rating failed because of response.errormessage with response.errorcode
    }
}

Listing levels

Listing levels can be done by popular or newest, with optional filtering by date ranges and/or custom fields.

PlayerLevels.list(options, callback);

Listing options

Property Type Description
mode String
  • alltime
    The most popular levels based on all time ratings
  • newest
    The most recently created levels
  • recentaverage
    Average calculated across just the last 100 votes a level received
  • todayaverage | yesterdayaverage | last7daysaverage | last30daysaverage | last90daysaverage
    Aggregated rating averages on / in the specified timeframe
datemin String 'mm/dd/yyyy' for the minimum date the level was created.
datemax String 'mm/dd/yyyy' for the maximum date the level was created.
playerid String Facebook or other userid
friendslist String[] Array of friend's playerids
data Boolean Return the level data with the request (maybe faster to load individually)
source String The website or device the level was created on
filters Object Any additional data you want to (or have) attached to a level.
Pagination
page int Page number to return (default is 1)
perpage int Results per page (default is 20)

An example listing levels:

function list() {
  var listoptions = {
    mode: "newest",
    data: false,
    perpage: 30,
    filters: {
      difficulty: "hard"
    }
  };

    PlayerLevels.list(listoptions, listLoaded);
}

function listLoaded(levels, numlevels, response) {
    if(response.success) {
        for(var i=0; i<levels.length; i++) {
            console.log(" - " + levels[i].levelid + ": " + levels[i].name);
        }
    } else {
        // Level list failed to load because of response.errormessage with response.errorcode
    }
}

Loading levels

If you do not include the data when you load lists of levels then you can request it seperately.

Playtomic.PlayerLevels.load(levelid, callback)

An example loading a single level:

function load() {
    PlayerLevels.load(level.levelid, loadComplete);
}

function loadComplete(level, response) {
    if(response.success) {
        console.log("Level has been loaded, now you can begin playing it");
    } else {
        // level failed to load because of response.errormessage with response.errorcode
    }
}

GameVars

GameVars let you change the value of key variables in your game any time you want.

Setting them up in your database

In your MongoHQ dashboard add a new entry to the "gamevars" collection.

{
  name: "basehitpoints",
  value: 800
}

Loading

They are loaded via:

Playtomic.GameVars.load(callback);

You can load variables individually, for instance if you are caching the GameVars you can check a 'version' GameVar to decide whether to reload the full collection.

Playtomic.GameVars.loadSingle("name", callback);

The callback parameter is your function that receives an object that has properties matching the variables you have configured in your database. The callback is the same for all or single GameVars.

// our variables with default, original values
var basehitpoints = 100;
var basegold = 50;

function initialiseGame() {
    // load GameVars
    Playtomic.GameVars.load(gameVarsLoaded);
    // or Playtomic.GameVars.loadSingle("basehitpoints", gameVarsLoaded);

    // carry on initializing your game
}

function gameVarsLoaded(vars, response) {
    if(response.success) {
        // sync the in-game variables
        basehitpoints = vars.basehitpoints;
        basegold = vars.basegold;
    } else {
        // request failed because of response.errormessage with response.errorcode
    }
}

Geolocation

The GeoIP service identifies which country the player is from, returning their country code and name.

It is called via:

Playtomic.GeoIP.lookup(callback);

The callback function receives an object that has 'code' and 'name' properties:

Playtomic.GeoIP.lookup(setPlayerCountry);

function setPlayerCountry(country, response) {
    if(response.success) {
        // we have the country data
        console.log("Player is from " + country.code + " / " + country.name);
    } else {
        // request failed because of response.errormessage with response.errorcode
    }
}