‹ Google Play Games Services Doc Home

Google Play Games Services Integration Guide

For the Lua version of cocos2d-x v3.x - (all other versions)

SDK Version

Integration

Open a terminal and use the following command to install the SDKBOX Google Play Games Services plugin. Make sure you setup the SDKBOX installer correctly.

$ sdkbox import gpg

Warning: Account creation within iOS is no longer supported, please read this blog post for details

After Installation

Android

Update AndroidManifest.xml

Add this meta-data tag to your AndroidManifest.xml

<meta-data android:name="com.google.android.gms.games.APP_ID"
    android:value="@string/google_app_id" />

Update string.xml

Add this entry to proj.android/res/values/string.xml

<string name="google_app_id">777734739048</string>

Replace google_app_id value with your own App Id.

iOS

Set a rootview controller for GPG:

Update proj.ios_mac/ios/RootViewController.h Add this:

#import <GoogleSignIn/GoogleSignIn.h>

// Change RootViewController class definition to:
@interface RootViewController : UIViewController<GIDSignInUIDelegate>

Set Google Play signin listeners

Update proj.ios_mac/ios/AppController.mm

  1. Add this method:
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options {
    return [[GIDSignIn sharedInstance] handleURL:url
                               sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]
                                      annotation:options[UIApplicationOpenURLOptionsAnnotationKey]];
}
  1. In this method:
