MINIPLAY C2S JAVASCRIPT API
APIs for casual & social games

Preface:

Please help us improving it by reporting us any bugs or suggestions to [email protected], we put our best efforts in order to make life easier for you and the other developers, and your help will be greatly appreciated.

In this document we’ll dig into the JAVASCRIPT API for connecting to our services from any game capable of reaching the Javascript layer of the browser, be it pure HTML+Javascript based or plugin based like Shockwave, Unity or Flash (although there’s an ActionScript 3 API available). Please refer to the MINIPLAY APIs OVERVIEW document first if you haven’t read it yet, knowledge of the concepts explained there is required.

As a convention, we will use red for required parameters and blue for optional parameters. Also be noticed that every timestamp is handled with a precision of milliseconds (POSIX timestamps only have a precision of seconds).

1. Introduction

The Javascript API allows you to connect to our services in read-only mode, right from the user browser. In case of internal games (those that run inside our site sandbox, be them hosted by us or pointed to a custom URL), the API provides your game interoperability with our site as well, (i.e.: opening the login dialog, a scoreboard, purchase items, maximize the game...). In case of external games, the API automatically detects them and provides methods to allow your users authenticate by using their Miniplay account, that’s what we call Miniplay connect*, we’ll talk about it later (although other methods designed for internal interoperability will be disabled).

If your game is hosted by us, this API is automatically loaded on your sandbox.

* You must ask for permission if you want to use this API in an external site so we enable Miniplay connect for you

2. Read only mode

We don’t allow writes through this API because we want to keep the users from sending fake in-game statistics (that will reward them with achievements, experience and gems), if that happens, all the highscores wouldn’t mean anything and the global experience will be ruined. That’s not what we want, we’ll work hard to have fair scores, in case any user that is detected cheating will be penalized and we’ll urge you to patch the game.

To perform writes you can use the Server 2 Server REST API (secure) or the Client 2 Server Actionscript 3 API (which can also be hacked, but it’s a lot harder because the connections are fully encrypted).

UPDATE: Since the rise of HTML5 games we will allow full write permissions for your API if you request us to do it (not by default). Just please notice that these requests can be easily simulated by the users, so, we don't recommend using any kind of highscores or providing big rewards for achievements.

3. API Loading

If your game is running inside our sandbox, it’s also hosted by us, and it has the API enabled, it will be automatically loaded, so, you can skip this chapter.

For games not hosted by us, running either within in an iframe or completely external, the API must be loaded in the head section of your HTML.

<!-- Load Miniplay JS API Synchronously! --> <script id='LeChuckAPIjs' src="https://ssl.minijuegosgratis.com/lechuck/js/latest.js"></script> <!-- Create an instance of the Miniplay JS API! --> <script type='text/javascript'> var lechuck = new LeChuckAPI({}); </script>

This creates a new instance of the Miniplay JS API and allows it to be globally used. For simplicity and ease of use, the loading is done synchronously, do not try to make it asynchronous or it will fail. The static file will reside in our high availability CDN, so loading it synchronously shouldn’t be a concern. You can use whatever variable name you want for the instance, just remember it and do not create new instances.

For your convenience we've created a sandbox template (in php) that you can just download and put into your server to act as a game launcher. It automatically takes care of all received parameters, validates their signature (important!), initializes the JS API for you and checks the user status.

Download the sandbox template here: https://gist.github.com/miniplay/4996722

Additionally, we've created a sandbox template + a small demo of the Javascript API.

Download the sandbox JS API demo here: https://gist.github.com/miniplay/5003037

3.1 Options

Our API automatically detects all the parameters that our site sandbox sends to you (Read MINIPLAY APIs OVERVIEW section 10), so, no configuration options are needed unless you’re including the API in an external game (that runs in your own site). Anyway, these are the configuration options that can be set in the object provided (all are optional, id is required only for external games).

  • id number api_id (Read MINIPLAY APIs OVERVIEW section 12)
  • debug boolean enable or disable logging debug messages to the console
  • user_id string Automatically logs the user provided (with user_token)
  • user_token string Automatically logs the user provided (with user_id)
  • url string url for ajax connections to the backend (can be ignored)
  • flash_object string dom id of the flash game (if it uses the AS3 API)

You can make your game both external/internal, just make sure to provide the right user_id & user_token options or omit them and let the API to automatically detect them from the url params mp_api_user_token & mp_api_user_id (Read MINIPLAY APIs OVERVIEW section 10).

3.2 Games that have page reloads or url navigation

A lot of social games have navigation between different urls, if your game is internal and runs inside our sandbox, this can be a serious issue: reloading the page will work (with document.location.reload()) seamlessly but changing the url after the API has been loaded will disable our crossdomain bridge if you don't pass along our XDM parameters (i.e. &xdm_c=defaultXXXX&xdm_p=1), therefore, any communication between your game and our site will be blocked and the communications with our site won't work properly.

Said that, there is an easy workaround for this, you can create a bridge page which loads the API and create a new iframe inside it to your real, navigable game, that way, you can still access the API by using the parent object, it won’t be reloaded and everything will work as expected.

4. Debugging & logging

You can enable or disable automatic logging to the browser console (if available) by calling the setDebug( boolean flag ) method.

For hosted sandboxed games the logging is automatically enabled if the game is in devel mode.

5. Integration with the ActionScript 3 API (only for flash games)

The Javascript API (this one) is required to use our ActionScript 3 API. That way, we can relay all the events that the Javascript API receives to it, and call the AS3 API callbacks when needed (i.e. when the user completes a purchase, or logs in with Miniplay connect).

