Using OAuth and Graph API’s in FaceBook Canvas Apps

FaceBook OAuth

On a FaceBook Canvas Application project I needed to post messages to a users wall using PHP. Now, you may or may not be aware, but FaceBook has switched to Open Authentication and Graph API’s. There is quote a bit of documentation on the subject and it’s implementation at http://developers.facebook.com/docs/. The only thing missing is direct examples on how to perform these tasks. I searched around a bit and found information on this topic scarce. So, for your viewing pleasure, here are a couple examples on how to use the OAuth and Graph API’s.

Requesting Application Permissions

To request “extended permissions” from a user along with any other capabilities you’d like you app to be granted, you can call the following URL, either directly or through a CURL call.

https://graph.facebook.com/oauth/authorize?client_id=XXXXXXXXXXXXXXX&redirect_uri=http://apps.facebook.com/myapp&scope=publish_stream

You can locate you Client ID in you developer application settings. The “redirect_uri” is obviously where you’d like to redirect when the user makes a decision on your request. The Note the “scope” parameter. This is where you specify a coma delimited list of permissions you’d like you app to request. For a full list of available permissions take a look here:

http://developers.facebook.com/docs/authentication/permissions

Once redirected, some data is passed as URL params about you’re users choice. You can use this in you app to whatever ends you need.

Posting to a User’s Wall

There are two parts to doing this. First you need to get an Access Token before you can actually make the call to post to a user’s wall. Here you can see the call through OAuth to retrieve the token. Again, you’re applications Client ID and Client Secret can be found in your developer application settings. The callFb is just a CURL method wrapper that returns the results of the loaded page. After we get the contents returned, we just extract the actual token.