(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

add a call to (before return YES):

    // _viewController could also be named
    //  viewController, depending of the project type.
    [GIDSignIn sharedInstance].uiDelegate = _viewController;

Add URL types

Add the following URL types under your project > Info > URL Types

Further info

For more information check out the official documentation

Important Notice

Please make sure the following settings in your project to make the plugin work well.

Disable App Transport Security

Adding the following entry to the info.plist file:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

It should look like this:

Disable Bitcode support

You have to turn off Bitcode support. If you don't, cocos2d-x will fail to build.

Set your game requires full screen

If your game doesn't support all screen orientations, you will need to check Requires full screen in Xcode. If you do not, your app will fail Apple's submission process.

Whitelist canOpenURL function

This setting depends on what plugins are in your project. You may need to add the required entry to the info.plist, under LSApplicationQueriesSchemes.

Usage

Pre-requisites

Your must create your app on Google Play Developer console and all the services must be explicitly enabled and configured in the console.

Note: Google Play Games Services will use your release keystore by default, if you want to test your game in debug settings, please link an additional app with debug keystore

Initialization

Currently the configuration process is done in Lua and passed into Google Play Services when creating the game services object. This object is managed for you, and is available from the gpg Lua namespace.

To create the game services instance, you need to pass in a table that contains the ClientID that represents the game you have created in the Google Play Console.

    local config = {ClientID="..."}
    gpg:CreateGameServices(config)

Note that the ClientID used is the forwards version from the Google Play Console. There is also a reversed version that is used in the plist. Make sure that you have the correct version, else the initialization will fail.

The full list of configuration data that can be passed is as follows.

{
    LogLevel        = 1 or 2,
    EnableSnapshots = true or false,
    ClientID        = forwards client id
}

Callbacks

Most of the Google Play Services methods take a callback argument to return the results. This is mainly because the methods are performed asynchronously, and the results may only be available in the future.

Two types of callbacks are supported. Class method callbacks, and function callbacks (which includes lambda functions)

Class method example

ExampleClass:CallbackMethod(result)
    -- use result here
end

local someClass = ExampleClass:new()

gpg:MethodWithCallback({someClass, ExampleClass.CallbackMethod})

Notice that in the class method example, you must pass in the instance of the class as well as the method.

Lambda function example

gpg:MethodWithCallback(function(result)
    -- use result here
end)

Authorization

Before you can do anything with Google Play Services, you must authenticate. If you have previously authenticated, then sdkbox will attempt to log you in automatically. You will still get the same events that you normally would if you are logged in automatically.

To begin the authentication process, you call the following, and pass in either a class method or a lambda method (see Callbacks) to receive the response.

gpg:StartAuthorizationUI(function(result)
    if result.authStatus == gpg.AuthStatus.VALID then
        -- successfully authenticated
    end
end)

Quests API

Before you begin

Make sure to checkout the Google Play Services Quests documentation in order to better understand how to setup quests using their portal, and for a reference on the API.

Before your game can access events and quests, you must define them first in the Google Play Developer Console

Submitting an event

You send events to the Events service in order to let it know that something has happened. There is no result to this method, so no callback is needed.

gpg.Events:Increment("<event id>")

Retrieving events

To retrieve the current count of events, use one of the Fetch methods.

gpg.Events:Fetch("<event id>", function(result)
    -- use result.count here
end)

-- or

gpg.Events:FetchAll(function(results)
    for k,v in pairs(results.data) do
        -- k is the event id
        -- use v.count here
    end
end)

The complete list of members to callback results can be found in the callback result descriptions section at the end of this documentation.

Displaying quests

Google Play Services provides a UI to select quests, or you can provide your own using the quest data from callbacks.

To use the one provided, you can either display all available quests, or just a single quest UI.

gpg.Quests:ShowUI("<quest id>", function(result)
    -- use result.quest here
end)

-- or

gpg.Quests:ShowAllUI(function(result)
    -- use result.quest here
end)

Handling quest acceptance

If your game uses the built-in quest UI, then the callback result will have a valid Quest object, which you can test using quest.valid() otherwise if you are using your own UI, then you can call accept as follows.

gpg.Quests:Accept("<quest id>", function(result)
    -- use result.quest here
end)

Handling quest completion

After players accept a quest, you send events to the quest service to inform it of progress on the quest.

One all the criteria for the quest have been satisfied, you can claim the reward in the built-in UI or your own.

You claim a quest milestone by calling the claim method.

gpg.Quests:ClaimMilestone("<milestone id>", function(result)
    if result.status == gpg.ClaimMilestoneResponse.VALID
        -- use result.milestone.completionRewardData here
    end
end)

Player statistics

For a complete description of what player statistics are, and how to use them, please refer to the Google Play Services section on the topic here

Getting stats for the currently signed in player

You can fetch stats for the current player like this.

gpg.Stats:FetchForPlayer(function(result)
    if result.status == gpg.FetchForPlayerResponse.VALID then
        -- use PlayerStats here
    end
end)

Achievements

For the complete documentation, check out achievements

State

Achievements can be hidden, revealed, and unlocked.

Achievements can be designated as standard or incremental. Generally, an incremental achievement involves a player making gradual progress towards earning the achievement over a longer period of time

Showing the UI

    gpg.Achievements:ShowAllUI(function(result)
        -- handle the result here
    end)

Fetch Achievements

    gpg.Achievements:FetchAll(nil, function(result)
        log:d(log:to_str(result))
    end)

Fetch Achievement

    gpg.Achievements:Fetch('CgkI6KjppNEWEAIQBQ', nil, function(result)
        log:d(log:to_str(result))
    end)

Increment Achievement

   gpg.Achievements:Increment('CgkI6KjppNEWEAIQBQ')

Unlock Achievement

   gpg.Achievements:Unlock('CgkI6KjppNEWEAIQBQ')

Reveal Achievement

    gpg.Achievements:Reveal('CgkI6KjppNEWEAIQBQ')

Leaderboards

Checkout additional docs for leaderboards here

Show UI

    gpg.Leaderboards:ShowUI("achievement id")

ShowAllUI

    gpg.Leaderboards:ShowAllUI()

Submit Score

    gpg.Leaderboards:SubmitScore("achievement id", score, "meta data", function(result)
    end)

FetchAllScoreSummaries

    gpg.Leaderboards:FetchAllScoreSummaries("achievement id", data source, function(result)
    end)

FetchAll

    gpg.Leaderboards:FetchAll(datasource, function(result)
    end)

FetchScorePage

    gpg.Leaderboards:FetchScorePage("achievement id", datasource, time, timespan, collection, maxitmes, function(result)
    end)

FetchNextScorePage

    gpg.Leaderboards:FetchNextScorePage(datasource, max items, function(result)
    end)

Realtime Multiplayer

Before you begin, familiarize yourself with the Google Play Games real time multiplayer game concepts here.

In order to use real time multiplayer, you must enable it in the Google Play Developer Console.

To begin a real time multiplayer game, there are three ways to connect with other players to start a real time multiplayer games.

Quick game

Lets the player play against randomly selected opponents (via auto-matching).

    gpg.Realtime:CreateRealTimeRoom(
        {
            type = "quick_match", -- select automatching
            quick_match_params = 
            {
                maximumAutomatchingPlayers = 1,
                minimumAutomatchingPlayers = 1
            }
        },
        listener, 
        function(result)
            if (gpg:IsSuccess(result.result)) then
                -- use result.room here
            end    
        end
    )

Invite players

This lets you choose specific players to invite.

    gpg.Realtime:CreateRealTimeRoom(
        {
            type = "ui", -- select invite players UI
            ui_params = 
            {
                maximumPlayers = 1,
                minimumPlayers = 1
            }
        },
        listener, 
        function(result)
            if (gpg:IsSuccess(result.result)) then
                -- use result.room here
            end           
        end
    )

Accept an invitation

In the case of choosing specific players, you will receive and invitation that you can either accept or decline.

    -- you can fetch all pending invitations like this
    -- this will call you back with a result and array of invitations
    gpg.Realtime:FetchInvitations(function(result)
        if (gpg:IsSuccess(result.result)) then
            -- do something with result.invitations
        end
    end)

    -- or you can use the UI to accept or decline an invitation
    gpg.Realtime:ShowRoomInboxUI(function(result)
        if (gpg:IsSuccess(result.result)) then
            -- do something with result.invitation
        end
    end)

The listener

The room creation methods, including accepting an invitation, take a listener object. This is so that when things happen in the room, the listener can be informed.

This is also where you will receive data messages from other players, via the onDataReceived callback method.

listener = 
{
    -- called when something about the room changes
    onRoomStatusChanged = function(room)
    end,

    -- called when something about the connection changes
    onConnectedSetChanged = function(room)
    end,

    -- called when you get connected
    onP2PConnected = function(room, participant) 
    end,

    -- called when you get disconnected
    onP2PDisconnected = function(room, participant) 
    end,

    -- called if the status of one of the room participants changes
    onParticipantStatusChanged = function(room, participant) 
    end,

    -- called whenever someone sends you a message
    onDataReceived = function(room, from_participant, data, is_reliable) 
    end
}

Sending messages to other players

There are two types of messages you can send, reliable and unreliable. Reliable messages are guaranteed, and will automatically resend if they get lost. There is some overhead to this, so if you don't need reliability, then you can send an unreliable message which is a little more efficient at the cost of reliability.

gpg.Realtime:SendReliableMessage(room_id, participant_id, message, function(result)
    if (gpg:IsSuccess(result.result)) then
        -- message send was successful
    end
end)

Sending an unreliable message takes a json encoded string for the parameters. There is no callback, since being unreliable, there is no return status.

gpg.Realtime:SendUnreliableMessage(json.encode({
    data = message,
    room_id = room_id
    participant_ids = {}
}))

Leaving a room

gpg.Realtime:LeaveRoom(room_id, function(result)
end)

Accepting / declining and dismissing invitations

For accepting invitations, you must provide a listener that will handle all the events for the room you are joining.

gpg.Realtime:AcceptInvitation(invitation_id, listener, function(result)
end)

Decline and Dismiss do not take callbacks, they just inform the server that you are no longer interested in the invitation. Dismissing an invitation is for when the game is over, but the invitation is still in your inbox.

gpg.Realtime:DeclineInvitation(invitation_id)
gpg.Realtime:DismissInvitation(invitation_id)

Turn Based Multiplayer

Before you begin make sure to checkout Google's documentation here and also checkout the turn based multiplayer game concepts here

To start a turn based multiplayer game, there are two ways to do so. You can either use a UI to select players (either Google's or your own), or you can start a quick match which will choose players for you.

Quick Match

local minimumPlayers = 1
local maximumPlayers = 2
local allowAutoMatching = false
gpg.Turnbased:ShowPlayerSelectUI(minimumPlayers, maximumPlayers, allowAutoMatching, function(result)
    params = {
        type = "quick_match",
        minimumAutomatchingPlayers = result.minimumAutomatchingPlayers,
        maximumAutomatchingPlayers = result.maximumAutomatchingPlayers,
        playerIds = result.playerIds
    }
    gpg.Turnbased:CreateTurnBasedMatch(params, function(result)
        if gpg:IsSuccess(result.result) then
            -- use result.match to start playing
        end
    end)
end)

Choose Players UI

params = {
    type = "ui",
    minimumAutomatchingPlayers = 1,
    maximumAutomatchingPlayers = 2
}
gpg.Turnbased:CreateTurnBasedMatch(params, function(result)
    if gpg:IsSuccess(result.result) then
        -- use result.match to start playing
    end
end)

Handling match events

There are two events that need to be handled for turn based multiplayer. You can register for two callbacks (see Callbacks) in order to handle these events.

gpg.Turnbased:addMatchEventCallback(
    gpg.DefaultCallbacks.TURN_BASED_MATCH_EVENT, 
    function(event) 
        gpg.Turnbased:ShowMatchInboxUI(function(result)
            if gpg:IsSuccess(result.result) then
                -- start using result.match here
            end
        end)    
    end
)

-- or

gpg.Turnbased:addMatchEventCallback(
    gpg.DefaultCallbacks.MULTIPLAYER_INVITATION_EVENT, 
    {instance, method}
)

function class:method()
    gpg.Turnbased:ShowMatchInboxUI(function(result)
        if gpg:IsSuccess(result.result) then
            local match = result.match
            if match.matchStatus == gpg.MatchStatus.MY_TURN then
                -- do something with match, take a turn
            elseif match.matchStatus == gpg.MatchStatus.THEIR_TURN then
                -- update for their turn
            elseif match.matchStatus == gpg.MatchStatus.COMPLETED then
                -- complete match, dismiss
            else match.matchStatus == gpg.MatchStatus.EXPIRED then
                -- dismiss 
            end
        end
    end)
end

Taking a turn

To take a turn, you must update the match data with your turn data, and pass it to the next participant. You can use the id "AUTOMATCHING_PARTICIPANT" if you would like the next participant to be automatched.

local results = match.participantResults
if winnig then
    results = gpg.Turnbased:createParticipantResult(match_id, match.pendingParticipant.id, my_rank, win_token)
elseif losing then
    results = gpg.Turnbased:createParticipantResult(match.id, match.pendingParticipant.id, my_rank, lose_token)
end

local nextParticipant = "AUTOMATCHING_PARTICIPANT"
if match.suggestedNextParticipant.valid and 
   match.suggestedNextParticipant.id ~= "" then
    nextParticipant = match.suggestedNextParticipant.id
end
gpg.Turnbased:TakeMyTurn(match_id, match.pendingParticipant.id, nextParticipant, data, function(result)
end)    

Creating participant results

Sometimes you need to pass participant results to a method. In c++ this is done directly using a struct, but in Lua you need to use an id. This id is used to lookup the struct and pass it for you. You can reuse existing participant ids or just create your own. The method will also return the struct as a Lua object.

local results = gpg.Turnbased:CreateParticipantResult(match_id, participant_id, placement, match_result)
-- use results, or call method and pass participant_id

Completing a match

gpg.Turnbased:FinishMatchDuringMyTurn(match_id, participant_results_id, data, function(result)
    if gpg:IsSuccess(result.result) then
        -- success
    end
end)

Leaving a match

You can leave a match at any time, but you need to call the right method, either of the following.

gpg.Turnbased:LeaveMatchDuringMyTurn(match_id, next_participant_id, function(result)
    if gpg:IsSuccess(result.result) then
        -- success
    end 
end)

-- or

gpg.Turnbased:LeaveMatchDuringTheirTurn(match_id, function(result)
    if gpg:IsSuccess(result.result) then
        -- success
    end
end)

Cancelling a match

gpg.Turnbased:CancelMatch(match_id, function(result)
    if gpg:IsSuccess(result.result) then
        -- success
    end
end)

Dismissing a match

gpg.Turnbased:CancelMatch(match_id)

Starting rematch

gpg.Turnbased:Rematch(match_id, function(result)
    if gpg:IsSuccess(result.result) then
        -- success
    end
end)

Fetching a previous match

gpg.Turnbased:FetchMatch(match_id, function(result)
    if gpg:IsSuccess(result.result) then
        -- success
    end
end)

Fetch all matches

gpg.Turnbased:FetchMatches(function(result)
    if gpg:IsSuccess(result.result) then
        -- use result.matches here
    end
end)

NearbyConnections

For the complete documentation, check out Nearby Connections

Init

init nearby connection, if not support current platform, will return false

local support = gpg.NearbyConnections:Init("{\"LogLevel\":1}",
    function(result)
        if result.InitializationStatus then
            print('GPG Nearby init success')
        else
            print('GPG Nearby init failed')
        end
    end)
if not support then
    print('GPG Nearby is not support ios')
end

Get local endpoint id

get local endpoint id when connect success

local endpoint = gpg.NearbyConnections:GetLocalEndpointId();
print('Local Endpoint Id:' .. endpoint)

Get local device id

local deviceid = gpg.NearbyConnections:GetLocalDeviceId();
print('Local device id:' .. deviceid)

Advertising

start advertising

gpg.NearbyConnections:StartAdvertising(
    "\"name\":\"\",\"duration\":0,\"app_identifiers\":{\"identifier\":\"com.sdkbox.gpg\"},",
    function(result)
        -- start advertising result

        if (1 == result.start_advertising_result.status) then
            print("GPG start advertising result:" .. result.client_id
                .. " status:" .. result.start_advertising_result.status
                .. " local_endpoint_name:" .. result.start_advertising_result.local_endpoint_name)
        else
            print('start advertising failed:' .. result.start_advertising_result.status)
        end
    end,
    function(result)
        --request connect callback

        local remote_endpoint_id = result.request.remote_endpoint_id
        local payload = result.request.payload

        log:d('GPG receive connect request:' .. remote_endpoint_id)

        -- auto accept or query user
        -- 1. accept connect request
        -- invoke AcceptConnectionRequest
        -- gpg.NearbyConnections:AcceptConnectionRequest(remote_endpoint_id, payload, function (result) end)

        -- 2. reject connect request
        -- invoke RejectConnectionRequest
    end)

Stop advertising

gpg.NearbyConnections:StopAdvertising()

Accept connect request

gpg.NearbyConnections:AcceptConnectionRequest(
    remote_endpoint_id,
    payload,
    function (result)
        print('event:' .. result.event)
        if 'OnMessageReceived' == result.event then
            print('OnMessageReceived client_id:' .. tostring(result.client_id)
                .. ' remote_endpoint_id:' .. tostring(result.remote_endpoint_id)
                .. ' payload:' .. tostring(result.payload)
                .. ' is_reliable:' .. tostring(result.is_reliable))
        elseif 'OnDisconnected' == result.event then
            print('OnDisconnected client_id:' .. tostring(result.client_id)
                .. ' remote_endpoint_id:' .. tostring(result.remote_endpoint_id))
        else
            print('Unknown event:' .. result.event);
        end
    end)

Reject connect request

gpg.NearbyConnections:RejectConnectionRequest(remote_endpoint_id)

Start Discovery

duration in milliseconds

gpg.NearbyConnections:StartDiscovery(server_id, duration,
    function (result)
        if 'OnEndpointFound' == result.event then
            print('found client_id:' .. tostring(result.client_id)
                .. ' endpoint_id:' .. tostring(result.endpoint_details.endpoint_id)
                .. ' device_id:' .. tostring(result.endpoint_details.device_id)
                .. ' name:' .. tostring(result.endpoint_details.name)
                .. ' service_id:' .. tostring(result.endpoint_details.server_id))
        elseif 'OnEndpointLost' == result.event then
            print('endpoint lost')
        else
            print('unknown event')
        end
    end)

Stop Discovery

gpg.NearbyConnections:StopDiscovery()

Send Connect Request

gpg.NearbyConnections:SendConnectionRequest(
    name, remote_endpoint_id, payload,
    function(result)
        -- connect response callback
        if (1 == result.response.status) then
            print('Connect advertising success');
            local remote_endpoint_id = result.response.remote_endpoint_id;
        else
            print('Connect advertising failed');
        end
    end,
    function(result)
        if 'OnMessageReceived' == result.event then
            print('OnMessageReceived client_id:' .. tostring(result.client_id)
                .. ' remote_endpoint_id:' .. tostring(result.remote_endpoint_id)
                .. ' payload:' .. tostring(result.payload)
                .. ' is_reliable:' .. tostring(result.is_reliable))
        elseif 'OnDisconnected' == result.event then
            print('OnDisconnected client_id:' .. tostring(result.client_id)
                .. ' remote_endpoint_id:' .. tostring(result.remote_endpoint_id))
        else
            print('Unknown event:' .. result.event);
        end
    end)

Send Reliable Message

gpg.NearbyConnections:SendReliableMessage(remote_endpoint_id1, message)
gpg.NearbyConnections:SendReliableMessage([remote_endpoint_id1, remote_endpoint_id2], message);

Send Unreliable Message

gpg.NearbyConnections:SendUnreliableMessage(remote_endpoint_id1, message)
gpg.NearbyConnections:SendUnreliableMessage([remote_endpoint_id1, remote_endpoint_id2], message);

Disconnect

gpg.NearbyConnections:Disconnect(remote_endpoint_id)

Stop

gpg.NearbyConnections:Stop()

API Reference

Callback result descriptions

Result Codes

{
    VALID                           = 1,
    VALID_BUT_STALE                 = 2,
    VALID_WITH_CONFLICT             = 3,
    FLUSHED                         = 4,
    ERROR_LICENSE_CHECK_FAILED      = -1,
    ERROR_INTERNAL                  = -2,
    ERROR_NOT_AUTHORIZED            = -3,
    ERROR_VERSION_UPDATE_REQUIRED   = -4,
    ERROR_TIMEOUT                   = -5,
    ERROR_CANCELED                  = -6,
    ERROR_MATCH_ALREADY_REMATCHED   = -7,
    ERROR_INACTIVE_MATCH            = -8,
    ERROR_INVALID_RESULTS           = -9,
    ERROR_INVALID_MATCH             = -10,
    ERROR_MATCH_OUT_OF_DATE         = -11,
    ERROR_UI_BUSY                   = -12,
    ERROR_QUEST_NO_LONGER_AVAILABLE = -13,
    ERROR_QUEST_NOT_STARTED         = -14,
    ERROR_MILESTONE_ALREADY_CLAIMED = -15,
    ERROR_MILESTONE_CLAIM_FAILED    = -16,
    ERROR_REAL_TIME_ROOM_NOT_JOINED = -17,
    ERROR_LEFT_ROOM                 = -18
}

Events

Event description

{
    "valid"       : 1 or 0
    "id"          : event id,
    "name"        : event name,
    "description" : event description text,
    "visibility"  : whether or not event can be seen,
    "count"       : current count of events of this type,
    "imageUrl"    : URL to the event image
}

Events:FetchAll

{
    "status" : 1 or 0 indication success or failure,
    "data"   : {
        event_id : Event,
        ...
    }
}

Events:Fetch

{
    "result" : 1 or 0,
    "event"  : Event
}

Quests

Quest description

{
    "valid"            : 1 or 0,
    "id"               : quest id,
    "name"             : name of quest,
    "description"      : text description of quest,
    "iconUrl"          : URL to quest icon,
    "bannerUrl"        : URL to quest banner image,
    "currentMilestone" : QuestMileStone,
    "questState"       : quest state, accepted or not,
    "startTime"        : time the quest starts,
    "expirationTime"   : time the quest expires,
    "acceptedTime"     : time that the quest was accepted
}

QuestMilestone description

{
    "valid"                : 1 or 0,
    "id"                   : milestone id,
    "questId"              : quest id for this milestone,
    "eventId"              : event id,
    "state"                : milestone state,
    "currentCount"         : current count,
    "targetCount"          : count to complete milestone,
    "completionRewardData" : string containing reward data from console
}

Quests:Fetch

{
    "result" : 1 or 0,
    "quest"  : Quest
}

Quests:FetchList

{
    "status" : 1 or 0,
    "data    : 1 based array of Quest
}

Quests:Accept

{
    "status" : 1 or 0,
    "quest"  : Quest
}

Quests:ClaimMilestone

{
    "status"    : 1 or 0,
    "milestone" : QuestMilestone
    "quest"     : Quest
}

Quests:ShowUI

{
    "status" : 1 or 0,
    "result" : 1 or 0,
    "quest"  : Quest
}

Quests:ShowAllUI

{
    "status" : 1 or 0,
    "result" : 1 or 0,
    "quest"  : Quest
}

PlayerStats

PlayerStats description

{
    "valid"                   : 1 or 0,
    "hasAverageSessionLength" : 1 if valid,
    "averageSessionLength"    : length of session in ?,
    "hasChurnProbability"     : 1 if valid,
    "churnProbability"        : 0 - 1 likelihood of retention,
    "hasDaysSinceLastPlayed"  : 1 if valid,
    "daysSinceLastPlayed"     : count of days,
    "hasNumberOfPurchases"    : 1 if valid,
    "numberOfPurchases"       : total number of purchases,
    "hasNumberOfSessions"     : 1 if valid,
    "numberOfSessions"        : number of sessions played,
    "hasSessionPercentile"    : 1 if valid,
    "sessionPercentile"       : what percentile they are in,
    "hasSpendPercentile"      : 1 if valid,
    "spendPercentile"         : what spend percentile they are in
}

Achievements

Achievement description

{
    "currentSteps"     : Current steps completed of the achievement,
    "description"      : Description of the achievement.
    "id"               : String Id,
    "lastModifiedTime" : Time last modified,
    "name"             : Name of the achievement,
    "revealedIconUrl"  : URL for the revealed icon,
    "state"            : State, hidden, revealed, unlocked,
    "totalSteps"       : Total number of steps,
    "type"             : Incremental or standard,
    "unlockedIconUrl"  : URL for the unlocked icon,
    "valid"            : 1 or 0 if valid,
    "xp"               : Amount of XP awarded
}

Achievements:ShowAllUI

{
    "result" : result code
}

Achievements:FetchAll

    "result"            : result code,
    "achievement_array" : array of Achievements

Achievements:Fetch

    "result"         : result code,
    "achievement" : Achievement

Multiplayer

Player

{
    "valid",
    "id",
    "name",
    "avatarUrlHiRes",
    "avatarUrlIconRes",
    "hasLevelInfo",
    "currentLevel",
    "nextLevel",
    "currentXP",
    "lastLevelUpTime",
    "title",
}

PlayerLevel

{
    "valid",
    "levelNumber",
    "minimumXP",
    "maximumXP"
}

Participant

{
    "valid",
    "displayName",
    "avatarUrl",
    "id",
    "hasPlayer",
    "player",
    "participantStatus",
    "hasMatchResult",
    "matchResult",
    "matchRank",
    "icConnectedToRoom"
}

Room

{
    "valid",
    "id",
    "variant",
    "automatchWaitEstimate",
    "creatingParticipant",
    "creationTime",
    "description",
    "participants",
    "remainingAutomatchingSlots",
    "status"
}

MultiplayerInvitation

{
    "valid",
    "id",
    "variant",
    "automatchingSlotsAvailable",
    "creationTime",
    "invitingParticipant",
    "type",
    "participants"
}

ParticipantResults

{
    "valid",
    "hasResultsForParticipant",
    "placeForParticipant",
    "matchResultForParticipant"
}

TurnBasedMatch

{
    "valid",
    "id",
    "creationTime",
    "lastUpdateTime",
    "creatingParticipant",
    "lastUpdatingParticipant",
    "pendingParticipant",
    "matchStatus",
    "automatchingSlotsAvailable",
    "variant",
    "description",
    "number",
    "version"
}

NearbyConnections

NearbyConnections:Init

{
    "InitializationStatus" : initialization result
}

NearbyConnections:StartAdvertising

{
    "client_id" : client id,
    "start_advertising_result" :
    {
        "status"    : start advertising result,
        "local_endpoint_name"   : local endpoint name
    }
},
{
    "client_id" : client id,
    "request" :
    {
        "remote_endpoint_id" : remote endpoint id,
        "remote_device_id" : remote device id
        "remote_endpoint_name": remote endpoint name
        "payload" : payload message
    }
}

NearbyConnections:AcceptConnectionRequest

{
    "event" : "OnMessageReceived" or "OnDisconnected",
    "client_id" : client id,
    "remote_endpoint_id" : remote endpoint id,
    "payload" : payload message, valid when event is "OnMessageReceived",
    "is_reliable" : if message is reliable, valid when event is "OnMessageReceived"
}

NearbyConnections:StartDiscovery

{
    "event" : "OnEndpointFound" or "",
    "client_id" : client id,
    "remote_endpoint_id", remote endpoint id, valid when event is "OnEndpointLost"
    "endpoint_details" : endpoint info, valid when event is "OnEndpointFound"
    {
        "endpoint_id" : endpoint id,
        "device_id" : device id,
        "name" : name,
        "service_id" : service id
    }
}

NearbyConnections:SendConnectionRequest

second callback function result is same with NearbyConnections:AcceptConnectionRequest

{
    "client_id" : client id,
    "response" : connection response
    {
        "remote_endpoint_id" : remote endpoint id,
        "status" : status code;
        "payload" : payload message;
    }
},
{
    "event" : "OnMessageReceived" or "OnDisconnected",
    "client_id" : client id,
    "remote_endpoint_id" : remote endpoint id,
    "payload" : payload message, valid when event is "OnMessageReceived",
    "is_reliable" : if message is reliable, valid when event is "OnMessageReceived"
}

Manual Integration

If the SDKBOX Installer fails to complete successfully, it is possible to integrate SDKBOX manually. If the installer complete successfully, please do not complete anymore of this document. It is not necessary.

These steps are listed last in this document on purpose as they are seldom needed. If you find yourself using these steps, please, after completing, double back and re-read the steps above for other integration items.

Manual Integration For iOS

Drag and drop the following frameworks from the plugins/ios folder of theGooglePlay bundle into your Xcode project, check Copy items if needed when adding frameworks:

sdkbox.framework

PluginGPG.framework

GoogleAppUtilities.framework

GoogleAuthUtilities.framework

GoogleNetworkingUtilities.framework

GoogleOpenSource.framework

GooglePlus.bundle

GooglePlus.framework

GoogleSignIn.bundle

GoogleSignIn.framework

GoogleSymbolUtilities.framework

GoogleUtilities.framework

gpg.bundle

gpg.framework

The above frameworks depend upon other frameworks. You also need to add the following system frameworks, if you don't already have them:

AddressBook.framework

AssetsLibrary.framework

CoreData.framework

CoreLocation.framework

CoreMotion.framework

CoreTelephony.framework

CoreText.framework

Foundation.framework

MediaPlayer.framework

QuartzCore.framework

SafariServices

Security.framework

StoreKit

Security.framework

SystemConfiguration.framework

libc++.dylib

libz.dylib

Add a linker flag, if your setup requires it, to: Target -> Build Settings -> Linking -> Other Linker Flags:

-ObjC

Code changes

Set a rootview controller for GPG:

Update proj.ios_mac/ios/RootViewController.h Add this:

#import <GoogleSignIn/GoogleSignIn.h>

// Change RootViewController class definition to:
@interface RootViewController : UIViewController<GIDSignInUIDelegate>

Set Google Play signin listeners

Update proj.ios_mac/ios/AppController.mm

  1. Add this method:
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options {
    return [[GIDSignIn sharedInstance] handleURL:url
                               sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]
                                      annotation:options[UIApplicationOpenURLOptionsAnnotationKey]];
}
  1. In this method:
(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

add a call to (before return YES):

    // _viewController could also be named
    //  viewController, depending of the project type.
    [GIDSignIn sharedInstance].uiDelegate = _viewController;

Add URL types

Add the following URL types under your project > Info > URL Types

Further info

For more information check out the official documentation

Manual Integration For Android

SDKBOX supports three different kinds of Android projects command-line, eclipse and Android Studio.

Copy Files

Copy the following jar files from plugin/android/libs folder of this bundle into your project's /libs folder.

Plugingpg.jar

sdkbox.jar

Copy jni libs

Copy and overwrite all the folders from plugin/android/jni to your <project_root>/jni/ directory.

Edit AndroidManifest.xml

Add following meta-data tags:

<meta-data android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />
<meta-data android:name="com.google.android.gms.games.APP_ID"
    android:value="@string/google_app_id" />

Make sure to add an entry to the file res/values/string.xml of the form: <string name="google_app_id">777734739048</string> Change that value for your own generated play games App Id.

Edit Android.mk

Edit <project_root>/jni/Android.mk to:

Install in a folder named gpg inside your proj.android\jni directory

Add this to your android.mk file

Add include path

LOCAL_C_INCLUDES += ./gpg/include/

Add static libraries

Add additional requirements to LOCAL_WHOLE_STATIC_LIBRARIES:

LOCAL_WHOLE_STATIC_LIBRARIES += gpg-1
LOCAL_WHOLE_STATIC_LIBRARIES += PluginGPG
LOCAL_WHOLE_STATIC_LIBRARIES += sdkbox

Add a call to:

$(call import-add-path,$(LOCAL_PATH))

before any import-module statements.

Add additional import-module statements at the end:

$(call import-module, ./gpg)
$(call import-module, ./sdkbox)
$(call import-module, ./plugingpg)

Note: It is important to make sure these statements are above the existing $(call import-module,./prebuilt-mk) statement, if you are using the pre-built libraries.

Modify Application.mk (Cocos2d-x v3.0 to v3.2 only)

Edit <project_root>/jni/Application.mk to make sure APP_STL is defined correctly. If Application.mk contains APP_STL := c++_static, it should be changed to:

APP_STL := gnustl_static

Modify Cocos2dxActivity.java

Note: When using Cocos2d-x from source, different versions have Cocos2dxActivity.java in a different location. One way to find the location is to look in proj.android/project.properties. Example: android.library.reference.1=../../cocos2d-x/cocos/platform/android/java

In this case, Cocos2dxActivity.java should be located at:

../../cocos2d-x/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java
import android.content.Intent;
import com.sdkbox.plugin.SDKBox;
onLoadNativeLibraries();
SDKBox.init(this);
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          if(!SDKBox.onActivityResult(requestCode, resultCode, data)) {
            super.onActivityResult(requestCode, resultCode, data);
          }
    }
    @Override
    protected void onStart() {
          super.onStart();
          SDKBox.onStart();
    }
    @Override
    protected void onStop() {
          super.onStop();
          SDKBox.onStop();
    }
    @Override
    protected void onResume() {
          super.onResume();
          SDKBox.onResume();
    }
    @Override
    protected void onPause() {
          super.onPause();
          SDKBox.onPause();
    }
    @Override
    public void onBackPressed() {
          if(!SDKBox.onBackPressed()) {
            super.onBackPressed();
          }
    }

Manual Integration for Google Play Services SDK (dependent library only)

Suggestion

Please try the SDKBOX installer first. It will do all the following step for you automatically.

$ sdkbox import googleplayservices

Modify project.properties

An Android Library Reference for Google Play Services is required. The path will be different depending upon your setup. Also, this is an additional download that does not come as part of a standard install. To install use the sdk installer and choose extras->google play services. Here is an example of what this line could look like:

android.library.reference.1=
../android/sdk.latest/extras/google/google_play_services/libproject/
google-play-services_lib

Note: if you already have an android.library.reference.1 you can add another by incrementing the number as android.library.reference.2, etc.

Integration manually

We make a lite version of Google Play Services, the project repo is https://github.com/darkdukey/Google-Play-Service-Lite

Copy Files

Copy the gps folder from plugin folder of this bundle into your project's /libs folder.

Modify files for Eclipse

  1. Modify project.properties
# For source project
android.library.reference.2=../cocos2d/cocos/platform/android/java/libs/gps/

# Or
# For framework project
android.library.reference.1=libs/gps/

Modify files for Android Studio

1. Modify cocos2d/cocos/platform/android/libcocos2dx/build.gradle
 dependencies {
+    compile project(':gps')
     compile fileTree(dir: '../java/libs', include: ['*.jar'])
 }
2. Modify proj.android-studio/app/project.properties
 # Project target.
 target=android-14
+android.library.reference.1=../cocos2d/cocos/platform/android/java/libs/gps/
3. Modify proj.android-studio/settings.gradle
 project(':libcocos2dx').projectDir = new File(settingsDir, '../cocos2d/cocos/platform/android/libcocos2dx')
 include ':your_project_name'
 project(':your_project_name').projectDir = new File(settingsDir, 'app')
+
+include ':gps'
+project(':gps').projectDir = new File(settingsDir, '../cocos2d/cocos/platform/android/java/libs/gps')

Proguard (optional)

proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# cocos2d-x
-keep public class org.cocos2dx.** { *; }
-dontwarn org.cocos2dx.**
-keep public class com.chukong.** { *; }
-dontwarn com.chukong.**

# google play service
-keep class com.google.android.gms.** { *; }
-dontwarn com.google.android.gms.**

-keep class * extends java.util.ListResourceBundle {
    protected Object[][] getContents();
}

-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {
    public static final *** NULL;
}

-keepnames @com.google.android.gms.common.annotation.KeepName class *
-keepclassmembernames class * {
    @com.google.android.gms.common.annotation.KeepName *;
}

-keepnames class * implements android.os.Parcelable {
    public static final ** CREATOR;
}

#sdkbox
-keep class com.sdkbox.** { *; }
-dontwarn com.sdkbox.**

Note: Proguard only works with Release builds (i.e cocos run -m release) debug builds do not invoke Proguard rules.