By default, the Javascript API tries to find the flash game by looking for a DOMObject with a ‘MPFlashGame’ id (that’s the id we use for our hosted, sandboxed games), but you can specify your own custom id if needed. Should it fail to find the object, it will fail silently. We provide 2 methods to manage the current flash object.

5.1 setFlashObject( string | DOMObject flashObject )

Sets the flashObject by specifying the DOMObject id or the DOMObject instance.

5.2 getFlashObject()

Gets the DOMObject instance (if available).

6. API modules

The API instance contains the following objects:

  • EVENTS
  • ENVIRONMENT
  • USER
  • STAT
  • HIGHSCORE
  • ITEM

7. EVENTS module

The events module allows you to register a handful set of custom listeners, just provide your callback function as a parameter and it will be automatically called. You can register as much listeners as you want, even of the same type. As time goes on, there will be more event listeners available.

7.1 onDocumentReady( Function callback )

Executes it when the document has finished loading and the DOM is ready.

7.2 onApiReady( Function callback )

Executes it when the API is connected and the user (if sent as option or if it’s detected from the url parameters) is authenticated. This is when you can start doing things with the API, here’s a working example:

// Check if the API instance exists if (lechuck instanceof Object) { // Attach an onReady event listener to be dispatched once the api is ready! // if the api is ready it will be automatically dispatched lechuck.events.onApiReady(function() { if(lechuck.user.isGuest()) { alert("API ready, guest user, show a 'please log-in' message."); } else { alert("API ready, welcome back "+lechuck.user.getUid()+"!"); } }); // Initializing api... // You should wait until it's ready, this is a good place to show a loader }

7.3 onUserDisconnect( Function callback )

Executes it when the user was authenticated and it disconnects (may happen if the user has multiple windows and closes the session).

7.4 onPlayerResize( Function callback )

Executes it when the game container is resized.

8. ENVIRONMENT module

The environment module allows you to interact with the game environment, in other words, to communicate with our site. This module is disabled for external games.

8.1 isInternal()

Returns true if the game is running inside our site, false otherwise.

8.2 isExternal()

Returns true if the game is not running inside our site, false if it’s internal.

8.3 toComments()

Scrolls to the comments section.

8.4 toControls()

Scrolls to the controls section.

8.5 toDescription()

Scrolls to the description section.

8.6 toSimilarGames()

Scrolls to the similar games section.

8.7 toCollectionGames()

Scrolls to the games of the same collection section.

8.8 toSagaGames()

Scrolls to the games of the same saga section.

8.9 isMobile()

Returns true if the game is running in our mobile site, false otherwise.

8.9 toAchievements()

Opens the game achievements or navigate to them if they’re already opened.

8.10 toHighscoreGlobal( string hs_uid, string timespan = “TOTAL” )

Opens the game global scoreboard (for all users) specified at hs_uid. * Feature not supported in our mobile sites

Supported timespans: TOTAL, DAY, WEEK, MONTH.

// Show best points scoreboard for last 24 hours lechuck.environment.toHighscoreGlobal("best_points","DAY");

// Show best points scoreboard for last 24 hours
lechuck.environment.toHighscoreGlobal(
"best_points","DAY");

8.11 toHighscoreFriends( string hs_uid )

Opens the game friends scoreboard (for an user) specified at hs_uid. * Feature not supported in our mobile sites

// Show best points scoreboard only for the users followed by the logged user lechuck.environment.toHighscoreFriends("best_points");

// Show best points scoreboard only for the users followed by the logged user
lechuck.environment.toHighscoreFriends(
"best_points");

8.12 PLAYER submodule

The player submodule is an object inside the environment module that allows you to obtain information about our game player (the player is the sandbox iframe with the hosted game or with your game url).

8.12.1 isScalable()

Returns true if the game can be maximized, false otherwise. * Feature not supported in our mobile sites

8.12.2 isMaximized()

Returns true if the game is maximized, false otherwise. * Feature not supported in our mobile sites

8.12.3 maximize()

Request the game to be maximized, false otherwise. * Feature not supported in our mobile sites

8.12.4 minimize()

Request the game to be minimized (remember: the minimized version is just the small player). * Feature not supported in our mobile sites

8.12.5 getSize()

Returns the original player dimensions.

lechuck.environment.player.getCurrentSize() == {"width":"100%","height":"100%"}

8.12.6 getCurrentSize()

Returns the current player dimensions.

lechuck.environment.player.getCurrentSize() == {"width":944,"height":256}

8.12.7 getViewType()

Returns a string with the default player type for the game, “small”, “large” or “fullscreen” (Read MINIPLAY APIs OVERVIEW section 12). * Feature not supported in our mobile sites

8.12.8 getCurrentViewType()

Returns a string with the current player type for the game, “small”, “large” or “fullscreen”. It should match the default view type but it could change if you use the resize API. * Feature not supported in our mobile sites

8.12.9 isResizable()

Returns true if the resize API is available, false otherwise. Contact us to request access. * Feature not supported in our mobile sites

8.12.10 setSize( number width, number height ) Requires the resize API to be available

* Feature not supported in our mobile sites

Allows you to change the sandbox player size in pixels. It automatically changes the view type between "small" and "large". Specially useful if you’ve got a flexible height game. Call it whenever your game width/height* changes:

lechuck.environment.player.setSize(980, document.height); // 980 x our height * Max: width 980px, Height 1400px, for greater dimensions please request us the fullscreen mode for your game

* Max: width 980px, Height 1400px, for greater dimensions please request us the fullscreen mode for your game

8.12.11 resetSize() Requires the resize API to be available

Resets the sandbox player size to it’s defaults. * Feature not supported in our mobile sites

8.12.12 setViewportScale(number)

