‹ Facebook Doc Home

Facebook Integration Guide

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

Prerequisites

SDK Version

Integration

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:

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

Follow this link

FAQ

  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
    didFinishLaunchingWithOptions:launchOptions];

  app->run();

  return YES;
}

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

  BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application
    openURL:url
    sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]
    annotation:options[UIApplicationOpenURLOptionsAnnotationKey]
  ];
  // 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
    openURL:url
    sourceApplication:sourceApplication
    annotation:annotation
  ];
  // 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.

http://stackoverflow.com/a/39788102/5443510

Setup Android

JSON Configuration

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

options

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

"Facebook":
{
    "debug":true,
    "app_id":"",
    "url_scheme_suffix":""
}

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

https://developers.facebook.com/docs/ios/change-log-4x/

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.

preview

Usage

Register Javascript Functions

You need to register all the Facebook JS functions with cocos2d-x before using them.

To do this: * Modify ./frameworks/runtime-src/Classes/AppDelegate.cpp to include the following headers:

#include "PluginFacebookJS.hpp"
#include "PluginFacebookJSHelper.h"
sc->addRegisterCallback(register_all_PluginFacebookJS);
sc->addRegisterCallback(register_all_PluginFacebookJS_helper);

Initialize Facebook

Initialize the plugin by calling init() where appropriate in your code. We recommend to do this in the app.js. Example:

sdkbox.PluginFacebook.init();

Using Facebook

Login

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

sdkbox.PluginFacebook.login();

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

sdkbox.PluginFacebook.logout();

You can check whether user already logged in using

sdkbox.PluginFacebook.isLoggedIn();

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

Permissions

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

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

sdkbox.PluginFacebook.requestReadPermissions(["public_profile", "email"]);
sdkbox.PluginFacebook.requestPublishPermissions(["publish_actions"]);

Share

There are two types of sharing functionality.

var info = new Object();
info.type  = "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";
sdkbox.PluginFacebook.share(info);

share a photo:

var info = new Object();
info.type  = "photo";
info.title = "My Photo";
info.image = __path to image__;
sdkbox.PluginFacebook.share(info);

present a share dialog:

var info = new Object();
info.type  = "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";
sdkbox.PluginFacebook.dialog(info);

share a photo with comments:

var info = new Object();
info.type  = "photo";
info.title = "My Photo";
info.image = __path to image__;
sdkbox.PluginFacebook.dialog(info);

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

Invite

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 a URL for app and a preview image. Example:

sdkbox.PluginFacebook.inviteFriends(
 "https://fb.me/322164761287181",
 "http://www.cocos2d-x.org/attachments/801/cocos2dx_portrait.png");

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

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:

sdkbox.PluginFacebook.inviteFriendsWithInviteIds([], "title", "invitation text");

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:

var params = new Object();
sdkbox.PluginFacebook.api("/me/friendlists", "GET", params, "/me/friendlists");

Facebook events

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

sdkbox.PluginFacebook.setListener({
    onLogin: function(isLogin, msg) {},
    onAPI: function(tag, data) {},
    onSharedSuccess: function(data) {},
    onSharedFailed: function(data) {},
    onSharedCancel: function() {},
    onPermission: function(isLogin, msg) {}
});

API Reference

Methods

sdkbox.PluginFacebook.init();

initialize the plugin instance.

sdkbox.PluginFacebook.setLoginBehavior(loginBehavior);

login

sdkbox.PluginFacebook.login();

log in

This method calls login with a single permission: sdkbox::FB_PERM_READ_PUBLIC_PROFILE
sdkbox.PluginFacebook.login(permissions);
sdkbox.PluginFacebook.requestReadPermissions(permissions);

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

sdkbox.PluginFacebook.requestPublishPermissions(permissions);

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

sdkbox.PluginFacebook.logout();

log out

sdkbox.PluginFacebook.isLoggedIn();

Check whether the user logined or not

sdkbox.PluginFacebook.getUserID();

get UserID

sdkbox.PluginFacebook.getAccessToken();

get AccessToken

