Thursday, January 31, 2013

facebook wal post api access post and submit post to facebook

Graph API & IFrame Base Facebook Application Development

FacebookFacebook is one of the top social networking site and its easy to develop facebook application. You can also easily integrate facebook features via facebook connect into your site. But it may happen that you want to develop facebook application that will run within facebook site. If this is the case, then this is the right article for you to start.
In this article I discussed all the basics and techniques you need to develop iframe base facebook application.
You’ll learn from this article:
  1. Setup IFrame Application
  2. Facebook Authentication for Iframe Application
  3. Setting extended permission for more information
  4. How to set links
  5. Form Submission technique and getting Data
  6. JQuery – how to use javascript and javascript library
  7. Graph api using php
  8. Stream Publish (wall post)
  9. Status Update via php api
  10. Status Update via javascript api
  11. Invitation Feature
  12. Iframe Resizing
Before proceeding checkout the demo & Download Code
Demo: http://apps.facebook.com/thinkdiffdemo/ (this application now runs PHP SDK 3.0 base code)
Download Old Code PHP SDK 2.2
PHP SDK 3.0 Base Updated Code

UPDATED Tutorial and Code

If you’re first time developer then read the full post and then the updated post , otherwise skip this post and just go to the updated post.

http://thinkdiff.net/facebook/graph-api-iframe-base-facebook-application-development-php-sdk-3-0/

Recommended Reading
  1. http://thinkdiff.net/facebook/graph-api-javascript-base-facebook-connect-tutorial/
  2. http://thinkdiff.net/facebook/php-sdk-graph-api-base-facebook-connect-tutorial/

1. Setup IFrame Application

First visit http://www.facebook.com/developers and setup your facebook application. Set your project server path in Canvas Callback Url, set a canvas page url name, set render method to IFrame, set iframe size Resizable.
facebook app setup screen 1
Set Connect URL to your project server url also
facebook app setup screen 2
Now click save changes . So you just created a new facebook app.
Now download my code and upload all the files to your server’s project dir.
facebook.php is the php-sdk library. Now update configuration of fbmain.php. Copy paste your application’s appid, api key, secret key in $fbconfig. And also set $fbconfig baseUrl and appBaseUrl .
//facebook application
    $fbconfig['appid' ] = "";
    $fbconfig['api'   ] = "";
    $fbconfig['secret'] = "";

    $fbconfig['baseUrl']    =   ""; //http://thinkdiff.net/demo/newfbconnect1/ifram
    $fbconfig['appBaseUrl'] =   ""; //http://apps.facebook.com/thinkdiffdemo
In the template.php you’ll see I load facebook javascript library. Its mandatory to render xfbml tags in your application and also some facebook tasks via javascript.
<div id="fb-root"></div>
    <script type="text/javascript" src="http://connect.facebook.net/en_US/all.js">
</script>
     <script type="text/javascript">
       FB.init({
         appId  : '<?=$fbconfig['appid']?>',
         status : true, // check login status
         cookie : true, // enable cookies to allow the server to access the session
         xfbml  : true  // parse XFBML
       });
     </script>
So the application setup is complete.

2. Facebook Authentication for Iframe Application

fbmain.php file is used for facebook authentication also. Here look at this part
//Facebook Authentication part
    $session = $facebook->getSession();
    $loginUrl = $facebook->getLoginUrl(
            array(
            'canvas'    => 1,
            'fbconnect' => 0,
            'req_perms' => 'email,publish_stream,status_update,user_birthday,
 user_location,user_work_history'
            )
    );

    $fbme = null;

    if (!$session) {
        echo "<script type='text/javascript'>top.location.href = '$loginUrl';
</script>";
        exit;
    }
    else {
        try {
            $uid      =   $facebook->getUser();
            $fbme     =   $facebook->api('/me');

        } catch (FacebookApiException $e) {
            echo "<script type='text/javascript'>top.location.href = '$loginUrl';
</script>";
            exit;
        }
    }
Look we pass an array of configuration in getLoginUrl().  canvas=1 as our app is iframe app.
If we don’t find a valid session or session key is expired, we redirect user to the facebook login page generated by getLoginUrl() function via javascript code top.location.href.