Since your game will run inside an iframe, any viewport modification you do won't be applied by the device browser. With this method you can change our viewport size to your needs: just provide a scale number and the viewport initial-scale, minimum-scale & maximum-scale properties will be set accordingly. A resize event will be automatically triggered, check the EVENTS module for more information. * Feature ONLY supported in our mobile sites

8.12.12 hideOverlay()

On our mobile sites, a tiny 'miniplay' button is shown in the bottom-right corner to let the users track their unlocked achievements, rate your game, favorite it and go back to our site. This method allows you to hide it. Only hide the overlay if it collides with your UI. * Feature ONLY supported in our mobile sites

8.12.12 showOverlay()

On our mobile sites, a tiny 'miniplay' button is shown the bottom-right corner to let users track their unlocked achievements, rate your game, favorite it and go back to our site. This method allows you to show it if it was previously hidden. Only hide the overlay if it collides with your UI. * Feature ONLY supported in our mobile sites



8.13 SHARING, INVITATIONS & CHALLENGES TO OTHER USERS

* Module not yet supported in our mobile sites

Sharing is part of the environment module. For games running inside our site you can trigger the game sharing, invite friends or even challenge them providing custom parameters that you can detect later (they will be sent to your game as GET parameters or flashvars in case of flash games).

For the moment, game invites & game challenges are suported. We plan to extend the support to other kind of messages like gifts & requests soon.

Internal invitantions can only be sent to friends of the user, those are the users that are mutually following each other, because private messaging are restricted to them.

8.13.1 toShare()

Opens the STANDARD SHARE game dialog, it's an alias for the toUserShare() method in order to provide backwards compatibility. It's just a STANDARD INVITATION.

8.13.2 toUserShare(Array userIds, Object customParameters, Function callback(Bool success, Array userIds) {} )

