Child pages
  • Facebook integration
Skip to end of metadata
Go to start of metadata

Bug Fix/Change notice

07-25-2014: "social.fb.userManager": added support for users who will not get a hashed password

06-19-2014: "social.api.facebookLogin" script, "social.fb.userManager":

  • script, not asking to retrieve he username from the Facebook graph User object, as this has been deprecated in v 2.0. User's login is now replaced with the Facebook user's email in Apstrata, or, if email is not specified, with the combination of user's first_name + "_" + "last_name"
  • email is not mandatory anymore when creating a user from a Facebook account
  • fixed bug in error handling

09-25-2013: "social.api.facebookLogin" script : added the capability to request new permissions + bug fix on September 25 2013. Please update your version if it is anterior to the current one.

09-25-2013: "social.api.fb.checkPermissions": new script

09-25-2013: "social.fb.userManager" : added new capabilities (check permissions) on August 05 2013. Please update your version if it is anterior to the current one.

09-25-2013: "social.fb.facebookManager" script was updated on August 25 2013. Please update your version if it is anterior to the current one.

09-25-2013: "social.fb.common" script was updated with new properties (Facebook instrumentation) on August 25 2013. You do not need to update your version unless FB's instrumentation needed.

08-06-2013: A bug was fixed in the "social.api.fb.getUserFriends" script on August 06 2013. Please update your version if it is anterior to the current one.

1. Content and purpose

Attached to the page are Apstrata server-side scripts that will allow you to easily integrate your  Apstrata application with Facebook, notably to log in to your application through Facebook, and/or post or publish action to your users' Facebook timeline and wall.

 How Apstrata helps you leverage Facebook's APIs

Apstrata helps developers to integrate their applications with Facebooks in three different ways:

The native apsdb.social.facebook object

Facebook is natively available in Apstrata's server-side scripts through the "apsdb.social.facebook" object. This object exposes the following functions to the developers:

  • getRequestToken: this function allows the developer to request for an authorization URL from Facebook, in order to use it in a "log-in-through-Facebook" scenario
  • getAccessToken: this function allows the developer to request for an authentication token using an oAuth verifier obtained from Facebook further to a successful authentication. This function is also part of the "log-in-through-Facebook" scenario
  • callApi: this is a generic function that enables the developer to invoke any Facebook API (Graph API, Open Graph API or FQL request) from within an Apstrata server-side script
  • getApiCall: this is a generic function that returns the url/formEncodedParams needed to invoke any Facebook API (Graph API, Open Graph API or FQL request)

The social.fb.XXX objects

Though very flexible and efficient, the "apsd.social.facebook" object is a generic wrapper of Facebook's APIs, i.e. it requires from the developer to have some understanding of the Facebook APIs names and parameters, and it does not implement any process from end to end, such as for example the "log-in-through-Facebook" process. Therefore, in order to facilitate the manipulation of Facebook's most used APIs, we have implemented complementary objects that tackle this manipulation. These objects are implemented as Apstrata server-side scripts and need to be downloaded by the developers and deployed into their Apstrata application accounts, where they become available to all their server-side scripts.
The objects currently available are the following:

  • social.fb.facebookManager: implements the invocation of some of the most used Facebook API's such as: posting to a timeline, publishing actions, requesting authentication, getting user data, searching for friends or searching for places.
  • social.fb.userManager: uses the preceding object and is responsible for managing the connection between Facebook users and Apstrata application users, i.e. make sure that a user who logs in through Facebook is also identified as a user of the application built on Apstrata and as such, is subject to the authorizations and constraints specified by the developer in his Apstrata application.
  • social.fb.common: this is a utility object that notably contains the configuration parameters required to "connect" the Apstrata application of the developer to his Facebook application.

The social.api.fb.XXX APIs

