Friday, May 4, 2012

Photo Sharing on Facebook using Graph API - Javascript Implementation

For quite some time I have been working on the Graph APIs by Facebook, and have so far successfully conquered to integrate them to an app I am working on.

An initial quick read is must whoever wants to use the Graph APIs. Understanding the APIs is important before you start making use of them for your applications.

How to implement Facebook Photo Sharing using Graph API in Javascript?

I am discussing sharing of photos alone in this post. Sharing of photos along with the album will be posted soon.

Register your app on Facebook and get your app credentials.

Step 1: Register your app on Facebook here.
Step 2: When you provide an app name, an App ID and App Secret Key is generated for your app. You are not suppose to disclose your app key and app secret key with any one.
Step 3: You are now required to provide your site domain. For Facebook to act as an OpenID url for your app users, you have to provide you site url as well. For testing/development phase you can provide your app domain as localhost and your site url as http://localhost:80 (or the appropriate server port).

*Even a small discrepancy in the site domain/url will not give proper results on using the Graph APIs. Hence you have to be very careful when providing the app details.

Seek user's permission to authorize the app for sharing your photos on Facebook.

Step 1: In your JSP file, add the following code:

<div id="fb-root"></div>
<script src="https://connect.facebook.net/en_US/all.js" type="text/javascript"></script>
<script>
  $(document).ready(function () {
      FB.init({
      appId      : 'YOUR_APP_ID', // App ID
      channelURL : 'URL_TO_CHANNEL_FILE', //must be in your domain
      status     : true, // check login status
      cookie     : true, // enable cookies to allow the server to access the session
      oauth      : true, // enable OAuth 2.0
      xfbml      : true  // parse XFBML
    });
 });
</script>

Note: The channelURL points to a file that you add to your local directory which helps improve communication speed in some older browsers. Without the channelURL , we are forced to use workarounds such as loading a second copy of the webpage in a hidden iframe to properly load social plugins. The workarounds increase load times and inflate referral traffic from Facebook.

Once you have initialized your Facebook APIs, it is time for the user to know that he can share his photos on Facebook if he permits your app to do so.

Step 2: Write the following Javascript code to know that user->app->facebook authorization status.

FB.getLoginStatus(function (response) {
       
        if(response.status == "unknown")
        {
            //user is not logged into facebook
         }
        else if (response.status == "not_authorized")
        {
            //user has not authorized the app to access his account
        }
        else if (response.status == "connected")
        {
            if (response.authResponse) {
                alert(response.authResponse.accessToken);
                setAccessToken(response.authResponse.accessToken);
            }
        }
    });


If you get the login status as "unknown", it means that no user is logged-in to Facebook on the current browser. So, the user is suppose to log-in.

If you get the login status as "not_authorized", it means that a user is logged in to Facebook on the same browser, but has not authorized the app to share photos. Hence you should prompt the user to a url which will allow your app to share the photos. The url looks like:

https://www.facebook.com/dialog/oauth/authorize?client_id=YOUR_APP_ID&redirect_uri=http%3A%2F%2Fwww%2Esomedomain%2Ecom%2Fdomainpage%2Ejsp&scope=user_photos,read_stream"

If you get the login status as "connected", it means that a user is logged in and has authorized the app for photo sharing. Along with the status "connected" you will receive an access token from Facebook, which will allow the user to post photos to his Facebook account.


Final step to Photo Sharing

Once login/authorization is done and the access token is received, you can go ahead and post your photos using the following Graph API:

<script>

var accessToken = "";

function setAccessToken(at){
   accessToken = at;
}

function sharePhoto( ) {

var imgURL = "http://www.someimageurl.com";
    FB.api('/photos', 'post', {
        message: 'some photo description',
        access_token: accessToken, // response.authResponse.accessToken
        url: imgURL
    }, function (response) {
        if (!response || response.error) {
            alert('Error!' + response.error.message);
        } else {
            alert('Photo Posted');
        }

    });
}

</script>


And your photo is posted on Facebook!

Facebook creates an album called "Your_app_name" Photos. Any photo sharing request from your app posts the photo by default into this album.

If you open your Facebook account, you will not see the photos immediately in your album list. You have to check your albums, approve these photos posted from your app to be shared by your Facebook account, for your friends to view. Any unapproved photo is not visible to public. This is a security check by Facebook, so as to prevent any leakage of private data by the app.

Shoot an email/comment for any queries!

5 comments:

  1. Hey, I just used this method. This is posting photo on my wall but not on my friends wall

    * I have publish_actions permissions
    * I am getting "photo posted" message.. No Error.

    # I cross checked with my friends, they didn't find any new albums on my app name nor any new pic from my app.. Nothing of such kind!!

    ReplyDelete
  2. i am getting same problem i am using from http://www.cutumb.com/
    for photo sharing
    lastly i found it it is posting in album section u need to authorize it. from photo section

    checkout photo in fb. it is uploading..

    ReplyDelete
  3. Hi Tushira,

    Do you have a demo on this?

    I'm trying to figure out this code but I'm new to JS so I don't know what I'm doing wrong.

    Thanks in advance!

    ReplyDelete
  4. Hi Joey,
    The example code in this blog post is a tested code and I use it for my app as well.
    Please refer to https://developers.facebook.com/docs/reference/api/ for a detailed description.

    Thanks!

    ReplyDelete
  5. Hi, Tushira,

    Thanks for your article. In other words, there is no way to have a function to upload a pic and share it to user's friends at one time. Am I correct?

    ReplyDelete