Opens the INVITE USER/s dialog, with both social networks & miniplay community sharing capabilities. The recipients will receive a private message and a realtime notification if they're browsing our sites.

  • Array userIds (optional, [] by default) autoadd the specified users (providing they're friends of the user performing the action) to the dialog
  • Object customParameters (optional, {} by default) Custom GET parameters that will be appended to your game when the recipients access it from the link received (i.e {"invite_id":30012,"invited_by":"demo_user"})
  • Function callback (optional) Custom Callback function when the modal is closed, it will receive 2 parameters, a first parameter true/false with the success status, and a second parameter with an Array of userIds that were invited/challenged

8.13.3 toUserChallenge(Array userIds, Boolean allowAddUsers, Boolean allowMultiUser, Object customParameters, Function callback(Bool success, Array userIds) {} )

Opens the CHALLENGE USER/s dialog (MATCH-MAKING), with just miniplay community sharing capabilities. Recipients will receive a private message and a realtime notification if they're browsing our sites.

  • Array userIds (optional, [] by default) autoadd the specified users (providing they're friends of the user performing the action) to the dialog.
    Provide an empty array [] for no completion. For 1 user, provide a 1 item array.
  • boolean allowAddUsers (optional, false by default) Allows the user to add other users, or just keep the one/s provided. For challenges, it's recommended that you provide the user ids and forbid the user to pick another ones.
  • boolean allowMultiUser (optional, true by default) Allows or prevent the user to challenge more than just one user, true by default (more than 1 user allowed).
  • Object customParameters (optional, {} by default) Custom GET parameters that will be appended to your game when the recipients access it from the link received (i.e {"challenge_date":"2013-01-01","challenge_id":300035012,"challenged_by":"demo_user"})
    Use them to send the invitation hash that your game generates for match-making
  • Function callback (optional) Custom Callback function when the modal is closed, it will receive 2 parameters, a first parameter true/false with the success status, and a second parameter with an Array of userIds that were invited/challenged

9 USER module

Allows you to manage the current logged user or to authenticate one, the user will be automatically connected if the user_id and user_token are set as options or automatically detected from the mp_api_user_id & mp_api_user_token url parameters.

You must assume that by default, your game will receive guest users, and, only if the user is logged in in our site, you’ll receive the mp_api_user_id and mp_api_user_token parameters. So, if your game only works for authenticated users you must check the current status:

// Check if the API instance exists if (lechuck instanceof Object) { // Attach an onReady event listener to be dispatched once the API is ready! // if the API is ready it will be automatically dispatched lechuck.events.onApiReady(function() { // Is the user logged in? if(lechuck.user.isGuest()) { // REQUIRE THE GUEST USER TO LOG IN // Just show a 'please log in message' and attach the action to the // lechuck.user.login() method, the API will handle the login. // REGISTRATION // You can also create a registration buton tied to the // lechuck.user.register() method, the API will handle the registration. } else { // THE USER IS LOGGED IN // alert("Welcome back "+lechuck.user.getUid()+", let’s play!"); } }); // Initializing API ... // You should wait until it's ready, this is a good time to show a loader }

Please see the document MINIPLAY APIs OVERVIEW. Handling guests users for more information.

All users grant you permissions to access their user_token just by playing your game, there’s no need for them to grant you any special privileges.

9.1 isGuest()

Returns true if the user is not logged in, false otherwise (the user is logged in).

9.2 getId()

Returns the user id of the logged user. This field is immutable, it will be always the same.

9.3 getUid()

Returns the user uid (alias) of the logged user. This field is mutable, the user can change it and a different user could use it later, never use it as the unique identifier of the user.

9.4 getLevel()

Returns the progress level of the logged user.

9.5 getAvatar()

Returns the default avatar url of the logged user (head) (96x96px jpg). This asset is immutable (you can store this url and you’ll always get the latest version).

9.6 getAvatarMini()

Returns the default avatar url of the logged user (head) in small format (32x32px jpg). This asset is immutable (you can store this url and you’ll always get the latest version).

9.7 getAvatarBig()

Returns the default avatar url of the logged user (head) in big format (256x256px jpg). This asset is immutable (you can store this url and you’ll always get the latest version).

9.8 getAvatarAlpha()

Returns the default avatar url of the logged user (head) in standard, transparent format (96x96px png). This asset is immutable (you can store this url and you’ll always get the latest version).

9.9 getAvatarBody()

Returns the default avatar url of the logged user (full body) in standard, transparent format (160x220px png). This asset is immutable (you can store this url and you’ll always get the latest version).

9.10 login()

Opens the login dialog for authentication if the game is internal or initiates the Miniplay connect workflow (by opening a popup to our site, crossdomain issues are automatically handled by our API), once completed, the page is refreshed (In external games, your page will be reloaded in order to to receive the mp_api_user_id and mp_api_user_token url parameters).

9.11 register()

Opens the registration dialog if the game is internal, (external games not supported), once completed, the page is refreshed.

9.12 die()

Logs out the current user, only works for external games, for internal games users cannot be logged out.

9.13 authenticate( Function callback, string user_id, string user_token )

Authenticates an user token and sets it as logged if it’s valid, a response object is sent as the first parameter to the callback with the properties:

  • boolean isValid
  • string errorType in case of error (false on success)
  • string errorMessage (false on success)

9.14 get( Function callback, string user_id, string user_token )

Gets an user detail, if no user_token is provided, the public detail will be retrieved; if provided and it’s valid, the full detail will be retrieved. If no user_id provided, the current logged user will be assumed (if any).

A response object is sent as the first parameter to the callback with the properties:

  • Object userData Here’s the full user data (if the user_token is provided):
{ "id":"2", /* 32 bit number as string (immutable) */ "uid":"demo_user_2", /* 32 character string (mutable) */ "gender":"M", /* (M)ale,(F)emale */ "name":"xxxxxx", /* only for selected developers (may be empty) */ "surname":"yyyyyy", /* only for selected developers (may be empty) */ "email":"user@host.com", /* only for selected developers */ "date_birth":"1970-12-30", /* YYYY-mm-dd */ "locale":"en_US", /* user locale string or property not present for null */ "avatar":"http://beta.miniplay.com/....../default/head_96x96.jpg", "avatar_mini":"http://beta.miniplay.com/....../default/head_32x32.jpg", "avatar_big":"http://beta.miniplay.com/....../default/head_256x256.jpg", "avatar_alpha":"http://beta.miniplay.com/....../default/head_96x96.png", "avatar_body":"http://beta.miniplay.com/....../default/body_160x220.png", "profile":"http://beta.miniplay.com/profile/demo_user_2", "social_total_followers":10, /* 32 bit number */ "social_total_subscriptions":15, /* 32 bit number */ "social_total_friends":10, /* 32 bit number */ "progress_points":2795, /* 32 bit number */ "progress_level":14, /* 32 bit number */ "progress_level_points_max":3061, /* 32 bit number */ "progress_level_points_min":2683 /* 32 bit number */ }
  • string errorType in case of error (false on success)
  • string errorMessage (false on success)

Please notice that some fields will only be provided to selected developers prior mutual agreement.

9.15 subscriptions( Function callback, Object options )

This is probably the most important list for game developers. Gets the subscriptions list of the logged user (who he/she follows), ordered by descending timestamp, can be easily paginated by using the timestamps. Every user in the list will contain the time property corresponding to the millisecond timestamp when the event occurred (in this case, the subscription of the user).

The following options are supported:

  • boolean withProgress include each user progress level
  • boolean withDetail include each user basic detail (true by default)
  • boolean withInstalled to include the installed flag (has played the game?, false by def.)
  • number limit number of items to retrieve (20 by default, 99 max)
  • number fromTimestamp oldest timestamp (in milliseconds), inclusive
  • number toTimestamp newest timestamp (in milliseconds), exclusive

A response object is sent as the first parameter to the callback with the properties:

  • Array subscriptions an array of user objects
[ { "id":"19", /* 32 bit number as string (immutable) */ "uid":"demo_user_19", /* 32 character string (mutable) */ "avatar":"http://beta.miniplay.com/....../default/head_96x96.jpg", "avatar_mini":"http://beta.miniplay.com/....../default/head_32x32.jpg", "avatar_big":"http://beta.miniplay.com/....../default/head_256x256.jpg", "avatar_alpha":"http://beta.miniplay.com/....../default/head_96x96.png", "avatar_body":"http://beta.miniplay.com/....../default/body_160x220.png", "profile":"http://beta.miniplay.com/profile/demo_user_2", "progress_points":190, /* 32 bit number */ "progress_level":2, /* 32 bit number */ "progress_level_points_max":220, /* 32 bit number */ "progress_level_points_min":100, /* 32 bit number */ "time":1359977519115 /* 64 bit number */ "is_friend":false, /* boolean, is this user a friend? */ "is_installed":false /* boolean, has this user played this game? (if requested) */ }, { "id":"14", /* 32 bit number as string (immutable) */ "uid":"demo_user_14", /* 32 character string (mutable) */ "avatar":"http://beta.miniplay.com/....../default/head_96x96.jpg", "avatar_mini":"http://beta.miniplay.com/....../default/head_32x32.jpg", "avatar_big":"http://beta.miniplay.com/....../default/head_256x256.jpg", "avatar_alpha":"http://beta.miniplay.com/....../default/head_96x96.png", "avatar_body":"http://beta.miniplay.com/....../default/body_160x220.png", "profile":"http://beta.miniplay.com/profile/demo_user_14", "progress_points":1810, /* 32 bit number */ "progress_level":11, /* 32 bit number */ "progress_level_points_max":2024, /* 32 bit number */ "progress_level_points_min":1740, /* 32 bit number */ "time":1358357279751 /* 64 bit number */ "is_friend":false, /* boolean, is this user a friend? */ "is_installed":false /* boolean, has this user played this game? (if requested) */ } ]
  • string errorType in case of error (false on success)
  • string errorMessage in case of error (false on success)

Here’s a demo code that echoes to console the last 5 followers of the logged user:

lechuck.user.subscriptions(function(response){ if (response.errorType || !response.subscriptions) { alert("Something went wrong: "+response.errorMessage); } else { console.log("Last 5 subscriptions:"); for (var i=0;i<response.subscriptions.length;i++) { console.log( "User " + response.subscriptions[i].uid + " (level " + response.subscriptions[i].progress_level + ") - " + (response.subscriptions[i].is_friend ? "friend":"not friend")+ " - " + (response.subscriptions[i].is_installed ? "installed":"not installed") ); } } }, {"withInstalled": true, "withProgress": true, "limit":5});

9.16 friends( Function callback, Object options )

Gets the friends list of the logged user (who are followed by and following user), ordered by descending timestamp, can be easily paginated by using the timestamps. Every user in the list will contain the time property corresponding to the millisecond timestamp when the event occurred (in this case, when the friendship).

The following options are supported:

  • boolean withProgress include each user progress level
  • boolean withDetail include each user basic detail (true by default)
  • boolean withInstalled to include the installed flag (has played the game?, false by def.)
  • number limit number of items to retrieve (20 by default, 99 max)
  • number fromTimestamp oldest timestamp (in milliseconds), inclusive
  • number toTimestamp newest timestamp (in milliseconds), exclusive

A response object is sent as the first parameter to the callback with the properties:

Array friends an array of user objects

[ { "id":"19", /* 32 bit number as string (immutable) */ "uid":"demo_user_19", /* 32 character string (mutable) */ "avatar":"http://beta.miniplay.com/....../default/head_96x96.jpg", "avatar_mini":"http://beta.miniplay.com/....../default/head_32x32.jpg", "avatar_big":"http://beta.miniplay.com/....../default/head_256x256.jpg", "avatar_alpha":"http://beta.miniplay.com/....../default/head_96x96.png", "avatar_body":"http://beta.miniplay.com/....../default/body_160x220.png", "profile":"http://beta.miniplay.com/profile/demo_user_2", "progress_points":190, /* 32 bit number */ "progress_level":2, /* 32 bit number */ "progress_level_points_max":220, /* 32 bit number */ "progress_level_points_min":100, /* 32 bit number */ "time":1359977519115 /* 64 bit number */ "is_friend":false, /* boolean, is this user a friend? (always true for this list) */ "is_installed":false /* boolean, has this user played this game? (if requested) */ }, { "id":"14", /* 32 bit number as string (immutable) */ "uid":"demo_user_14", /* 32 character string (mutable) */ "avatar":"http://beta.miniplay.com/....../default/head_96x96.jpg", "avatar_mini":"http://beta.miniplay.com/....../default/head_32x32.jpg", "avatar_big":"http://beta.miniplay.com/....../default/head_256x256.jpg", "avatar_alpha":"http://beta.miniplay.com/....../default/head_96x96.png", "avatar_body":"http://beta.miniplay.com/....../default/body_160x220.png", "profile":"http://beta.miniplay.com/profile/demo_user_14", "progress_points":1810, /* 32 bit number */ "progress_level":11, /* 32 bit number */ "progress_level_points_max":2024, /* 32 bit number */ "progress_level_points_min":1740, /* 32 bit number */ "time":1358357279751 /* 64 bit number */ "is_friend":false, /* boolean, is this user a friend? (always true for this list) */ "is_installed":false /* boolean, has this user played this game? (if requested) */ } ]
  • string errorType in case of error (false on success)
  • string errorMessage in case of error (false on success)

9.17 followers( Function callback, Object options )

Gets the followers list of the logged user, ordered by descending timestamp, can be easily paginated by using the timestamps. Every user in the list will contain the time property corresponding to the millisecond timestamp when the event occurred (in this case, the following of the provided user).

The following options are supported:

  • boolean withProgress include each user progress level
  • boolean withDetail include each user basic detail (true by default)
  • number limit number of items to retrieve (20 by default, 99 max)
  • number fromTimestamp oldest timestamp (in milliseconds), inclusive
  • number toTimestamp newest timestamp (in milliseconds), exclusive

A response object is sent as the first parameter to the callback with the properties:

  • Array followers an array of user objects
[ { "id":"19", /* 32 bit number as string (immutable) */ "uid":"demo_user_19", /* 32 character string (mutable) */ "avatar":"http://beta.miniplay.com/....../default/head_96x96.jpg", "avatar_mini":"http://beta.miniplay.com/....../default/head_32x32.jpg", "avatar_big":"http://beta.miniplay.com/....../default/head_256x256.jpg", "avatar_alpha":"http://beta.miniplay.com/....../default/head_96x96.png", "avatar_body":"http://beta.miniplay.com/....../default/body_160x220.png", "profile":"http://beta.miniplay.com/profile/demo_user_19", "progress_points":190, /* 32 bit number */ "progress_level":2, /* 32 bit number */ "progress_level_points_max":220, /* 32 bit number */ "progress_level_points_min":100, /* 32 bit number */ "time":1359977519115 /* 64 bit number */ }, { "id":"14", /* 32 bit number as string (immutable) */ "uid":"demo_user_14", /* 32 character string (mutable) */ "avatar":"http://beta.miniplay.com/....../default/head_96x96.jpg", "avatar_mini":"http://beta.miniplay.com/....../default/head_32x32.jpg", "avatar_big":"http://beta.miniplay.com/....../default/head_256x256.jpg", "avatar_alpha":"http://beta.miniplay.com/....../default/head_96x96.png", "avatar_body":"http://beta.miniplay.com/....../default/body_160x220.png", "profile":"http://beta.miniplay.com/profile/demo_user_14", "progress_points":1810, /* 32 bit number */ "progress_level":11, /* 32 bit number */ "progress_level_points_max":2024, /* 32 bit number */ "progress_level_points_min":1740, /* 32 bit number */ "time":1358357279751 /* 64 bit number */ } ]
  • string errorType in case of error (false on success)
  • string errorMessage in case of error (false on success)

Here’s a demo code that echoes to console the last 5 followers of the logged user:

lechuck.user.followers(function(response){ if (response.errorType || !response.followers) { alert("Something went wrong: "+response.errorMessage); } else { console.log("Last 5 followers:"); for (var i=0;i<response.followers.length;i++) { console.log( "User " + response.followers[i].uid + " (level " + response.followers[i].progress_level + ")" ); } } }, {"withProgress": true, "limit":5});

9.18 subscriptionStatus(Function callback, int user2_id, boolean withInstalled)

Checks if an user is subscribed (follows) to another one (user2_id), set withInstalled flag to true if you want to retrieve the is_installed flag as well (if the user has played the game)

A response object is sent as the first parameter to the callback with the properties:

  • boolean is_subscribed Is the user subscribed to user2_id?
  • boolean is_friend Are they friends? (communications & sharing allowed)
  • boolean is_installed Has the user installed the game? (played it)
  • number time
  • string errorType in case of error(false on success)
  • string errorMessage in case of error(false on success)

10 STAT module

As we stated previously, this API is read-only, so, in this case, only get requests are allowed to prevent cheating. We will provide you the stat_uid when we create them but they will also be listed in your development sandbox, among a bunch of interesting tools :)

Update: we're starting to give write permissions to new HTML5 games. Please request access & instructions if you need them.

10.1 get( Function callback, string stat_uid )

Gets the provided stat uid value for the logged user. A response object is sent as the first parameter to the callback with the properties:

  • Object stat stat configuration {"id": "xxx", "uid": "yyy", "type": "zzz", ... }
  • number value stat value (32bit)
  • number timestamp timestamp when it was saved (64bit)
  • string errorType in case of error (false on success)
  • string errorMessage in case of error (false on success)

Demo code:

lechuck.stat.get(function(response){ if (response.errorType || !response.stat) { alert("Something went wrong: "+response.errorMessage); } else { console.log("Last score:" + response.value + " points"); } }, "last_score");

11. HIGHSCORE module

This module gives you the ability to retrieve the scoreboards and positions to show them in your game. Please remember that if you multiply the stats to handle floating point numbers in your game the highscore will also be stored multiplied, you have to divide them by in order to get the same precision for displaying it. In our sites we do that automatically, so you don’t have to worry about it, just tell us how many decimal numbers the stat & the highscore have.

We will provide you the hs_uid when we create them but they will also be available in your development sandbox along a few tools that you might find useful.

11.1 global( Function callback, string hs_uid, Object options )

Gets a global scoreboard, they will be ordered as configured, starting from the best, the items can be easily paginated by using the score and the timestamp of the last item of the batch.

The following options are supported:

  • string timespan [TOTAL, DAY, WEEK, MONTH] (TOTAL by default)
  • boolean withDetail include each user basic detail (true by default)
  • boolean withProgress include each user progress level
  • boolean withSharedContent to check if it has shared content and get the id
  • number limit number of items to retrieve (20 by default)
  • number startScore starting score, inclusive (exclusive if no timestamp sent)
  • number startTimestamp starting timestamp (in milliseconds), exclusive.

A response object is sent as the first parameter to the callback with the properties:

  • Object highscore hs config {"id": "xxxx", "uid": "yyyy", "type_sort": ... }
  • Array scores an array of user scores, will include the user detail if requested: {"score": "xxxx", "timestamp": "yyyy", "user": {...} }
  • string errorType in case of error (false on success)
  • string errorMessage in case of error (false on success)

Some demo code:

lechuck.highscore.global(function(response){ if (response.errorType || !response.scores) { alert("Something went wrong: "+response.errorMessage); } else { console.log("Top 5 scores today:"); for (var i=0;i<response.scores.length;i++) { console.log( "User "+response.scores[i].user.uid + " (level "+response.scores[i].user.progress_level+"): " + response.scores[i].score + " points" ); } } }, "best_points", {"timespan":"DAY", "withProgress": true, "limit":5});

11.1 friends( Function callback, string hs_uid, Object options )

Gets the user social scoreboard, the friends scoreboard corresponds to a board where only shows the user and the users he/she is following /not just the friends). As soon as the user follows another, its score will be sent to the user friends scoreboard, the same happens when the user stops following an user, it will be removed from it. Scores will be sorted as configured, starting from the best, items can be easily paginated by using the score and the user id of the last item of the batch. The user must be logged in or this will return an error response.