The functions exposed by "social.fb.XXX" objects defined in the preceding paragraphs can only be invoked from within Apstrata server-side scripts implemented by the developers, i.e. from the back-end tier of their application. Since these functions might also be needed from the application front-end, we exposed them through REST APIs. These APIs are also implemented as Apstrata server-side scripts and need to be downloaded by the developers and deployed into their Apstrata application accounts, where they become accessible to their front-end.
The APIs currently available are the following:

  • social.api.facebookLogin: handles all the login process through Facebook
  • social.api.fb.getUserData: returns data retrieved from the user's profile
  • social.api.fb.getUserFriends: returns the list of the user's friends on Facebook (paginated)
  • social.api.fb.searchUserFriends: allows to search for a user's friends on Facebook
  • social.api.fb.searchPlaces: search for places on Facebook
  • social.api.fb.checkPermissions: get the permissions that are granted by a user to an application

How to use the scripts

Deploy the scripts on your Apstrata application account, either using the Apstrata workbench (create new scripts then paste the content of the below scripts), or by uploading the scripts using the SaveScript API. Note that you should remove the "js" extension from the name of the scripts when they are deployed on your Apstrata application account.

If you need to leverage Facebook's services from a front-end application, you should invoke the API scripts, i.e. the scripts starting with "social.api.fb", from your application. Note that you still needs the other scripts to be deployed but you should not invoke them directly from your app.

If you need to leverage Facebook's service from an Apstrata server-side script that implements the back-end of your application, you can directly invoke the functions exposed by the "social.fb.facebookManager" script.

Available APIs and scripts

  File Modified
JavaScript File social.api.facebookLogin.js This scripts allows you to log in to your app through your Facebook credentials. Jun 19, 2014 by karim saikali
JavaScript File social.api.fb.checkPermissions.js This script allows you to verify what are the permissions that the current user has granted to a Facebook application. Sep 25, 2013 by karim saikali
JavaScript File social.api.fb.getUserData.js This script allows you to retrive the data of the user making the request to the script Jun 26, 2013 by karim saikali
JavaScript File social.api.fb.getUserFriends.js This script allows you to retrieve the friends of the user who is invoking the script Aug 06, 2013 by karim saikali
JavaScript File social.api.fb.searchPlaces.js Use this script to search for places on Facebook Jul 02, 2013 by karim saikali
JavaScript File social.api.fb.searchUserFriends.js This script allows you to search for users on Facebook Jul 02, 2013 by karim saikali
JavaScript File social.fb.common.js Sep 25, 2013 by karim saikali
JavaScript File social.fb.facebookManager.js This script manages the integration with Facebook. Use it from other server-side scripts Sep 25, 2013 by karim saikali
JavaScript File social.fb.userManager.js This script manages the users of your application. You generally won't need to modify it Jul 25, 2014 by karim saikali

When uploading these script to your Apstrata application account, do not forget:

  • to remove the "js" extension
  • to update the "social.fb.common" script (that contains configuration properties) to match your environment.

2. Log in to your Apstrata application through Facebook  

Pre-requisite: you need to create a Facebook application.

 Users management in Apstrata (reminder)

When you register to Apstrata through the Apstrata web site, you get an Apstrata application account. This account entitles you to use all Apstrata's APIs. It also provides you with an Apstrata store (a repository where you can persist data), as well as a user directory. You can create users for your Apstrata application in this directory, using the Apstrata Identity management API and notably "SaveUser". The credentials used to authenticate your users are the username and password passed to the "SaveUser" API.

Apstrata provides you with simple yet powerful mechanisms to grant permissions to the users of your Apstrata application on the data that is persisted in your store, as well as on the server-side scripts you might deploy in your Apstrata application account.

Users who are known by your Apstrata application account, i.e. part of your user directory, can sign-in to your Apstrata application using the username and password used when invoking "SaveUser".

The purpose of the following paragraphs is to explain the different ways of signing-in to your Apstrata application using Facebook credentials.There are two main advantages in signing-in through Facebook:

  1. First advantage is that you can trust Facebook to authenticate a user, even if he is not known by your Apstrata application account. Such users grant your Facebook application permissions to act on their Facebook account (depending on the permissions you requested). Note though that since the user is not known by your Apstrata account, you cannot grant him any permission on the data and scripts of your Apstrata account.
     
  2. Second advantage is to avoid making your users explicitly register to your Apstrata application. Instead, you can authenticate them using their Facebook credentials and use their Facebook profile information to automatically register them as users of your Apstrata account. In that case, you will be able to grant permissions to these users on your Apstrata resources (data and scripts). Of course, you will also be able to act on the Facebook account of these users.