sdkbox.PluginFacebook.getPermissionList();

get permissoin list

sdkbox.PluginFacebook.share(info);

share

sdkbox.PluginFacebook.dialog(info);

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

sdkbox.PluginFacebook.getSDKVersion();

return the version of Facebook SDK

sdkbox.PluginFacebook.fetchFriends();

fetch friends data from Facebook

This data only reflects your friends that are using the app.
The number of friends defaults to 25.
sdkbox.PluginFacebook.canPresentWithFBApp(info);

check whether can present Facebook App

sdkbox.PluginFacebook.inviteFriends(app_link_url, preview_image_url);

Use the default FB dialog to invite friends.

sdkbox.PluginFacebook.setAppId(appId);

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

sdkbox.PluginFacebook.setAppURLSchemeSuffix(appURLSchemeSuffix);

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

sdkbox.PluginFacebook.requestGift(invite_ids,
                                   object_id,
                                   message,
                                   title,
                                   additional_data);

Ask friends for a gift

sdkbox.PluginFacebook.sendGift(friend_ids,
                                object_id,
                                title,
                                message,
                                additional_data);

Send friend a gift

sdkbox.PluginFacebook.logEvent(eventName);

Log event

sdkbox.PluginFacebook.logEvent(eventName, valueToSum);

Log event with value

sdkbox.PluginFacebook.logPurchase(mount, currency);

Log purchase event

Listeners

onLogin(isLogin, msg);
onSharedSuccess(message);
onSharedFailed(message);
onSharedCancel();
onAPI(key, jsonData);
onPermission(isLogin, msg);
onFetchFriends(ok, msg);
onRequestInvitableFriends(friends);
onInviteFriendsWithInviteIdsResult(result, msg);
onInviteFriendsResult(result, msg);
onGetUserInfo(userInfo);
onRequestGiftResult(result, msg);
onSendGiftResult(result, 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:

sdkbox.framework

PluginFacebook.framework

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:

Security.framework

AdSupport.framework

Copy all source and header files from plugin/jsbindings/ to your projects Classes folder.

NOTE: plugin/jsbindings/jsb2 for creator 1.7.

Add these same files, that you just copied, to Xcode by either dragging and dropping them into Xcode or by using File -> Add files to....

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.

PluginFacebook.jar

sdkbox.jar

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:configChanges=
         "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
  android:theme="@android:style/Theme.Translucent.NoTitleBar"
  android:label="@string/app_name" />

  <provider android:authorities="com.facebook.app.FacebookContentProvider__replace_with_your_app_id__"
  android:name="com.facebook.FacebookContentProvider"
  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"?>
  <resources>
      <string name="app_name">facebook</string>
      <string name="facebook_app_id">280194012150923</string>
  </resources>

Edit Android.mk

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

Add additional requirements to LOCAL_WHOLE_STATIC_LIBRARIES:

LOCAL_WHOLE_STATIC_LIBRARIES += PluginFacebook
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, ./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

Copy all source and header files from plugin/jsbindings/ to your projects Classes folder.

NOTE: plugin/jsbindings/jsb2 for creator 1.7.

Add all .cpp files, that you just copied, to Android.mk in the LOCAL_SRC_FILES section. Example

LOCAL_SRC_FILES := hellocpp/main.cpp \
                  ../../Classes/AppDelegate.cpp \
                  ../../Classes/HelloWorldScene.cpp \
                                    ../../Classes/NewSourceFile.cpp

Modify project.properties

Add following line to your project.properties

android.library.reference.1=./libs/facebook_lib

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 >= 2.4.0.3

  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:

cpp
  - 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)

lua
  - 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)

js
  - 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 < 2.4.0.3

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();
          }
    }

Proguard (optional)

proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# 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;
}

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

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:

-ObjC
-force_load
${PROJECT_DIR}/Frameworks/FBSDKLoginKit.framework/FBSDKLoginKit
-force_load
${PROJECT_DIR}/Frameworks/FBSDKCoreKit.framework/FBSDKCoreKit

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.