The following options are supported:

  • boolean withProgress include each user progress level
  • boolean withDetail include each user basic detail (true by default)
  • boolean withSharedContent to check if it has shared content and get the i
  • number limit number of items to retrieve (20 by default, 99 max)
  • number startScore starting score, inclusive (exclusive if no starting user sent)
  • number startUser starting user (in milliseconds), exclusive.

A response object is sent as the first parameter to the callback with the properties:

  • Object highscore hs config {"id": "xxxx", "uid": "yyyy", "type_sort": ... }
  • Array scores an array of user scores, will include the user detail if requested: {"score": "xxxx", "timestamp": "yyyy", "user": {...} }
  • string errorType in case of error (false on success)
  • string errorMessage in case of error (false on success)

11.3 score( Function callback, string hs_uid, Object options )

Retrieves an user score from a scoreboard (this value may be different from the one reported by getting the stat value, because the scoreboard can have different sorting or computation methods than the stat).

The following options are supported:

  • string timespan [TOTAL, DAY, WEEK, MONTH] (TOTAL by default)
  • boolean withSharedContent to check if it has shared content and get the id

A response object is sent as the first parameter to the callback with the properties:

  • object highscore hs config {"id": "xxxx", "uid": "yyyy", "type_sort": ... }
  • number value highscore score
  • number timespan timestamp when it was saved
  • string sharedContentId shared content id if any (and if it was requested)
  • string errorType in case of error (false on success)
  • string errorMessage in case of error (false on success)