If you are only interested in the first advantage, check paragraphs 2.1. and 2.2. If you are more interested in the second advantage, check paragraphs 2.1 and 2.3.

2.1. The Facebook oAuth login process

Apstrata uses the oAuth login process provided by Facebook, which works as follows:

  • Step 1: first, ask for a oAuth code by passing your app credentials and a callback url. As a result, you get an authentication URL to the facebook login page.
  • Step 2: Invoke the authentication URL to log in. Once you log in, Facebook invokes your callback URL passing it the oAuth code
  • Step 3: Exchange your oAuth code for an access token
  • Step 4: Use the access token to do stuff on the user's facebook account

2.2. Log in through Facebook using Apstrata's social networking APIs

 Using Apstrata's social networking APIs, this is how the process can be executed:

  1. invoke apsdb.social.getRequestToken() from a server-side script to implement step 1 above
  2. invoke the authorization URL received and log in, Facebook then redirects to the callback URL (step 2) providing you with the oAuth code
  3. invoke apsdb.social.getAccessToken() from a server-side script using the oAuth code to implement step 3 above

2.3. Log in through Facebook using the "social.api.facebookLogin" script

2.3.1. From a web application

If your need to log in to a web application through Facebook credentials, invoke the "social.api.facebookLogin" script from your application. This will trigger the whole authentication process, create a user into your Apstrata application account (if not already there), and return of of the following:

Returned values

 Upon success, if no redirection requested and if no return of the Apstrata token is requested

{
 "status": "success",
 "accessToken": the_access_token_sent_by_facebook,
 "login": the Apstrata login of the user
 "hashedPwd": the Apstrata hashed password of the user
}

Upon success, if no redirection requested but returning an Apstrata token is requested

{
 "status" : "success",
 "login": the Apstrata login of the user
 "apsdb.authToken": "some_token",
 "apsdb.tokenExpires": "time_in_seconds",
 "apsdb.tokenLifetime": "time_in_seconds"
}

Input Parameters

  • accessToken(optional): if set, will check the (Facebook) token against Facebook. If valid, will verify if a user currently exists for that token. If so, the script updates the token with the one that might have been returned by Facebook and returns the user login and hashed password. If the user did not exist, the script creates him, and returns the above.
  • redirectAfterLogin (optional): if true, make the script to redirect upon success to the URL specified by "loggedInRedirectUrl" if provided,
  • loggedInRedirectUrl (optional): the URL where to redirect (if requested) further to successfully obtaining an access token from Facebook. If not specified, the script refers to the URL specified in "social.fb.common"
  • returnApstrataToken (optional): if sent and set to true, will make the API return an Apstrata token (and not a login + hashed password, which is safer if you are invoking social.api.facebookLogin from the client-side)

2.3.2. From a mobile application (or if your need to control the authentication process)

If your are not developing a web application or if you want to control the process, you can execute step 1 and step 3 of paragraph 2.1. separately, by invoking "social.api.facebookLogin" and respectively passing "command=getRequesToken" or "command=getAccessToken" as parameters of the request.

Input Parameters (when command=getRequestToken)

  • callbackUrl (optional): the URL that will be called back by Facebook after the user logs in using the Facebook authentication form. If not provided, the script uses the url defined in "social.fb.common"

Make sure that the "callbackUrl" is part of the domain or sub-domain of your Facebook application ! Check the "App domains" field of your application settings on Facebook.


  • loggedInRedirectUrl (optional): the URL where to redirect (if requested) further to successfully obtaining an access token. If provided you do not need to set "redirectAfterLogin" to "true"

  • redirectAfterLogin (optional): if true, redirects to the "loggedInRedirectUrl" if provided or to the default redirection URL specified in "social.fb.common"

Returned values

 {
  status : "success",
  authorizationUrl : URL_sent_by_facebook
 }