3. Setting extended permission for more information

You couldn’t get some information until user approve your application via extended permission. So look in our above code we provided these extended permissions
‘req_perms’ => ‘email,publish_stream,status_update,user_birthday, user_location,user_work_history’
Checkout extended permission list from here.

4. How to set links

In my application you’ll see menu links like Home, Invite . If you see the code for template.php you’ll see below codes at the bottom.
<a href="<?=$fbconfig['appBaseUrl']?>" target="_top">Home</a> |
    <a href="<?=$fbconfig['appBaseUrl']?>/index.php?page=invite.php" target="_top">
Invite</a>
The important thing is that you must provide target=”_top” in all links for your iframe app. Otherwise when you’ll click the link the full facebook will load in the iframe.

5. Form Submission technique and getting Data

One of the most important thing is form submission. If your application have any form then you have to provide action url as your application’s callbackurl. Don’t use facebook application url otherwise you’ll not get form data. And also again use target=”_top” within form tag.
<form name="fs" action="http://yoursite.com/yourfbapplication/form.php"
 target="_top" method="POST">
Your Name: <input name="name" value="" />
<input name="submit" type="submit" value="Submit" />
</form>
And after getting data redirect user to the app url.
form.php
if (isset($_REQUEST['submit'])){
    //retrieve form data here
    $name = $_REQUEST['name'];
    //save data to database or do other tasks
}

//now redirect user
header ("Location: http://apps.facebook.com/yourapplicationurl");
exit;

6. JQuery – how to use javascript and javascript library

When we develop fbml canvas base facebook application, we only can use partial and modified javascript named FBJS. But in iframe application development you could easily use normal javascript and any javascript library like jquery.
jquery-menu
Look the menu in my application. To create this menu here I coded.
In template.php I first load the jquery javascript library and ui library.
<link href="
http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
</pre>
Then I call the jquery function after the page fully loaded. And it will find the div named ‘tabs’ and make them a nice tabbed menu.
<script type="text/javascript">
            $(document).ready(function () {
                $("#tabs").tabs();
            });
</script>
And in home.php view file I coded for tab.
<div id="tabs">
    <ul>
        <li><a href="#fragment-1"><span>User Information</span></a></li>
        <li><a href="#fragment-2"><span>FQL Query</span></a></li>
    </ul>
    <div id="fragment-1">
        <img src="http://graph.facebook.com/<?=$uid?>/picture" alt="user photo" />
        <br />
        <div style="height: 400px; overflow: auto">
            <?php d($fbme); ?>
        </div>
    </div>
    <div id="fragment-2">
        <div style="height: 400px; overflow: auto">
        <?php
            echo "FQL QUERY: " . $fql;
            d($fqlResult);
        ?>
        </div>
    </div>
You can also easily use jquery ajax function to do ajax tasks. So its really amazing to use javascript library in your facebook application.

7. Graph api using php

Calling graph api using php sdk its very easy. In my previous article check how to call graph api using php. In fbmain.php you’ll see I called graph api.
$fbme     =   $facebook->api('/me');

8. Stream Publish (wall post)

Its very easy to publish stream via facebook javascript sdk. You’ll see in template.php I loaded facebook javascript library. And you’ll see below code there
    function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
        FB.ui(
        {
            method: 'stream.publish',
            message: '',
            attachment: {
                name: name,
                caption: '',
                description: (description),
                href: hrefLink
            },
            action_links: [
                { text: hrefTitle, href: hrefLink }
            ],
            user_prompt_message: userPrompt
        },
        function(response) {

        });
    }
    function publishStream(){
        streamPublish("Stream Publish", 'Thinkdiff.net is AWESOME. I just learned 
how to develop
 Iframe+Jquery+Ajax base facebook application development. ', 
'Checkout the Tutorial', 'http://wp.me/pr3EW-sv',
 "Demo Facebook Application Tutorial");
    }
In home.php view file you’ll see I just call the publishStream() method to show the stream box.
<div id="fragment-3">
        <a href="#" onclick="publishStream(); return false;">Click Here To Show
 A DEMO Stream Publish Box</a>
    </div>