11.4 position( Function callback, string hs_uid )

Retrieves an user position from a scoreboard, only the 1000 top positions are stored, any null value means out of the top 1000.

A response object is sent as the first parameter to the callback with the properties:

  • object highscore hs config {"id": "xxxx", "uid": "yyyy", "type_sort": ... }
  • number value highscore score
  • number timespan highscore position, null if out of top 1000
  • string errorType in case of error (false on success)
  • string errorMessage in case of error (false on success)

12. DATASTORE module

Allows you to store user related content and retrieve it when needed, to keep things simple: the datastore are the "savegames". There are 3 slots per user, 50kb each, numbered as 0, 1 & 2.

12.1 status( Function callback)

Retrieves the status of the user slots. A response object is sent as the first parameter to the callback with the properties:

  • number first_free_slot index number of the first free slot
  • array slots 3 item array with the status of each slot, each item can be null (empty slot) or an object with the following properties:
    • string label Slot label (specified when saving)
    • number size Slot size in bytes
    • number timestmap Slot timestamp (in milliseconds)
  • string errorType in case of error (false on success)
  • string errorMessage in case of error (false on success)

Demo code:

lechuck.datastore.status( function(response){ console.dir(response); } );

12.2 save( Function callback , number slot_number , mixed data , string label )

Saves data into an user slot (0, 1 or 2), it overwrites any existing data. The data can be any type, it will be converted automatically to JSON with JSON.sringify() prior saving, please make sure it can be properly stringified. Label is optional, it will default to the current date/time. A response object is sent as the first parameter to the callback with the properties:

  • boolean success Did it succeed?
  • number writtenBytes Written bytes
  • string errorType in case of error (false on success)
  • string errorMessage in case of error (false on success)

