‹ Facebook Doc Home

Facebook Integration Guide

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


SDK Version


Open a terminal and use the following command to install the SDKBOX Facebook plugin. Make sure you setup the SDKBOX installer correctly.

$ sdkbox import facebook

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:


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.

Follow this link


  1. If you want to switch Facebook Login behavior (Facebook Native App / Web Dialog), clear Safari Cookie
  2. If you want to switch Facebook Login Account, clear Safari Cookie

Extra steps

The following step assuming you already registered as a Facebook Developer And created a new APP on Facebook, If not please follow up the Setup Facebook App section below.

Setup iOS

#import <FBSDKCoreKit/FBSDKCoreKit.h>

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

  // **************************
  // !! IMPORTANT !!
  // **************************
  // call [[FBSDKApplicationDelegate sharedInstance] application:didFinishLaunchingWithOptions
  // before app->run()

  [[FBSDKApplicationDelegate sharedInstance] application:application


  return YES;

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {

  BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application
  // Add any custom logic here.
  return handled;

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {

  BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application
  // Add any custom logic here.
  return handled;

login doesn't work on simulator on iOS 10, Xcode8

Go to the Project Target and then Capabilities and switch Keychain Sharing ON.


Setup Android

JSON Configuration

SDKBOX Installer will automatically create a sample configuration sdkbox_config.json for you


The Facebook App ID to be used by the SDK.

The url scheme suffix to be used by the SDK.

Here is an example of the Facebook configuration you can enable/disable debug mode for Facebook here


With the release of the Facebook SDK version 4.28.0, App Links Hosting is deprecated. It will be supported until February 5, 2018. https://developers.facebook.com/docs/applinks/hosting-api/

  1. Get APP_ACCESS_TOKEN (App Token) in https://developers.facebook.com/tools/access_token/
  2. Create links
curl https://graph.facebook.com/app/app_link_hosts \
-F access_token="APP_ACCESS_TOKEN" \
-F name="iOS App Link Object Example" \
-F ios=' [
      "url" : "sharesample://story/1234",
      "app_store_id" : 12345,
      "app_name" : "ShareSample",
  ]' \
-F web=' {
    "should_fallback" : false,
  1. Query link
curl -G https://graph.facebook.com/{YOUR_LINK_ID} \
-d access_token="APP_ACCESS_TOKEN" \
-d fields=canonical_url \
-d pretty=true

# or
curl -G https://graph.facebook.com \
-d access_token="APP_ACCESS_TOKEN" \
-d fields=app_links \
-d ids=https://fb.me/{YOUR_LINK_ID} \
-d pretty=true
  1. Update link
curl https://graph.facebook.com/{YOUR_LINK_ID} \
-F access_token="APP_ACCESS_TOKEN" \
-F name="FB App Link Object Example" \
-F ios=' [
      "url" : "sharesample://story/1234",
      "app_store_id" : 12345,
      "app_name" : "ShareSample",
  ]' \
-F web=' {
    "should_fallback" : false,

~~Invite Friends~~


The App Invites feature has been deprecated. (4.28.0 - November 7, 2017)

You need a canvas version of your game, but you can submit an empty/placeholder canvas version.

'Dashboard' -> 'Settings' -> 'Basic' -> 'Add Platform'

Navigate to your app's Facebook settings. Go to the ‘Facebook Web Games' pane in the Basic tab of your app's ‘Settings' page and fill in the ‘Facebook Web Games URL (https)' field with the URL where you are serving your game. Now save your changes.



Initialize Facebook

Initialize the plugin where appropriate in your code. We recommend to do this in the AppDelegate::applicationDidFinishLaunching() or AppController:didFinishLaunchingWithOptions(). Make sure to include the appropriate headers:

#include "PluginFacebook/PluginFacebook.h"

Using Facebook


First the user needs to login to Facebook in order to use it.


If a user doesn't want to use Facebook functionality anymore, logout.


You can check whether user already logged in using


Note: user only needs to perform login once, unless they logout


Facebook requires you to ask for the user's permission before you can perform actions, such as, posting on the user's behalf. There are two types of permission read and publish You can get a complete list of permissions here

SDKBOX provides the most commonly used permissions:

To request a permission, you do so by specifying what you want:

sdkbox::PluginFacebook::requestReadPermissions({FB_PERM_READ_PUBLIC_PROFILE, FB_PERM_READ_USER_FRIENDS});


There are two types of sharing functionality.

sdkbox::FBShareInfo info;
info.type  = sdkbox::FB_LINK;
info.link  = "http://www.cocos2d-x.org";
info.title = "cocos2d-x";
info.text  = "Best Game Engine";
info.image = "http://cocos2d-x.org/images/logo.png";

share a photo:

sdkbox::FBShareInfo info;
info.type  = sdkbox::FB_PHOTO;
info.title = "My Photo";
info.image = __path to image__;

present a share dialog:

sdkbox::FBShareInfo info;
info.type  = sdkbox::FB_LINK;
info.link  = "http://www.cocos2d-x.org";
info.title = "cocos2d-x";
info.text  = "Best Game Engine";
info.image = "http://cocos2d-x.org/images/logo.png";

share a photo with comments:

sdkbox::FBShareInfo info;
info.type  = sdkbox::FB_PHOTO;
info.title = "My Photo";
info.image = __path to image__;

Note: sharing photo with comments requires the Facebook app to be installed on the device.


There are both standard and custom Invite dialogs available to use when inviting your Friends.

When using the standard invite dialog, it is necessary to select the friends to send the invitation request too. The API call is inviteFriends() passing in an app link url and a preview image. Example:


Note: Contrary to what it may seem the app link url, it is not an App Store or Google Play application url. You must follow the instructions on this page and use the resulting url as the app_link_url parameter. Facebook hosts this file for the developer, but anyone could host their own file using this format

At runtime, a custom message can be attached to the invite request. It is not possible to set a predefined invite message.

Creating a custom invite dialog is a two step process, starting with a call to requestInvitableFriends() then a call to inviteFriendsWithInviteIds() to actually send the invites. Example:

std::vector<std::string> vec;
sdkbox::PluginFacebook::inviteFriendsWithInviteIds(vec, "Invitation title", "Invitation text up to 60 chars.");

The requestInvitableFriends() function has a Bundle(map) parameter, where the developer can define a few flags:

Flag Description
fields a comma separated values of the fields you want to get from your invitable friend's profiles.
exclude_ids a comma separated FB ids to exclude from the result.
limit number of friends per page.

A call to requestInvitableFriends() will return a different collection of friends per call, and it is Facebook's decision which ones to return first. This function returns a FBInvitableFriendsInfo object, which will contain a collection of the friends data and a pagination cursor object which has URLS for requesting the next and previous page of invitable friends.

The custom invite dialog is only available for games with a canvas implementation for the Facebook application. The canvas must be defined but doesn't need to how any web content. If the canvas is not defined a standard invite dialog is used instead.

Graph API

You can perform Graph API using the api function

For example, to get the friend list:

sdkbox::PluginFacebook::FBAPIParam params;
sdkbox::PluginFacebook::api("/me/friends", "GET", params, "/me/friends");

Facebook events

This allows you to catch Facebook events so that you can perform operations after Facebook events have occurred.

#include "PluginFacebook/PluginFacebook.h"
class MyClass : public sdkbox::FacebookListener
  void onLogin(bool isLogin, const std::string& msg);
  void onPermission(bool isLogin, const std::string& msg);
  void onAPI(const std::string& tag, const std::string& jsonData);
  void onSharedSuccess(const std::string& message);
  void onSharedFailed(const std::string& message);
  void onSharedCancel();

API Reference


static void init ( ) ;

initialize the plugin instance.

static void setListener ( FacebookListener * listener ) ;

Set listener to listen for facebook events

static FacebookListener * getListener ( ) ;

Get the listener

static void removeListener ( ) ;

Remove the listener, and can't listen to events anymore

static void setLoginBehavior ( int loginBehavior ) ;


static void login ( ) ;

log in

This method calls login with a single permission: sdkbox::FB_PERM_READ_PUBLIC_PROFILE
static void login ( std::vector <std::string> & permissions ) ;
static void requestReadPermissions ( const std::vector <std::string> & permissions ) ;

log in with specific read permissions, conflict with publish permissions https://developers.facebook.com/docs/facebook-login/permissions

static void requestPublishPermissions ( const std::vector <std::string> & permissions ) ;

log in with specific public permissions https://developers.facebook.com/docs/facebook-login/permissions

static void logout ( ) ;

log out

static bool isLoggedIn ( ) ;

Check whether the user logined or not

static std::string getUserID ( ) ;

get UserID

static std::string getAccessToken ( ) ;

get AccessToken

static std::vector <std::string> getPermissionList ( ) ;

get permissoin list

static void share ( const FBShareInfo & info ) ;


static void dialog ( const FBShareInfo & info ) ;

open a dialog of Facebook app or WebDialog (dialog with photo only avaible with native Facebook app)

static std::string getSDKVersion ( ) ;

return the version of Facebook SDK

static void api ( const std::string & path ,
                  const std::string & method ,
                  const FBAPIParam & params ,
                  const std::string & tag ) ;

use Facebook Open Graph api https://developers.facebook.com/docs/ios/graph

static void fetchFriends ( ) ;

fetch friends data from Facebook

This data only reflects your friends that are using the app.
The number of friends defaults to 25.
static std::vector <FBGraphUser> getFriends ( ) ;

get friends info

static bool canPresentWithFBApp ( const FBShareInfo & info ) ;

check whether can present Facebook App

static void requestInvitableFriends ( const FBAPIParam & ) ;

Get a vector of invitable friends info which can be used to build a custom friends invite dialog.

The default set will be limited to 25 friends.
The order in which FB sorts the friends, and which ones returns vary between calls.
The returned invitation tokens are not supposed to be long-term stored and may vary between
calls for the same friends.
The application must have a canvas configuration for this API call to work.
static void inviteFriendsWithInviteIds ( const std::vector <std::string> & invite_ids ,
                                         const std::string & title ,
                                         const std::string & invite_text ) ;

Invite friends based on the result obtained from a call to requestInvitableFriends

static void inviteFriends ( const std::string & app_link_url ,
                            const std::string & preview_image_url ) ;

Use the default FB dialog to invite friends.

static void setAppId ( const std::string & appId ) ;

Set the Facebook App ID to be used by the FB SDK.

static void setAppURLSchemeSuffix ( const std::string & appURLSchemeSuffix ) ;

Set the app url scheme suffix used by the FB SDK.

static void requestGift ( const std::vector <std::string> & invite_ids ,
                          const std::string & object_id ,
                          const std::string & message ,
                          const std::string & title = "" ,
                          const std::string & additional_data = "" ) ;

Ask friends for a gift

static void sendGift ( const std::vector <std::string> & friend_ids ,
                       const std::string & object_id ,
                       const std::string & title ,
                       const std::string & message ,
                       const std::string & additional_data = "" ) ;

Send friend a gift

static void logEvent ( const std::string & eventName ) ;

Log event

static void logEvent ( const std::string & eventName , float valueToSum ) ;

Log event with value

static void logPurchase ( float mount , const std::string & currency ) ;

Log purchase event


void onLogin ( bool isLogin , const std::string & msg );
void onSharedSuccess ( const std::string & message );
void onSharedFailed ( const std::string & message );
void onSharedCancel ( );
void onAPI ( const std::string & key , const std::string & jsonData );
void onPermission ( bool isLogin , const std::string & msg );
void onFetchFriends ( bool ok , const std::string & msg );
void onRequestInvitableFriends ( const FBInvitableFriendsInfo & friends );
void onInviteFriendsWithInviteIdsResult ( bool result ,
                                          const std::string & msg );
void onInviteFriendsResult ( bool result , const std::string & msg );
void onGetUserInfo ( const FBGraphUser & userInfo );
void onRequestGiftResult ( bool result , const std::string & msg ) 
void onSendGiftResult ( bool result , const std::string & msg ) 

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 theFacebook bundle into your Xcode project, check Copy items if needed when adding frameworks:



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



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.



Copy the facebook_lib directories from plugin/android/libs to your <project_root>/libs/ directory.

Copy jni libs

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

Edit AndroidManifest.xml

Include the following permissions above the application tag:

  <uses-permission android:name="android.permission.INTERNET" />

There are also a few necessary meta-data tags that also need to be added:

<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
<activity android:name="com.facebook.FacebookActivity"
  android:label="@string/app_name" />

  <provider android:authorities="com.facebook.app.FacebookContentProvider__replace_with_your_app_id__"
  android:exported="true" />

Edit strings.xml

Open res/values/strings.xml, Add a new string with the name facebook_app_id and value as your Facebook App ID. Example:

  <?xml version="1.0" encoding="utf-8"?>
      <string name="app_name">facebook</string>
      <string name="facebook_app_id">280194012150923</string>

Edit Android.mk

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

Add additional requirements to LOCAL_WHOLE_STATIC_LIBRARIES:


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, ./sdkbox)
$(call import-module, ./pluginfacebook)

This means that your ordering should look similar to this:

$(call import-add-path,$(LOCAL_PATH))
$(call import-module, ./sdkbox)
$(call import-module, ./pluginfacebook)

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 project.properties

Add following line to your project.properties


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

Modify AppActivity.java

Plugin >=

  1. Find the AppActivity.java
find . -name "AppActivity.java"
  1. Replace extends Cocos2dxActivity with extends com.sdkbox.plugin.SDKBoxActivity

Example of the directory where the AppActivity.java file is located:

  - proj.android/src/org/cocos2dx/cpp/AppActivity.java
  - proj.android-studio/app/src/org/cocos2dx/cpp/AppActivity.java
  - proj.android/app/src/org/cocos2dx/cpp/AppActivity.java ( from cocos2d-x 3.17)

  - frameworks/runtime-src/proj.android/src/org/cocos2dx/lua/AppActivity.java
  - frameworks/runtime-src/proj.android-studio/app/src/org/cocos2dx/lua/AppActivity.java
  - frameworks/runtime-src/proj.android/app/src/org/cocos2dx/lua/AppActivity.java (from cocos2d-x 3.17)

  - frameworks/runtime-src/proj.android/src/org/cocos2dx/javascript/AppActivity.java
  - frameworks/runtime-src/proj.android/app/src/org/cocos2dx/javascript/AppActivity.java ( from cocos2d-x 3.17)

Plugin <

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:

import android.content.Intent;
import com.sdkbox.plugin.SDKBox;
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          if(!SDKBox.onActivityResult(requestCode, resultCode, data)) {
            super.onActivityResult(requestCode, resultCode, data);
    protected void onStart() {
    protected void onStop() {
    protected void onResume() {
    protected void onPause() {
    public void onBackPressed() {
          if(!SDKBox.onBackPressed()) {

Proguard (optional)

# facebook
-keep public class com.facebook.** { *; }
-dontwarn com.facebook.**

# cocos2d-x
-keep public class org.cocos2dx.** { *; }
-dontwarn org.cocos2dx.**
-keep public class com.chukong.** { *; }
-dontwarn com.chukong.**

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

-keep class com.google.protobuf.** { *; }
-dontwarn com.google.protobuf.**

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

-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.

Facebook Compile Issue

now SDKBox include Facebook iOS SDK 7.1.1 static library.

Facebook iOS SDK 7.1.1 static library conflict with Other Linker Flags -> -ObjC.

if you got following error, maybe the reason is conflict.

Could not find or use auto-linked library 'swiftCompatibilityDynamicReplacements'
Could not find or use auto-linked library 'swiftCore'
Could not find or use auto-linked library 'swiftQuartzCore'
Could not find or use auto-linked library 'swiftDispatch'
Could not find or use auto-linked library 'swiftAVFoundation'
Could not find or use auto-linked library 'swiftCoreMedia'
Could not find or use auto-linked library 'swiftCoreAudio'
Could not find or use auto-linked library 'swiftPhotos'
Could not find or use auto-linked library 'swiftCoreMIDI'
Could not find or use auto-linked library 'swiftCoreLocation'
Undefined symbol: protocol descriptor for Foundation._ErrorCodeProtocol
Undefined symbol: associated conformance descriptor for Foundation._ErrorCodeProtocol._ErrorType: Foundation._BridgedStoredNSError
Undefined symbol: base conformance descriptor for Foundation._BridgedStoredNSError: Foundation.CustomNSError
Undefined symbol: base conformance descriptor for Foundation._BridgedStoredNSError: Swift.Hashable
Undefined symbol: base conformance descriptor for Foundation._ErrorCodeProtocol: Swift.Equatable
Undefined symbol: associated conformance descriptor for Foundation._BridgedStoredNSError.Code: Foundation._ErrorCodeProtocol
Undefined symbol: associated conformance descriptor for Foundation._BridgedStoredNSError.Code: Swift.RawRepresentable
Undefined symbol: method descriptor for Foundation._BridgedStoredNSError.init(_nsError: __C.NSError) -> A
Undefined symbol: base conformance descriptor for Foundation.CustomNSError: Swift.Error
Undefined symbol: method descriptor for static Foundation.CustomNSError.errorDomain.getter : Swift.String
Undefined symbol: method descriptor for Foundation._ObjectiveCBridgeableError.init(_bridgedNSError: __shared __C.NSError) -> A?
Undefined symbol: method descriptor for Swift.Error._code.getter : Swift.Int
Undefined symbol: method descriptor for Swift.Error._userInfo.getter : Swift.AnyObject?
Undefined symbol: method descriptor for Swift.Error._getEmbeddedNSError() -> Swift.AnyObject?
Undefined symbol: protocol conformance descriptor for Swift.Int : Swift.FixedWidthInteger in Swift
Undefined symbol: type metadata for Swift.Int
Undefined symbol: protocol descriptor for Foundation.CustomNSError
Undefined symbol: static Swift._DictionaryStorage.allocate(capacity: Swift.Int) -> Swift._DictionaryStorage<A, B>
Undefined symbol: __swiftEmptyDictionarySingleton

solution A

solution B

  1. if your project need -ObjC link flag, then you can use Facebook dynamic library

  2. unzip and replace Facebook related framework FBSDK*.framework.

  3. Change Xcode Setting, Project Setting -> General -> Frameworks, Libraries, and Embedded Content -> FBSDK*.framework -> Embed & Sign

Facebook Compile Issue

if you got following error,

dyld: Library not loaded: @rpath/libswiftCore.dylib

you can try do like this, Xcode Project -> target -> Build Setting/All -> Always Embed Swift Standard Libraries -> YES

Facebook Crash Issue

if you got following error,

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[NSError fbErrorFromReturnURLParameters:]: unrecognized selector sent to class 0x1e0bdf480'

you can do add follow settings to Other Linker Flags:


Facebook Login View

if you got this issue. the Open in Facebook dialog is not response, when you use fb to login on iOS horizontal screen.

please, check file Info.plist, Do NOT include fb-messenger-api20140430 in item LSApplicationQueriesSchemes. fb-messenger-api20140430 is for old version fb sdk. the new value should be fb-messenger-share-api.