Visit facebook official library documentation to know more about stream publish.

9. Status Update via JQuery Ajax and php api

In the template.php you’ll see I created a javascript function. This function used jquery ajax functionality to send request to server and load.
    function updateStatus(){
        var status  =   document.getElementById('status').value;

        $.ajax({
            type: "POST",
            url: "<?=$fbconfig['baseUrl']?>/ajax.php",
            data: "status=" + status,
            success: function(msg){
                alert(msg);
            },
            error: function(msg){
                alert(msg);
            }
        });
    }
In the home.php you’ll see I’ve a textarea where user will write something and if click the button it will call updateStatus() javascript function to pass value to server.
<div id="fragment-4">
        <form name="statusUpdate" action="" method="">
            <textarea name="status" id="status" rows="4" cols="50"></textarea>
            <input type="button" onclick="updateStatus(); return false;" 
value="Write Something And Click Me" />
        </form>
    </div>
And in ajax.php you’ll see. Here user’s status will update via facebook api.
<?php
    include_once "fbmain.php";

    if ($fbme){
        //update user's status using graph api
        if (isset($_REQUEST['status'])) {
            try {
                $status       = htmlentities($_REQUEST['status'], ENT_QUOTES);
                $statusUpdate = $facebook->api('/me/feed', 'post', 
array('message'=> $status, 'cb' => ''));
            } catch (FacebookApiException $e) {
                d($e);
            }
            echo "Status Update Successfull. ";
            exit;
        }
    }
?>

10. Status Update via javascript api

In template.php you’ll see a javascript function. Where I used facebook javascript api to update status.
    function updateStatusViaJavascriptAPICalling(){
        var status  =   document.getElementById('status').value;
        FB.api('/me/feed', 'post', { message: status }, function(response) {
            if (!response || response.error) {
                alert('Error occured');
            } else {
                alert('Status updated Successfully');
            }
        });
    }
In home.php you’ll see I call this updateStatusViaJavascriptAPICalling() method to update status.
    <input type="button" onclick="updateStatusViaJavascriptAPICalling(); 
return false;
" value="Update Status via Facebook Javascript Library" />

11. Invitation Feature

Checkout the invite.php code
<?php
     include_once "fbmain.php";
    if (isset($_REQUEST['ids'])){
        echo "Invitation Successfully Sent";
        echo '<pre>';
        print_r($_REQUEST);
        echo '</pre>';
        echo "<b>If you need to save these user ids then save these to database
 <br />then redirect user
 to the apps.facebook.com/yourapp url</b>";
        $string = "<script type='text/javascript'>
top.location.href='{$fbconfig['appBaseUrl']}'; </script>";
        echo "Use the following javascript code to redirect user <br />";
        echo htmlentities($string, ENT_QUOTES);
    }
    else {
?>
<fb:serverFbml style="width: 500px;">
    <script type="text/fbml">
      <fb:fbml>
          <fb:request-form
                    action="<?=$fbconfig['baseUrl']?>/invite.php"
                    target="_top"
                    method="POST"
                    invite="true"
                    type="Demo Application | Thinkdiff.net"
                    content="Checkout this demo application and learn iframe 
base facebook application 
development. <fb:req-choice url='<?=$fbconfig['appBaseUrl']?>' label='Accept' />"
                    >

                    <fb:multi-friend-selector
                    showborder="false"
                    actiontext="Checkout this demo application and learn iframe
 base facebook application d
evelopment">
        </fb:request-form>
      </fb:fbml>
    </script>
  </fb:serverFbml>
<?php } ?>
Read the comments within code. remember if you want the users ids whom a user sent invitation then don’t forget to use callback url not facebook app url. And after getting invited user ids redirect user to the facebook app url.

12. Iframe Resizing

Sometimes you may need to resize your iframe app in runtime. Then use the following code to set iframe size
<script type="text/javascript">
    var obj =   new Object;
    obj.width=900;
    obj.height=1800;
    FB.Canvas.setSize(obj);
</script>
I hope this article has given you a clear view to developing iframe base facebook application. Don’t forget to checkout the demo application and to see the codes.
Reference:
Facebook Official Documentation

No comments:

Post a Comment