Demo code, store a simple object:

lechuck.datastore.save( function(response){ console.log(response.writtenBytes + " bytes written"); }, 0, { "property1": "value1", "property2": [0,5,10], "property3": true } );

12.3 load( Function callback, number slot_number )

Retrieves the datastore user slot data. A response object is sent as the first parameter to the callback with the properties:

  • mixed data data saved into the slot, will match the written data type
  • string errorType in case of error (false on success)
  • string errorMessage in case of error (false on success)

Demo code, load the simple object we stored previously:

lechuck.datastore.load( function(response){ console.dir(response.data); console.log("property1: " + response.data.property1); console.log("property2: " + response.data.property2); console.log("property3: " + response.data.property3); }, 0 );

12.2 reset( Function callback, number slot_number )

Clears an user slot. A response object is sent as the first parameter to the callback with the properties:

  • bool success Did it succeed?
  • string errorType in case of error (false on success)
  • string errorMessage in case of error (false on success)

Demo code:

lechuck.datastore.reset( function(response){ console.log( response.success ? "Success":"Not success" ); }, 0 );

13. ITEM module

The item module allows you access the inventory of items bought by the user for your game and to initiate the purchase workflow right from within your game.

13.1 detail( Function callback )

Retrieves an item configuration. A response object is sent as the first parameter to the callback with the properties:

  • Object item Item configuration, these are the properties of the object:
    • item.id Item id
    • item.uid Item uid (alphanumeric)
    • item.name Item name
    • item.is_enabled boolean flag, is the item enabled?
    • item.is_usabe boolean flag, is the item usable/consumable?
    • item.is_buyable boolean flag, can the item be purchased?
    • item.price_minicoins Item price in minicoins
    • item.max_stock Max stock of the item (for boolean items it will be 1)
  • string errorType in case of error (false on success)
  • string errorMessage in case of error (false on success)

13.2 list( Function callback )

Retrieves the list of configured items for the game. A response object is sent as the first parameter to the callback with the properties:

  • Array items item objects (refer to 13.1)
  • string errorType in case of error (false on success)
  • string errorMessage in case of error (false on success)

13.3 inventory( Function callback, Object options)

Retrieves the items owned by an user (the user inventory). The following options are supported:

  • boolean withDetail include each user basic detail (true by default)

A response object is sent as the first parameter to the callback with the properties:

  • Array items inventory items objects, each one with these properties:
    • items[x].id Item id
    • items[x].stock Item stock for the user
    • items[x].timestamp Last operation timestamp
    • items[x].item Item configuration object (refer to 13.1)
  • string errorType in case of error (false on success)
  • string errorMessage in case of error (false on success)

Some demo code:

lechuck.item.inventory(function(response){ if (response.errorType || !response.items) { alert("Something went wrong: "+response.errorMessage); } else { console.log("User item inventory:"); for (var i=0;i<response.items.length;i++) { console.log( "Item "+response.items[i].item.uid + ":"+ response.items[i].stock + " units" ); } } }, {"withDetail": true});