function callFb($url, $params)
{
    $ch = curl_init();
    curl_setopt_array($ch, array(
        CURLOPT_URL => $url,
        CURLOPT_POSTFIELDS => http_build_query($params),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_VERBOSE => true
    ));

    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

$params=array('client_id'=>'XXXXXXXXXXXXXXX', 'type'=>'client_cred', 'client_secret'=>'XXXXXXXXXXXXXXX');
$url = "https://graph.facebook.com/oauth/access_token";
$access_token = callFb($url, $params);
$access_token = substr($access_token, strpos($access_token, "=")+1, strlen($access_token));

Now that we have our token, we can use callFb again to tap the Graph API and post to the user’s wall.

$message = "Hello World, this is the Graph API.";
$params=array('access_token'=>$access_token, 'message'=>$message, 'link'=>'http://apps.facebook.com/myapp', 'name'=>'Graph API Test App');
$url = "https://graph.facebook.com/PROFILE_ID/feed";
callFb($url, $params);

You can see the message, name, and link being created. Notice the “/me” in the URL. This is a short cut to posting to the currently authenticated user. This can also be replaced with a specific user’s FaceBook ID as well. The next to notice is the “/feed” in the URL. This is the type of posting you’d like to perform. There are a number of other options to choose from and you can find them at the folowing link under “Publishing to Facebook”:

http://developers.facebook.com/docs/api

That’s it! I hope this saves someone from spending hours trying to locate some examples of how to make these common calls in a FaceBook app. If anyone has any further insight on better wasy to perform these task, please leave a comment.


  • http://Website Naresh Kumar

    Hi,

    How can we get ‘client ID’ and ‘client secret’ values? Also please let us know how can we get $access_token value?

    FYI, I have a facebook account and created an application. Is the Client ID is same as “aplication id”?

    Do we need to include any files? If so, please explain. Thanks in advance

    -Naresh Kumar

  • http://www.zen-sign.com Zack

    Hi Naresh,
    Yes, the nomenclature is a little confusing, but you can get the Client ID under the “Facebook Integration” tab as the Application ID. The Client Secret is right under that as the Application Secret.

    To get the Access Token, you need to make the CURL call to “https://graph.facebook.com/oauth/access_token”. There’s the full example above in the first code snippet but it looks like this:

    $params=array(‘client_id’=>’XXXXXXXXXXXXXXX’, ‘type’=>’client_cred’, ‘client_secret’=>’XXXXXXXXXXXXXXX’);
    $url = “https://graph.facebook.com/oauth/access_token”;
    $access_token = callFb($url, $params);
    $access_token = substr($access_token, strpos($access_token, “=”)+1, strlen($access_token));

    This basically returns a token that oauth can use to verify your app and allow you to then post to the user’s wall.

    In this basic example, you don’t need to include any files, but i usually work with the facebook php api, ewhich you can find here:

    http://github.com/facebook/php-sdk

    Thanks for your comments!

  • http://www.zen-sign.com Zack

    Hi Naresh,
    Yes, the nomenclature is a little confusing, but you can get the Client ID under the “Facebook Integration” tab as the Application ID. The Client Secret is right under that as the Application Secret.

    To get the Access Token, you need to make the CURL call to “https://graph.facebook.com/oauth/access_token”. There’s the full example above in the first code snippet but it looks like this:

    $params=array(‘client_id’=>’XXXXXXXXXXXXXXX’, ‘type’=>’client_cred’, ‘client_secret’=>’XXXXXXXXXXXXXXX’);
    $url = “https://graph.facebook.com/oauth/access_token”;
    $access_token = callFb($url, $params);
    $access_token = substr($access_token, strpos($access_token, “=”)+1, strlen($access_token));

    This basically returns a token that oauth can use to verify your app and allow you to then post to the user’s wall.

    In this basic example, you don’t need to include any files, but i usually work with the facebook php api, ewhich you can find here:

    http://github.com/facebook/php-sdk

    Thanks for your comments!

  • Anonymous

    Original Comment from Naresh Kumar

    Hi,

    How can we get ‘client ID’ and ‘client secret’ values? Also please let us know how can we get $access_token value?

    FYI, I have a facebook account and created an application. Is the Client ID is same as “aplication id”?

    Do we need to include any files? If so, please explain. Thanks in advance

    -Naresh Kumar

  • Grbosss

    Thanks a lot. You saved my day!!!!

  • Nareshkumar97

    Hi Zack,

    Thanks for Your quick reply.

    I have created an application and completed “Requesting Application Permissions” part as per your instructions. It has shown similar dialogue box shown in this article and I clicked “Allow” button to give permission. Next, I have created “fb_posting.php” file which contains this code:

    $url,
    CURLOPT_POSTFIELDS => http_build_query($params),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_VERBOSE => true
    ));

    $result = curl_exec($ch);
    echo “Result:”;
    echo “”; print_r($result); echo “”;
    curl_close($ch);
    return $result;
    }

    $params = array(‘client_id’=>’104055546325395′, ‘type’=>’client_cred’, ‘client_secret’=>’87e2094a6d467bd85d9805c6e09505c8′);
    echo “”; print_r($params); echo “”;

    $url = “https://graph.facebook.com/oauth/access_token”;

    echo ” URL:”.$url;
    $access_token = callFb($url, $params);
    echo “Access Token:”.$access_token;

    $access_token = substr($access_token, strpos($access_token, “=”)+1, strlen($access_token));

    echo “Access Token:”.$access_token;

    $message = “Hello World, this is the Graph API.”;

    echo ” Message:”. $message;
    $params=array(‘access_token’=>$access_token, ‘message’=>$message, ‘link’=>’http://apps.facebook.com/zensign_test', ‘name’=>’Graph API Test App’);

    echo “”; print_r($params); echo “”;

    $url = “https://graph.facebook.com/100000759504269/feed”;

    callFb($url, $params);

    ?>

    I am unable to get access_token value and publish messages. Please help.

    You can check this program at http://nareshphp.50gigs.net/apps/fbtest/fb_posting.php

    You can find phpinfo() output here: http://nareshphp.50gigs.net/apps/fbtest/phpinfo.php (To check whether curl is enabled or not)

    Please let me know correction(s) in this. Thanks in advance.

    Regards,
    -Naresh Kumar

  • Anonymous

    Hi Naresh,
    I tried copying your code and pasting it to an app i have set up and I actually received the access token. It’s possible it is a server setting issue, but first, can you try setting the “OAuth 2.0 for Canvas (beta)” to “enabled” under the “advanced” tab of you application settings?

  • http://www.zen-sign.com/creating-a-facebook-check-in-app-using-the-graph-api-places/ Creating a Facebook Check-in app using the Graph API Places | Zen-Sign Interactive

    [...] taking a look at the some analytics for the blog and I noticed that a lot of people are visiting my Using OAuth and Graph API’s in FaceBook Canvas Apps post. This leads me to believe there are a lot of people with Facebook Canvas app questions looking [...]

  • Nareshkumar97

    I have set “OAuth 2.0 for Canvas (beta)” to “enabled” as You instructed, but no luck. Could You please let me know any other thing(s) I need to update? Thanks.0

    -Naresh Kumar

  • Anonymous

    Hey Naresh,
    There is an alternate way to try and retrieve the access token. If you take a look at my latest blog post, i show a “Facebook-approved” way of getting the access token from the “signed request” object available in Canvas apps. You can check it out here: http://www.zen-sign.com/creating-a-facebook-check-in-app-using-the-graph-api-places/. You can also find out more about it in the Facebook docs here: http://developers.facebook.com/docs/authentication/canvas. Hope that helps.

  • Facebook Master

    Nice article
    Help me alot……

  • Nayar

    Thanks a lot buddy. I am 100% php n00b and i managed to make this work :)

  • http://www.facebook.com/people/Karthik-Kottapalli/100000564724233 Karthik Kottapalli

    Thanks for the tutorial. It sure made things easier for me :)

  • Nareshkumar97

    Hi,

    I have to publish messages on facebook page (fan page) dynamically (through cron job on particular day at particular time)

    Here is my plan for this:

    1.First collecting application AppID, Secret, API key and Page ID in one page. Assume that this page is http://mysite.com/facebookadmin.php

    2.Need to ‘allow’ application to post particular page [Here application creator and page owner are same]. So I need to to execute/run “https://graph.facebook.com/oauth/authorize?client_id=XXXXXXXXXXXXXXX&redirect_uri=http://mysite.com/facebookadmin.php&scope=publish_stream, offline_access”. Right? If so, How can I do this using curl?

    3. Also, I have a script which is able to get/display access_token using curl. [I can provide it here, if needed]

    Could You please let me know how to post on particular page dynamically using oauth and graph API? Are page access token(s) are needed for that? If so, how can I get them? Please help.

    Thanks in advance.

    -Naresh Kumar