Facebook Gameroom Integration Guide
For the C++ version of cocos2d-x v3.x - (all other versions)
Precondition
Please follow the guide from Facebook to setup a Facebook application with Gameroom configurations.
Integration with Cocos Project
Using SDKBOX Installer (recommend)
-
With SDKBOX Installer, you can install Gameroom Plugin in Windows easily. Please access SDKBOX official website for more information to get SDKBOX Installer.
-
After getting SDKBOX Installer, you can import Gameroom Plugin with it:
sdkbox import gameroom
- Or, if the gameroom plugin is in local, you can also import it like this:
sdkbox import -b c:\the_path_to_gameroom_plugin\sdkbox-gameroom_v0.01
Manual Integration
If you want to install Gameroom Plugin manually, you would modify more configurations step by step. It's a little perplex, we don't recommend you to do this.
-
Find the Visual Studio Solution file(.sln) and open it. For Cpp project created by
cocos
, you can find the solution file in "./proj.win32" sub-directory. We name the "proj.win32" project-dir for depict conveniently. -
Unzip the Gameromm Plugin package to get a dir including the plugin files. It's called plugin-dir.
-
Copy header files. For CPP project, copy
win32/include/*.h
in plugin-dir toinclude
in your project-dir. -
Copy library files
win32/libs/*.lib
in plugin-dir tolibs
in your project-dir. -
Deploy Facebook Gameroom SDK files.
a. Copy header files
sdk/fbg/*.h
in plugin-dir toinclude/fbg
in your project-dir.b. Copy library files
sdk/libs/*.lib
in plugin-dir tolibs
in your project-dir. -
Modify the configuration of Visual Studio. Follow the steps as below:
a. Add an include directory for the compiler, click: project(on top bar) -> properties -> Configuration Properties -> VC++ Directories -> Include Directories (click and edit, add a new entry).
And then add
$(solutiondir)include
.b. Add a library directory for *.lib files, click: project(on top bar) -> properties -> Configuration Properties -> VC++ Directories -> Library Directories (click and edit, add a new entry).
And then add
$(solutiondir)libs
.c. Link the *.lib files, click: project(on top bar) -> properties -> Configuration Properties -> Linker -> Input -> Additional Dependencies (click and edit, add a new entry).
And then add
GameroomPlugin32.lib
andLibFBGPlatform32.lib
.For
debug
version, Please addGameroomPlugin32.debug.lib
. -
Patch the
AppDelegate.cpp
. Open theAppDelegate.cpp
in project-dir/Classes. -
The following steps can also be fulfilled with
patch
tool. The fileAppDelegate.cpp3.15.patch
in plugin-dir is for CPP project.
patch AppDelegate.cpp ./plugin-dir/path/AppDelegate.cpp3.15.patch
- Before
USING_NS_CC
, add the SDKBOX header files:
#ifdef SDKBOX_ENABLED
#include "PluginGameroom.h"
#endif
- In the ctor and dtor of
AppDelegate
, redirect the STDOUT to a file since Facebook SDK don't offer any logging APIs.
AppDelegate::AppDelegate()
{
freopen("fbg.log", "w", stdout);
}
AppDelegate::~AppDelegate()
{
...
fclose(stdout);
}
- At beginning of the function
applicationDidFinishLaunching
, initialize the SDKBOX Gameroom Plugin:
#ifdef SDKBOX_ENABLED
sdkbox::PluginGameroom::init("your_app_id");
#endif
- And after the judgement statement
if (!glview)
, add these codes:
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
const wchar_t title[]{ L"Facebook Gameroom" };
auto parentWin = FindWindow(NULL, title);
// set dpi for app.
auto res_dpi = SetProcessDPIAware();
RECT rect;
GetWindowRect(parentWin, &rect);
glview = GLViewImpl::createWithRect("cocos_sample_cpp", Rect(0, 0, rect.right - rect.left - 20, rect.bottom - rect.top - 100), 1.0f, true);
director->setOpenGLView(glview);
auto currentWin = Director::getInstance()->getOpenGLView()->getWin32Window();
SetParent(currentWin, parentWin);
#else
glview = GLViewImpl::create("cocos_sample_cpp");
director->setOpenGLView(glview);
#endif
Usage
About the details of these methods depicted below, you can access the section API Reference. And if you wanna know the corresponding functions in Facebook Gameroom SDK, you can refer to Facebook Gameroom SDK website.
Initialize Plugin Gameroom
Before you call other APIs, you should Initialize the plugin. We recommend to do this in the AppDelegate::applicationDidFinishLaunching()
or AppController:didFinishLaunchingWithOptions()
. Make sure to include the appropriate headers:
#ifdef SDKBOX_ENABLED
#include "PluginGameroom.h"
#endif
bool AppDelegate::applicationDidFinishLaunching() {
#ifdef SDKBOX_ENABLED
// fill your Facebook Application ID
sdkbox::PluginGameroom::init("1234567890");
#endif
}
Set Listener
As other SDKBOX plugins, you need to set a listener class to handle events.
sdkbox::PluginGameroom::setListener(pointer_to_listener_class);
The listener class should inherit from sdkbox::GameroomListener
.
class HelloWorldListener : public sdkbox::GameroomListener
{
public:
// ...
virtual void onLoginAccessTokenMsg(sdkbox::AccessTokenHandle);
virtual void onFeedShareMsg(sdkbox::FeedShareHandle);
virtual void onPurchaseIAPMsg(sdkbox::PurchaseHandle);
virtual void onHasLicenseMsg(sdkbox::HasLicenseHandle);
virtual void onAppRequestMsg(sdkbox::AppRequestHandle);
};
Each callback will be explained below.
User Login
After the plugin is initialized, when your game starts, you should make a login call to retrieve player information. You can use a simple method login()
or another method loginWithScopes()
for it.
The different between these two methods is that login()
method will always apply 3 permissions of the player: user_friends
, email
and public_profile
.
SDKBOX::PluginGameroom::login();
But you can pass some parameters to loginWithScopes()
method to designate witch permissions are applied. In this example, user_friends
and email
will be applied.
std::vector<std::string> loginScopes{ "user_friends", "email" };
sdkbox::PluginGameroom::loginWithScopes(2, loginScopes);
You can also check whether the player has logged in:
auto ret = sdkbox::PluginGameroom::isLoggedIn();
if (!ret) {
// do something
}
The player login action will trigger onLoginAccessTokenMsg
callback in your listener class. You can use some methods to retrieve the player's login information via the parameter accessTokenHandle
.
void HelloWorld::onLoginAccessTokenMsg(sdkbox::AccessTokenHandle accessTokenHandle) {
auto isValid = sdkbox::PluginGameroom::accessTokenIsValid(accessTokenHandle);
if (!isValid) {
// user not logged in
return;
}
auto userid = sdkbox::PluginGameroom::accessTokenGetUserID(accessTokenHandle);
char token_string[512];
auto size = sdkbox::PluginGameroom::accessTokenGetTokenString(accessTokenHandle, token_string, 512);
auto expiration_timestamp = sdkbox::PluginGameroom::accessTokenGetExpirationTimestamp(accessTokenHandle);
fbgLoginScope permissions[512];
auto permission_size = sdkbox::PluginGameroom::accessTokenGetPermissions(accessTokenHandle, permissions, 512);
::CCLOG(
"OnLoginAccessTokenMsg, User ID: %lld\nAccess Token: %s\nExpiration Timestamp: %lld, Permission Count: %zu\nPermissions: ",
(long long)userid,
token_string,
(long long)expiration_timestamp,
permission_size
);
for (size_t i = 0; i < permission_size; i++) {
::CCLOG("%s", sdkbox::PluginGameroom::loginScopeToString(permissions[i]));
}
::CCLOG("\n");
}
Feed Share
In your game, you can offer the sharing function to the players:
sdkbox::PluginGameroom::feedShare(
nullptr,
"https://www.facebook.com",
"Testing Link Name",
"Testing Link Caption",
"Testing Link Description",
"http://www.pamperedpetz.net/wp-content/uploads/2015/09/Puppy1.jpg",
nullptr
);
Above example shares an image to the player's Facebook.
In your listener class, onFeedShareMsg
will be called after sharing with the argument feedShareHandle
. Post ID
can be returned if you call the method feedShareGetPostID()
.
void HelloWorld::onFeedShareMsg(sdkbox::FeedShareHandle feedShareHandle) {
auto postId = sdkbox::PluginGameroom::feedShareGetPostID(feedShareHandle);
::CCLOG(
"onFeedShareMsg, Feed Share Post ID: %ld\n",
(long)postId
);
}
IAP
IAP funciton includes 3 aspects:
- IAP with a product ID configured in your Facebook App.
sdkbox::PluginGameroom::purchaseIAP(
"sdkbox_product_2",
1,
1,
1,
nullptr,
nullptr,
nullptr
);
- IAP with an url link.
sdkbox::PluginGameroom::purchaseIAPWithProductURL(
"https://friendsmash-unity.herokuapp.com/payments/100coins.php",
1,
1,
1,
nullptr,
nullptr,
nullptr
);
- Purchase a premium version or license.
sdkbox::PluginGameroom::payPremium();
These 3 types of IAP will trigger onPurchaseIAPMsg
callback. Here is an example to show how to handle the IAP result.
void HelloWorld::onPurchaseIAPMsg(sdkbox::PurchaseHandle payHandle) {
size_t size;
char paymentId[512];
size = sdkbox::PluginGameroom::purchaseGetPaymentID(payHandle, paymentId, 512);
auto amount = sdkbox::PluginGameroom::purchaseGetAmount(payHandle);
char currency[512];
size = sdkbox::PluginGameroom::purchaseGetCurrency(payHandle, currency, 512);
auto purchaseTime = sdkbox::PluginGameroom::purchaseGetPurchaseTime(payHandle);
char productId[512];
size = sdkbox::PluginGameroom::purchaseGetProductID(payHandle, productId, 512);
char purchaseToken[512];
size = sdkbox::PluginGameroom::purchaseGetPurchaseToken(payHandle, purchaseToken, 512);
auto quantity = sdkbox::PluginGameroom::purchaseGetQuantity(payHandle);
char requestId[512];
size = sdkbox::PluginGameroom::purchaseGetRequestID(payHandle, requestId, 512);
char status[512];
size = sdkbox::PluginGameroom::purchaseGetStatus(payHandle, status, 512);
char signedRequest[512];
size = sdkbox::PluginGameroom::purchaseGetSignedRequest(payHandle, signedRequest, 512);
auto errorCode = sdkbox::PluginGameroom::purchaseGetErrorCode(payHandle);
char errorMessage[512];
size = sdkbox::PluginGameroom::purchaseGetErrorMessage(payHandle, errorMessage, 512);
::CCLOG(
"onPurchaseIAPMsg, Purchase Handle: %s\nAmount: %d\nCurrency: %s\nPurchase Time: %lld\n"
"Product Id:%s\nPurchase Token: %s\nQuantity: %d\nRequest Id: %s\n"
"Status: %s\nSignedRequest: %s\nError Code: %lld\nErrorMessage: %s\n",
paymentId,
(int)amount,
currency,
(long long)purchaseTime,
productId,
purchaseToken,
(int)quantity,
requestId,
status,
signedRequest,
(long long)errorCode,
errorMessage
);
}
In addtion, you can use hasLicense()
method to check whether the player has got the license or premium version.
sdkbox::PluginGameroom::hasLicense();
Please note that this checking operation will trigger a callback named onHasLicenseMsg
. Bizarrely, you should get the license ID via the method purchaseGetLicense()
in callback(Faceebook Gameroom SDK demands these behaviors).
void HelloWorld::onHasLicenseMsg(sdkbox::HasLicenseHandle hasLicenseHandle) {
auto hasLicense = sdkbox::PluginGameroom::purchaseGetLicense(hasLicenseHandle);
::CCLOG(
"onHasLicenseMsg, Has License: %llu",
hasLicense
);
}
Send App Events
You can log app events for Facebook Analytics via the following functions:
auto formData = sdkbox::PluginGameroom::formDataCreateNew();
char key[sdkbox::FBG_BUFFER_SIZE]{"sdkbox_key"};
char value[sdkbox::FBG_BUFFER_SIZE]{"3.1415"};
sdkbox::PluginGameroom::formDataSet(formData, key, sdkbox::FBG_BUFFER_SIZE, value, sdkbox::FBG_BUFFER_SIZE);
sdkbox::PluginGameroom::logAppEvent("test_event", formData);
::CCLOG("Gameroom Send App Event with sum value");
sdkbox::PluginGameroom::logAppEventWithValueToSum("test_event", formData, 1024.2);
sdkbox::PluginGameroom::formDataDispose(formData);
The key-value pairs are carried in FormData
structure. And if you intend to offer an extra value in an event, you should use logAppEventWithValueToSum()
method.
Send App Requests
To invoke an app request within your game, you may use the following call to trigger the dialog:
sdkbox::PluginGameroom::appRequest(
"hello world, try this gameroom sdk demo.",
nullptr,
nullptr,
"faceboo_user_id_1,facebook_user_id_2",
nullptr,
nullptr,
20,
nullptr,
"hello"
);
In common, you don't need to set the users' ID in order to let the player choose which friends he want to send the requests.
sdkbox::PluginGameroom::appRequest(
"hello world, try this gameroom sdk demo.",
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
20,
nullptr,
"hello"
);
In the callback of sending app requests, you can hanedle the result:
void HelloWorld::onAppRequestMsg(fbgAppRequestHandle appRequestHandle) {
char objectID[sdkbox::FBG_BUFFER_SIZE];
//auto size = sdkbox::PluginGameroom::appRequestGetRequestObjectID(appRequestHandle, objectID, sdkbox::FBG_BUFFER_SIZE);
auto size = fbg_AppRequest_GetRequestObjectId(appRequestHandle, objectID, sdkbox::FBG_BUFFER_SIZE);
::CCLOG("onAppRequestMsg");
::CCLOG("size = %lu\n", size); // return 0 here, indicating that appRequestHandle is invalid.
char toUser[sdkbox::FBG_BUFFER_SIZE];
size = sdkbox::PluginGameroom::appRequestGetTo(appRequestHandle, toUser, sdkbox::FBG_BUFFER_SIZE);
::CCLOG("size = %lu\n", size);
::CCLOG(
"object id: %s, to user: %s",
objectID,
toUser
);
}
API Reference
Although you can use these methods anywhere, some methods need Gameroom handle
object in practice. So this document distinguishes the common Methods
and the Methods in Listener Callbacks
.
Methods
static int init(const char* appID);
Initialize the Gameroom Plugin.
appID
is your Facebook Application ID. The method will return 0 if the plugin is Initialized successfully.
static std::string login();
Player login. It will return a string representing
GameroomReq
.
static std::string loginWithScopes(uint32_t scopeCount, const std::vector<std::string>& loginScopes);
Player login with some permissions.
scopeCount
is the total of the permissions.loginScopes
is a vector which can include these values:public_profile
,user_friends
andpublish_actions
. The method will return a string representingGameroomReq
.
static bool isLoggedIn();
Check whether the player has logged in.
static std::string feedShare(
const char* toId,
const char* link,
const char* linkName,
const char* linkCaption,
const char* linkDescription,
const char* pictureLink,
const char* mediaSource
);
Share to Facebook. The meaning of each parameters is as its name. The method will return a string representing
GameroomReq
.
static std::string purchaseIAP(
const char* product,
uint32_t quantity,
uint32_t quantityMin,
uint32_t quantityMax,
const char* requestId,
const char* pricePointId,
const char* testCurrency
);
Purchase a product with a prouduct ID.
quantity
is the number of product,quantityMin
is the minimum number of quantity of product,quantityMax
is the maximum of quantity of product. For other parameters, you can refer to Facebook Gameroom SDK and SDKBOX Gameroom Plugin Sample. The method will return a string representingGameroomReq
.
static std::string purchaseIAPWithProductURL(
const char* product,
uint32_t quantity,
uint32_t quantityMin,
uint32_t quantityMax,
const char* requestId,
const char* pricePointId,
const char* testCurrency
);
Purchase a product with a prouduct url link.
quantity
is the number of product,quantityMin
is the minimum number of quantity of product,quantityMax
is the maximum of quantity of product. For other parameters, you can refer to Facebook Gameroom SDK. The method will return a string representingGameroomReq
.
static std::string payPremium();
Purchase a premium version or license. It will return a string representing
GameroomReq
.
static std::string hasLicense();
Check whether the player has license or premium version. The method will return a string representing
GameroomReq
.
static std::string logAppEvent(const char* eventName, const FormDataHandle formData);
Send an event to Facebook Analytics.
FormDataHandle
is created and set by other APIs. The method will return a string representingGameroomReq
.
static std::string logAppEventWithValueToSum(const char* eventName, const FormDataHandle formData, float valueToSum);
Send an event to Facebook Analytics with an extra value
valueToSum
.FormDataHandle
is created and set by other APIs. The method will return a string representingGameroomReq
.
static const FormDataHandle formDataCreateNew();
Create a
FormDataHandle
object to store key-value pairs in an app event.
static void formDataSet(
const FormDataHandle obj,
char *fieldNameBuffer,
size_t fieldNameBufferLen,
char *valueBuffer,
size_t valueBufferLen
);
Store a key-value pair into
FormDataHandle
object.
static size_t formDataGet(
const FormDataHandle obj,
char *fieldNameBuffer,
size_t fieldNameBufferLen,
char *valueBuffer,
size_t valueBufferLen
);
Get a key-value pair from
FormDataHandle
object.
static void formDataDelete(const FormDataHandle obj, char *fieldNameBuffer, size_t fieldNameBufferLen);
Delete a key-value pair from
FormDataHandle
object.
static bool formDataHas(const FormDataHandle obj, char* fieldNameBuffer, size_t fieldNameBufferLen);
Check whether the
FormDataHandle
object has a specified key-value pair.
static void formDataDispose(const FormDataHandle obj);
Destory
FormDataHandle
object.
static std::string appRequest(
const char* message,
const char* actionType,
const char* objectID,
const char* to,
const char* filters,
const char* excludeIDs,
uint32_t maxRecipients,
const char* data,
const char* title
);
Send an app request to some users. if parameter
to
isnullptr
, this method will let player to choose which users he want to send the request. For other parameters, please refer to Facebook Game Service Requests and SDKBOX Gameroom Plugin Sample. The method will return a string representingGameroomReq
.
Listener Callbacks
virtual void onLoginAccessTokenMsg(sdkbox::AccessTokenHandle);
Triggered by
login()
orloginWithScopes()
.
virtual void onFeedShareMsg(sdkbox::FeedShareHandle);
Triggered by
feedShare()
.
virtual void onPurchaseIAPMsg(sdkbox::PurchaseHandle);
Triggered by
purchaseIAP()
,purchaseIAPWithProductURL()
orpayPremium()
.
virtual void onHasLicenseMsg(sdkbox::HasLicenseHandle);
Triggered by
hasLicense()
.
virtual void onAppRequestMsg(sdkbox::AppRequestHandle);
Triggered by
appRequest()
.
static int setListener(GameroomListener *);
Set a pointer to listener object.
static GameroomListener* removeListener();
Delete current listener object, return the pointer to it.
static GameroomListener* listener();
Return the pointer to current listener object.
Methods in Listener Callbacks
These methods can be called in onLoginAccessTokenMsg
to get some information from the AccessTokenHandle
object.
static bool accessTokenIsValid(AccessTokenHandle obj);
Check the access token is valid.
static FacebookID accessTokenGetUserID(AccessTokenHandle obj);
Get the Facebook User ID.
static size_t accessTokenGetTokenString(AccessTokenHandle obj, char* buffer, size_t bufferLen);
Get the access token string.
static uint64_t accessTokenGetExpirationTimestamp(AccessTokenHandle obj);
Get the expired time of access Token.
static size_t accessTokenGetPermissions(AccessTokenHandle obj, LoginScope* buffer, size_t bufferLen);
Get the applied permissions.
static const char* loginScopeToString(LoginScope loginScope);
Get the string name of applied permission.
This method can be called in onFeedShareMsg
to get the post ID.
static FacebookID feedShareGetPostID(FeedShareHandle obj);
Get the post ID.
These methods can be called in onPurchaseIAPMsg
to get some information from the PurchaseHandle
object.
static size_t purchaseGetPaymentID(PurchaseHandle obj, char* buffer, size_t bufferLen);
Get the payment ID.
static uint32_t purchaseGetAmount(PurchaseHandle obj);
Get the of purchasing.
static size_t purchaseGetCurrency(PurchaseHandle obj, char* buffer, size_t bufferLen);
Get the currency of purchasing.
static uint64_t purchaseGetPurchaseTime(PurchaseHandle obj);
Get the time of purchasing.
static size_t purchaseGetProductID(PurchaseHandle obj, char* buffer, size_t bufferLen);
Get the product ID.
static size_t purchaseGetPurchaseToken(PurchaseHandle obj, char* buffer, size_t bufferLen);
Get the token of purchasing.
static uint32_t purchaseGetQuantity(PurchaseHandle obj);
Get the quantity of purchasing.
static size_t purchaseGetRequestID(PurchaseHandle obj, char* buffer, size_t bufferLen);
Get the request ID of purchasing.
static size_t purchaseGetStatus(PurchaseHandle obj, char* buffer, size_t bufferLen);
Get the status of purchasing.
static size_t purchaseGetSignedRequest(PurchaseHandle obj, char* buffer, size_t bufferLen);
Get the signed request.
static uint64_t purchaseGetErrorCode(PurchaseHandle obj);
Get the error code of purchasing.
static size_t purchaseGetErrorMessage(PurchaseHandle obj, char* buffer, size_t bufferLen);
Get the error message of purchasing.
This method can be called on onHasLicenseMsg
to get license ID.
static FacebookID purchaseGetLicense(HasLicenseHandle obj);
Get the license ID.
This methods can be called on onAppRequestMsg
to get some information of app request.
static size_t appRequestGetRequestObjectID(const AppRequestHandle obj, char *buffer, size_t bufferLen);
Get the request ID of app request.
static size_t appRequestGetTo(const AppRequestHandle obj, char *buffer, size_t bufferLen);
Get the receivers of app request.