13.4 stock( Function callback, string item_uid, Object options)

Retrieves the item stock owned by an user. The following options are supported:

  • boolean withDetail include item configuration (true by default)

A response object is sent as the first parameter to the callback with the properties:

  • number stock Item stock owned by the user
  • number timestamp timestamp of the last operation
  • Object Item configuration object if requested (refer to 13.1)
  • string errorType in case of error (false on success)
  • string errorMessage in case of error (false on success)

Some demo code:

lechuck.item.stock(function(response){ if (response.errorType || !response.item) { alert("Something went wrong: "+response.errorMessage); } else { console.log( "Item "+response.item.uid + " stock for the user: "+ response.stock + " units" ); } }, "ammo", {"withDetail": true});

13.5 buy( Function callback, Object items)

Initiates the purchase items with Minicoins workflow (fully handled by us) an object with the items uids and amount that the user is going to purchase must be provided. The items uids are available on your development sandbox, as well as some interesting stuff (like an item reset tool or a log). On your development game all items are free, on the production game they’re paid, please contact us in order to define and configure the items along with their price, there’s no limit of items that can be configured.

This is a sample items purchase object, 100 units of amo and 1 shield unit:

{"ammo": 100, "shield": 1 }

Once the item/s have been purchased (or cancelled) a response object is sent as the first parameter to the callback with the following properties:

  • boolean success Were some items purchased?
  • Array items Items purchased, each one with these properties:
    • items[x].uid Item uid.
    • items[x].qty Amount purchased
    • items[x].stock New item total stock owned by the user.
  • string errorType in case of error (false on success)
  • string errorMessage in case of error (false on success)

Some demo code:

lechuck.item.buy(function(response){ if (response.errorType == "CANCELLED") alert("User cancelled"); else if (response.errorType || !response.success) { alert("Something went wrong: "+response.errorMessage); } else { console.log("Items purchased:"); for (var i=0;i<response.items.length;i++) { console.log( "Item "+response.items[i].uid + ":"+ response.items[i].qty + " units bought / new stock: " + response.items[i].stock ); } } }, {"ammo": 100, "shield": 1});

SPECIAL CASE: DYNAMIC ITEMS

For selected developers and complex games we support an additional type of items called "dynamic", which allows you to set a custom title and price for an item when you initiate the purchase workflow via any of our client apis. To prevent any modification of the payload, these items purchases must be validated server-side, we will always ask you if the user can purchase the dynamic item with the data that you provided us.

To initiate the workflow, you just need to provide a "dynamic" item, but instead of specifying the amount to purchase, you need to provide a string with the following data:

PRICE_IN_MINICOINS|ITEM_NAME|OPT_YOUR_CUSTOM_ICON_URL|OPT_YOUR_CUSTOM_DATA

Please be noticed of this:

  • Only one dynamic item can be sold at the same time, only 1 unit of the item can be sold.
  • The price in minicoins is not your net share, it's the amount that the user has to pay for it, the amount you specify is the amount that will be charged to the user. It must be an integer.
  • You have to provide the name in the user locale language, your game receive the user locale as parameter.
  • The icon is optional and provisioned for the future, it's not yet supported, we recommend you to leave it empty or provide a 128x128px transparent png url.
  • After the third | you can specify whatever you need, like an internal item id, you can even include more | symbols.
  • The payload max length is 700 characters, including icon

Some demo code:

lechuck.item.buy(function(response){ if (response.errorType == "CANCELLED") alert("User cancelled"); else if (response.errorType || !response.success) { alert("Something went wrong: "+response.errorMessage); } else { console.log("Items purchased:"); for (var i=0;i<response.items.length;i++) { console.log( "+ Item "+response.items[i].uid + ":"+ response.items[i].qty + " units bought / new stock: " + response.items[i].stock ); if (response.items[i].is_dynamic) { console.log("Dynamic item payload: '" + response.items[i].dynamic_payload + "'"); /* Your callback will receive the dynamic payload you provided as well */ } } } }, {"dynamic": "100|Demo dynamic item, a great offer only for you|OPT_MY_CUSTOM_ICON_URL|OPT_MY_CUSTOM_DATA"} /* Custom dynamic item for 100 minicoins */);

14. Ads module

The item module allows you to show video ads in your game. We will provide you an adTagURL to monetize your game with video ads if it's eligible.

14.1 showInterlevelAd( String adTagURL, Function onPlayCallback, Function onEndedOKCallback(bool campaignCompleted), Function onEndedKOCallback )

Shows an interlevel video AD. A close button will appear after 10 seconds. Please make sure to:

- Provide a proper adTagURL (if empty a demo adTagURL will be used) Contact us to request one.
- Do not use the demo adTagURL in production
- Provide valid callbacks. onPlayCallback: An ad is being played. onEndedOKCallback: An ad has been played. onEndedKOCallback: An ad could not be played.
- Pause your game and stop all audio on the onPlayCallback event.
- Focus your game and resume it on the onEndedOKCallback & onEndedKOCallback events.

Some demo ad (no monetization, do not use it on production):

lechuck.ads.showInterlevelAd("", function() { console.log("ad start"); }, function(campaignCompleted) { if (campaignCompleted) { console.log("ad end ok. a campaign has been shown"); } else { console.log("ad end ok"); } }, function() { console.log("ad end ko"); });

Custom adTagUrl (contact us to request one to monetize your game):

lechuck.ads.showInterlevelAd("https://s3.amazonaws.com/demo.jwplayer.com/player-demos/assets/preroll.xml?rnd={random}", function() { console.log("ad start"); }, function() { console.log("ad end ok"); }, function() { console.log("ad end ko"); });

Do you have questions or want to report some bugs? please contact us at [email protected]