Parameters (when command=getAccessToken)

  • code: the oAuth verifier sent by facebook upon redirection to the "callbackUrl" (see command=getRequestToken)

  • callbackUrl (optional): : the URL that will be called back by Facebook after the user logs in (see command=getRequestToken). If not provided, will use the url defined in "social.fb.common"
Note: this has to be the same URL as the one provided when invoking "getRequestToken"

  • loggedInRedirectUrl (optional): the URL where to redirect (if requested) further to successfully obtaining an access token

  • redirectAfterLogin (optional): if true, redirect either to the "loggedInRedirectUrl" if provided, if not, will use the one defined in "social.fb.common"

  • returnApstrataToken: if sent and set to true, will make the API return the Apstrata token

Returned values

Check returned values in paragraph 2.3.1

2.3.3. Examples

For mobile apps developers

If you are using the mobile SDKs (Android or iOS) provided by Facebook, just invoke "social.api.facebookLogin" and pass it the authentication token received using the SDK ("accessToken=the_facebook_access_token"), then use the login and hashed password to sign your calls to Apstrata using the corresponding Apstrata SDK (iOS or Android). Check the example in paragraph 2.3.3.1.

(for example, using the Apstrata iOS SDK, create an instance of the "ApstrataiPhoneClient" class using "-(id) initWithURL:(NSString*)_baseUrl key:(NSString *)_key secret:(NSString*)_secret authMode:(AuthMode) _authMode", where "secret" is the hashed password of the user.

2.3.3.1. Example for iOS - Authenticate through Facebook and automatically create a user in your Apstrata account

First:

  • Download and add the Facebook iOS SDK to your iOS application.
  • Download the Apstrata iOS client and add it to your iOS application. This client allows you to invoke Apstrata's APIs from a native Objective C object that takes care of issuing and signing the HTTP calls to the Apstrata APIs.

In your iOS application, implement the logic needed to trigger the Facebook login process, as explained in the corresponding tutorial. Basically, this is what you need to do:

FBSession *session = [[FBSession alloc] init];
  • Open a session using your session object and associate it to a session handler (the "sessionStateChanged" method you need to implement)
[FBSession openActiveSessionWithReadPermissions:nil
                 allowLoginUI:YES
                 completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
                             [self sessionStateChanged:session
                                                 state:state
                                                 error:error];
                 }
];
 About Facebook login with the FB iOS SDK

The FB SDK offers many ways to login to Facebook. As an alternative to the above code, you could for example use the below. Please check all the possibilities on the Facebook site.

(BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUIemailRequired:(BOOL)email {
	NSArray *permissions;
	if (email) {
		
		 // The below list of permissions is an example.
		 // Only ask for the permissions you need.
		 permissions = [NSArrayarrayWithObjects:
					@"publish_stream",
					@"read_stream",
					@"user_photos",
					@"user_videos",
					@"user_status",
					@"offline_access",
					@"publish_checkins",
					@"manage_pages",
					@"read_insights",
					@"user_likes",
					@"user_birthday",
					@"user_website",
					@"email",
					nil];
	}
	else {
		permissions = [NSArrayarrayWithObjects:
					@"publish_stream",
					@"read_stream",
					@"user_photos",
					@"user_videos",
					@"user_status",
					@"offline_access",
					@"publish_checkins",
					@"manage_pages",
					@"read_insights",
					@"user_likes",
					@"user_birthday",
					@"user_website",
					nil];
	}
	
return [FBSessionopenActiveSessionWithPermissions:permissions
allowLoginUI:allowLoginUI
completionHandler:
			
			^(FBSession *session, FBSessionState state, NSError *error) {
				[selfsessionStateChanged:sessionstate:stateerror:error];
			}];    
}



Implement the sessionStateChanged handler. This is where you will use Apstrata

(void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state  error:(NSError *)error
{
    switch (state) {
        case FBSessionStateOpen: {
            
			// Create an instance of the Apstrata iOS client using your Apsrtata Authentication key and secret
			NSString *url = @"https://sandbox.apstrata.com/apsdb/rest";
        	NSString *authKey = @"Your_auth_key_goes_here";
      		NSString *secret = @"Your_secret_goes_here";
	        ApstrataiPhoneClient *client = [[ApstrataiPhoneClient alloc] initWithURL: url key: authKey secret: secret authMode: SIMPLE];

			// Retrieve the Facebook access token from the session parameter, the token is a property of FBSession
			NSString *token = session.accessToken;

			/* Using the token, invoke the social.api.facebookLogin script on your Apstrata account */

			// the dictionary that will contain the parameters of the call
			NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
			
			// this will be kept empty as we do not need to attach files in this example
			NSDictionary *files = [[NSMutableDictionary alloc] init]; 
			
			// this specifies the API that we need to invoke on Apstrata
			NSString* methodName = @"RunScript";

			// The RunScript API expects the name of the script to run
			[parameters setObject: @"social.api.facebookLogin" forKey: @"apsdb.scriptName"]; 

			// We pass the Facebook token as a parameter of the call 
			[parameters setObject: token forKey: @"accessToken"]; 
			
			// Invoke the RunScript API in order to trigger "social.api.facebookLogin". 
			// The result is returned in JSON format (as string)
			// Check paragraph 2.3.1, "Returned values", first code block to get the returned structure
			NSString *result = [client callAPIJson: (NSString *)methodName params:parameters files: files];

			// If everything went fine, the preceding call should have automatically created a new user in your Apstrata account 
			//(or updated an existing user) based on the profile of the Facebook user matching 
			// the token sent to social.api.facebookLogin. 
			// The returned JSON structure now contains the login and hashed password of that user.

			// ... implement some additional logic
			break;
        }
        case FBSessionStateClosed:
        case FBSessionStateClosedLoginFailed: {
            // Handle the logged out scenario

            // Close the active session            
            [FBSession.activeSession closeAndClearTokenInformation];
         
            break;
        }
        default:
            break;
    }

    if (error) {
        // Handle authentication errors
    }    
}

What we have done so far is:

  • Authenticate using Facebook credential. We got back a Facebook access token
  • We use the access token to create a new user in our Apstrata application account. We got back the username and hashed password of this user.

Starting from there, you now can use the user's username and hashed password to authenticate him against resources in your Apstrata application account:

NSString *url = @"https://sandbox.apstrata.com/apsdb/rest";
NSString *authKey = @"Your_auth_key_goes_here";
NSString *user = @"The_user_username_goes_here"; 
NSString *secret = @"The_user_hashed_password_goes_here";
ApstrataiPhoneClient *client = [[ApstrataiPhoneClient alloc] initWithURL: url key: authKey user: user secret: secret authMode: SIMPLE];

2.3.3.1. Example for HTML/JavaScript - Authenticate through Facebook and automatically create a user in your Apstrata account

Let us create a very simple example. First we implement a simple login page that contains a "Login with Facebook" button. When clicked, the button triggers a call to a function that invokes the "social.api.facebookLogin" API with some parameter:

<html>
    <head>
        <title>Login with Facebook sample</title>
        <script>
            function facebookLogin() {
                
				// Specify the Apstrata endpoint
                var apstrataEndPoint = "https://sandbox.apstrata.com/apsdb/rest/";

				// Specify the authentication key of your Apstrata account 
				// (below is an example please use your own key)
                var authKey = "B037C6F303";

				// Specify the name of the Apstrata Facebook API to invoke
                var scriptName = "social.api.facebookLogin";

				// In this example, we need to be redirected to a welcome page once logged in
				// We set the below to true
                var redirectAfterLogin = true;

				// Specify the URL where to be redirected once logged in 
				// (please change to your own URL - cannot be localhost)
                var loggedInRedirectUrl = "http://www.some-site.com/welcome.html";
                
				// Build the URL to the Apstrata REST RunScript API that will be
				// used to trigger "social.api.facebookLogin"
				var url = apstrataEndPoint + authKey + "/RunScript?apsws.time=1375367198116&apsws.responseType=jsoncdp&apsws.authMode=simple&apsdb.scriptName=" + scriptName;

				// Append the optional redirectionAfterLogin parameter and corresponding value
                url = url + "&redirectAfterLogin=" + redirectAfterLogin;

				// Append the optional loggedInRedirectUrl parameter and corresponding value
                url = url + "&loggedInRedirectUrl=" + loggedInRedirectUrl;

				// Invoke the Apstrata API
                window.open(url, "_self");
            }
        </script>
    </head>
    <body>
        <form>
            <input type="button" value="Login with Facebook" onclick="facebookLogin()"/>
        </form>
    </body>
</html>

Once you click on the "Login with Facebook" button on the HTML page, you will automatically be redirected to the Facebook authentication page. Enter the credentials of a valid Facebook user and submit. Apstrata automatically redirects you to the URL you specified in the "login.html" page. Before it redirects, Apstrata will chec if the authenticated user exists in your Apstrata account. If not, it will create a new user with some information retrieve from the user's Facebook profile.

Notice in your browser that the redirection URL is augmented with new parameters: "login", that contain the login of the Facebook user and "hashedPwd" that contains his hashed password. You can easily retrieve these values in the resulting page.

http://www.some-site.com/welcome.html?accessToken=CAACPRSl1wZBQBAIkghgW36TbSglk7HLvZCnaqcLvegXosCGcNcdR6dptCamQnSvyV9ctcafgkfDH7g2SxSjvUMY9PHZCsD5jrk3iTNZALQZCZCpM0iWhfaoWvNmCdA164sraZBQB4ecd5Kz5LRHJrmf&login=john.smith&hashedPwd=S610957F81892CV63F67B33DADF8932C#_=_

Since it is not a good idea to pass a password to the client side, you should rather ask for an Apstrata authentication token when invoking the "social.api.facebookLogin" API. Therefore, modify the "login.html" file by simply adding an additional parameter to your request to the Apstrata API, as follows:

<html>
    <head>
        <title>Login with Facebook sample</title>
        <script>
            function facebookLogin() {
                
				// Same as above ...

				var returnApstrataToken = true;
                
				// Build the URL to the Apstrata REST RunScript API that will be
				// used to trigger "social.api.facebookLogin"
				var url = apstrataEndPoint + authKey + "/RunScript?apsws.time=1375367198116&apsws.responseType=jsoncdp&apsws.authMode=simple&apsdb.scriptName=" + scriptName;

				// Append the optional redirectionAfterLogin parameter and corresponding value
                url = url + "&redirectAfterLogin=" + redirectAfterLogin;

				// Append the optional loggedInRedirectUrl parameter and corresponding value
                url = url + "&loggedInRedirectUrl=" + loggedInRedirectUrl;

				// Append the new parameter to the URL				
				url = url + "&returnApstrataToken=" + returnApstrataToken;

				// Invoke the Apstrata API
                window.open(url, "_self");
            }
        </script>
    </head>
    <body>
        <form>
            <input type="button" value="Login with Facebook" onclick="facebookLogin()"/>
        </form>
    </body>
</html>

You can now observe that the redirection URL has been changed to include the "apstrataToken" parameter instead of the hashed password. The URL also contains the lifetime of the current token. The Facebook access token is also not available anymore (still present in the Apstrata profile of your user through)

http://www.some-site.com/welcome.html?apstrataToken=FA9DC8D5G095626BAF6FC3EA7541CF15&expiresAfter=1800&userName=john.smith#_=_

3. Post on the user's wall using your application

Use the "post" method of the social.fb.facebookManager script. You should actually invoke this method from another Apstrata server-side script that accepts HTTP request (include the former into this latter using "apsdb.require(social.fb.facebookManager)" (check the insert at the end of the paragraph for a sample of code to implement such a script)

Input Parameters

Parameters of type object or array should be sent as stringified JSON
  • link (optional): a link on which users can click from the post

Returned value

{ "result": { "id": "the_identifier_of_the_facebook_post"}}

Core logic to implement a server side Post-to-Facebook API
<script>
<scriptACL>
  <execute>authenticated-users</execute>
  <read>nobody</read>
  <write>nobody</write>
</scriptACL>
<code><![CDATA[

/*
 * Use this script to post on the requestor's wall on facebook. 
 * @param facebook post parameter (optional): e.g. "to", "message", etc. 
 * Check the complete list at https://developers.facebook.com/docs/reference/api/post/
 * Note: parameters of type object or array should be sent as stringified JSON
 * @param link (optional): a link on which users can click from the post
 * @param accessToken (optional): the facebook access token of the requestor 
 * @return 
 * if successful, {"result": {"id": "the_facebook_id_of_the_posted_message"}}
 * if failure because the user is not authenticated:
 * {"result": {"status":"failure", "errorCode": "PERMISSION_DENIED", "errorDetail": "some_details"}}
 * if failure because the request is signed with account owner crendentials:
 * {"result": {"status":"failure", "errorCode": "INVALID_USER", "errorDetail": "some_details"}}
 * if failure because of any other reason
 * {"result": {"status":"failure", "errorCode": "some_code", "errorDetail": "some_details"}}
 */
try {
    
    var userManager = apsdb.require("social.fb.userManager");
    var common = apsdb.require("social.fb.common");
    
    // get the login and account key of the user who sent the request, if any
    var currentUserLogin = userManager.getUserLoginFromRequest(apsdb, request);
    var accountKey = userManager.getUserAccountFromRequest(apsdb, request);
    
    // the script should not be called as an account owner
    if (currentUserLogin.indexOf("#") > 1) {
    
        throw {
        
            "errorCode": "INVALID_USER",
            "errorDetail": "You cannot use this API as an account owner"
        }
    }    
    
    // get the data on the user who sent the request, either using his login if available or his access token
    var user = null;
    var accessToken = request.parameters["accessToken"]
    if (currentUserLogin != "anonymous") {
        user = userManager.getUser(apsdb, currentUserLogin);
        accessToken = user.user.accessToken;
    }else {
        user = userManager.findUserFromToken(apsdb, accessToken);
    }

    var postDTO = {};

 	// PUT SOME ADDITIONAL LOGIC HERE

	for (var param in request.parameters) {
        
        if (_isPostParameter(param)) {        
        
            try {    
                postDTO[param] = JSON.parse(request.parameters[param]);
            }catch(exception){
                postDTO[param] = request.parameters[param];
            }
        }
    }

    // PUT SOME ADDITIONAL LOGIC HERE
    
    // post to facebook using Apstrata's APIs
    var facebookManager = apsdb.require("social.fb.facebookManager");
    var response = facebookManager.post(apsdb, user.facebookid, accessToken, postDTO);
    var headers = {"Access-Control-Allow-Origin": "*"};
    apsdb.httpRespond(JSON.stringify(response), 200, headers);
	// Use "apsdb.httpRespond" if you need to invoke this script from cross-domains HTML/JS
	// Otherwise, just replace it with "return response;"
}catch(exception) {

    return {
    
        "status": "failure",
        "errorCode": exception.errorCode ? exception.errorCode: exception,
        "errorDetail": exception.errorDetail ? exception.errorDetail : ""
    }
}

function _isPostParameter(parameter) {

    if (parameter.indexOf("apsdb") > -1 || parameter.indexOf("apsws") > -1) {
        return false;
    }
    
    if (parameter == "accessToken") {
        return false;
    }
    
    return true;
}    
    
]]>
</code>
</script>

4. Publish an action on the user's timeline using your application

Use the "executeAction" method of the social.fb.facebookManager script. You should actually invoke this method from another Apstrata server-side script that accepts HTTP request (include the former into this latter using "apsdb.require(social.fb.facebookManager)"

Input Parameters

  • facebookid: the facebook identifier of the targeted user
  • accessToken: the access token to the facebook account of the user
  • actionDTO: the parameters of the action, i.e. { "actionType": the_name_of_the_action_type, "objectType": the_name_of_the_object_type, "objectRef": the_url_to_the_object_need_by_the_action }

Returned value

 { "result": { "id": "the_identifier_of_the_facebook_action_execution"}}

Sample code to implement a Publish-action-to-Facebook API
/*
 * Note that to be able to use the below you have to create action and object types
 * in your Facebook application account. You also need to configure them appropriately
 * @param actionType: the name of the targeted facebook action type
 * @param objectType: the name of the facebook object type that is associated to the action type
 * @param accessToken (optional): the access token received from facebook for the current user
 */
try {
    
    var userManager = apsdb.require("social.fb.userManager");
    var common = apsdb.require("social.fb.common");
    
    // get the login and account key of the user who sent the request, if any
    var currentUserLogin = userManager.getUserLoginFromRequest(apsdb, request);
    var accountKey = userManager.getUserAccountFromRequest(apsdb, request);
    
    // the script should not be called as an account owner
    if (currentUserLogin.indexOf("#") > 1) {
    
        throw {
        
            "errorCode": "INVALID_USER",
            "errorDetail": "You cannot use this API as an account owner"
        }
    }    
    
    // get the data on the user who sent the request, either using his login if available or his access token
    var user = null;
    var accessToken = request.parameters["accessToken"]
    if (currentUserLogin != "anonymous") {
        user = userManager.getUser(apsdb, currentUserLogin);
        accessToken = user.user.accessToken;
    }else {
        user = userManager.findUserFromToken(apsdb, accessToken);
    }
    
	// PUT SOME LOGIC HERE 

    var actionDTO = {};
    for (var param in request.parameters) {
        
        if (_isPostParameter(param)) {        
        
            try {    
                actionDTO[param] = JSON.parse(request.parameters[param]);
            }catch(exception){
                actionDTO[param] = request.parameters[param];
            }
        }
    }
    
    // PUT SOME LOGIC HERE

    // Uncomment the below if you need a link (URL) to a resource
    /* var objectRef = common.apstrataUrl + accountKey + "/RunScript?apsws.time=" + new Date().getTime() + "&apsws.responseType=jsoncdp&apsdb.scriptName=your_link_goes_here
    actionDTO.objectRef = objectRef;
    */
	
	// Make sure the below is enabled in your Facebook application
    actionDTO["fb:explicitly_shared"]="true";    
    
    // post action to facebook using Apstrata's APIs
    var facebookManager = apsdb.require("social.fb.facebookManager");
    var response = facebookManager.executeAction(apsdb, user.facebookid, accessToken, actionDTO);
    var headers = {"Access-Control-Allow-Origin": "*"};
    apsdb.httpRespond(JSON.stringify(response), 200, headers);
	// Use "apsdb.httpRespond" if you need to invoke this script from cross-domain HTML/JS
	// Otherwise, just replace it with "return response;"
}catch(exception) {

    return {
    
        "status": "failure",
        "errorCode": exception.errorCode ? exception.errorCode: exception,
        "errorDetail": exception.errorDetail ? exception.errorDetail : ""
    }
}

function _isPostParameter(parameter) {

    if (parameter.indexOf("apsdb") > -1 || parameter.indexOf("apsws") > -1) {
        return false;
    }
    
    if (parameter == "accessToken") {
        return false;
    }
    
    return true;
}    
    
]]>
</code>
</script>

5. Search for friends

Use the "social.api.fb.searchUserFriends" script and invoke it from your client application.

Input parameters

  • name: some name (it contains the name of the targeted friend)

Returned values

"result": {
 "friends": [
      {
         "uid": some_uid,
        "name": "the_friends_name",
        "pic_small": "url_to_the_profile_pic",
        "profile_url": "url_to_the_profile"
      }
    ]
 }

6. Search for places

Input parameter

  • q (mandatory): a Facebook search query (you can limit it to the name of the place, for example if you type "starbuck" it will search for places with that name. If you type "star" it searches for places that have a name starting with "star") 
  •  center (mandatory): longitude,latitude (e.g. 34.8752806,36.5818626)
  • distance: the distance in meters around the center where to narrow the search (e.g. 100) 

Returned values

 result":{"data":[{"name":"page_name","location":{"street":"some_address","city":"city_name","state":"state_name","country":"country_name", etc.},"id":"place_id_on_fb", "picture": {"data": {"url": "link_to_pic", ...}, ...},  etc.]}


Note that at the minimum, the data contains the following fields: name, location, id, picture
  • No labels