Successfully reported this slideshow.
Integrate App with Facebook   (Integrate app with Facebook using Facebook API’s)                    Kamal Sharma
Requirement   •   PHP 5   •   Web Hosting running PHP (Facebook not providing that you to store your application files on ...
•   Site URL - Provide your website address   •   Canvas Page - if your application is in root directory of your web hosti...
•   public function getSession()       Session object. This function looks for session that already exists. Return details...
Implementing in fileFile index.php (default file)<?php// include facebook class filerequire facebook.php;// Call facebook ...
else{?>   <a href="<?php echo $logoutUrl ?>">                       $logoutUrl;      <img src="http://static.ak.fbcdn.net/...
You cannot use Facebook website in IFrame. If you are using this in your own domain like                                  ...
Print the Array information with PHP print_r                                     print_r(Array) function for checking what...
Using Facebook Login in WebsiteIf u want to show the data in your website when user logged in with Facebook, the all codin...
Generate JSON data of friend list with PHP foreach Loop which represent key value pairs json_encode function              ...
// check if user set wall posting permission    if($can_post)    {      // call the Graph API - feed      $facebook->api(/...
{  $logoutUrl = $facebook->getLogoutUrl();}else{  // generate login URL with custom permission in array.  $loginUrl = $fac...
</body></html>friends.php<?phprequire facebook.php;$facebook = new Facebook(array(  appId => YOUR APP ID,  secret => YOUR ...
{                 // parse JSON data                 var data = JSON.parse                                  parse(xhr.resp...
Upcoming SlideShare
Loading in …5
×

Facebook Application

4,010 views

Published on

Published in: Technology, Design
  • Be the first to comment

  • Be the first to like this

Facebook Application

  1. 1. Integrate App with Facebook (Integrate app with Facebook using Facebook API’s) Kamal Sharma
  2. 2. Requirement • PHP 5 • Web Hosting running PHP (Facebook not providing that you to store your application files on Facebook Facebook server. They just provide IFrame which call URL and display pages in IFrame)Using facebook API in PHP. Download the PHP SDK provide by facebookhttps://github.com/facebook/php-sdk/Register your application in Facebook and obtain Key • Open http://developers.facebook.com/ Go to My Apps section cebook.com/. • Click Setup New App button • Fill your desired app name. Click Create App button • Fill Basic Information about app. • Description – Description about your application • Icon – 16x16 pixel Icon for application (Optional) • Logo – Logo image (Optional)Kamal Sharma Page 2
  3. 3. • Site URL - Provide your website address • Canvas Page - if your application is in root directory of your web hosting, leave this field blank otherwise provide directory name like http://www.mysite.com/my http://www.mysite.com/my-first-app . Where my-first first-app is folder which contain source file of your application. • Click Save ChangesApplication details are now registered with Facebook. Facebook Provide App ID and API Key for using in SDK.Some important function details about Facebook PHP Class fileKamal Sharma Page 3
  4. 4. • public function getSession() Session object. This function looks for session that already exists. Return details in Array otherwise return 1. . • public function getUser() Return the UID from session • public function getLoginUrl($params=array()) Generate URL for login and display Facebook login page with HTTPS. You can extend the permission box with custom permission such as email – request user email address publish_stream – publish on user wall. etc. By default Facebook not provide this option. You need to set the permission and pass in your application URL where permission box will appear with your custom permission when user signing the application first time. (Default Permission Box) (Extend Permission Box)Full list of custom permissions are available in Facebook website: ilablehttp://developers.facebook.com/docs/authentication/permissions/ • public function getLogoutUrl() Generate logout URL if user is logged in in. • public function api(‘/me’) If you have an authenticated user get their User Object using Graph API. me is current authenticated user. user, You can get user object which contain properties of user profile information such as id, name, gender etc. Full list of properties which contain in Object: http://developers.facebook.com/docs/reference/api/user/Kamal Sharma Page 4
  5. 5. Implementing in fileFile index.php (default file)<?php// include facebook class filerequire facebook.php;// Call facebook class for starting the application instance$facebook = new Facebook (array ( appId => YOUR APP ID, secret => YOUR SECRET KEY, cookie => true, // if true read cookie));// If session found that means user signed application permission otherwise the sessionvariable hold value 1.$session = $facebook->getSession();// Initialize the user variable with null value. Which store the user properties.$user = null ;// Check if session exist or user already logged in with facebook.if ($session){ try { $uid = $facebook->getUser(); // call Graph API with me (current user) for getting details about user. $user = $facebook->api(/me); } catch (FacebookApiException $e) { error_log($e) ; }}// check if user object return result.// login or logout URL will be needed depending on current user state.if ($user){ $logoutUrl = $facebook->getLogoutUrl();}else{ // generate login URL with custom permission in array. $loginUrl = $facebook->getLoginUrl(array( req_perms => email,status_update,publish_stream,user_photos, ));}// Check if user Object is not null// generate login and logout button.// img URL contain login button and logout button image which provide by Facebook.if(!$user){?> <a href="<?php echo $loginUrl; ?>"> <img src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif"> </a><?php}Kamal Sharma Page 5
  6. 6. else{?> <a href="<?php echo $logoutUrl ?>"> $logoutUrl; <img src="http://static.ak.fbcdn.net/images/fbconnect/logout- http://static.ak.fbcdn.net/images/fbconnect/logout-buttons/logout_small.gif"> </a><?php}?>// Check if user Object return otherwise show Not connected with App. Which means usernot signed the permission box.<?phpif($user){ echo $user ;}else{ echo " You are not connected with app" ;}?> Upload files on serverFolder structure • Root(www) Your-app-name(Folder) - index.php - facebook.php and execute it with apps.facebook.com/your-app-name/You see Connect with Facebook button while I already logged in, but not signed the permission box. if you tryConnect with Facebook button, Facebook show error message because Facebook try to open a original URL (Whereapp is hosted) and URL redirect back to Facebook in IFrame while Facebook blocked this feature.Kamal Sharma Page 6
  7. 7. You cannot use Facebook website in IFrame. If you are using this in your own domain like IFrame.www.your-domain.com/your-app this will work.Solution for displaying permission dialog box is, catch the address bar URL from window.location and reload with splayingJavaScript top.location method. If user open your app in Facebook URL like apps.facebook.com/your apps.facebook.com/your-app-name/redirect the whole browser window with JavaScript with permission parameters. Otherwise opening from domain .URL there’s no issue with IFrame.client_id = App IDredirect_uri = Facebook App URLPlace this code in body tag in index file.<script type="application/javascript">if(window.location == http://www. www.your-domain.com/your-app-name/){ top.location.href = https://www.facebook.com/dialog/oauth?client_id= https://www.facebook.com/dialog/oauth?client_id=APP- ID&redirect_uri=http://apps.facebook.com/YOUR_APP_NAME/index.php&scope= &redirect_uri=http://apps.facebook.com/YOUR_APP_NAME/index.php&scope= email,read_stream,publish_stream ;}</script> Now upload files and execute, it automatically reload with permission dialog with custom parameters parameters.After Allow Request for Permission. Facebook logout button will appear, also message removed you are not .connected with App. And user Object returns user’s properties in PHP Array.Kamal Sharma Page 7
  8. 8. Print the Array information with PHP print_r print_r(Array) function for checking what information contain in user Object Object.if($user){ echo "<pre>" ; print_r($user); echo "</pre>" ;}So you can access user detail with user Object like.Id - $user[id]Name - $user[name]Location - $user[location][name name]<?phpif($user){ echo "User ID : " . $user[id ."<br>" ; id] echo "Name : " . $user[name . "<br>" ; name] echo "Location : " . $user[location location][name] ;}?>Kamal Sharma Page 8
  9. 9. Using Facebook Login in WebsiteIf u want to show the data in your website when user logged in with Facebook, the all coding which describe at top isnecessary. You just need to check with user Object. .if($user){ // Display protected data while user logged logged-in.}else{ // Display data while user not logged logged-in.}Working with Graph API (connections connections)Full list of connections name:http://developers.facebook.com/docs/reference/api/user/Getting user’s friend list with call to Graph API API.<?phpif($user){ $friends = $facebook->api(/me/friends ; /me/friends) echo "<pre>" ; print_r($friends); echo "</pre>" ;}?>$friends Object return in PHP Array format// counting total friends.echo count($friends[data]);Kamal Sharma Page 9
  10. 10. Generate JSON data of friend list with PHP foreach Loop which represent key value pairs json_encode function key-value pairs.generates JSON from PHP Array.if($user){ $friends = $facebook->api(/me/friends ; /me/friends) foreach ($friends as $key=>$value $value) { $friendList = json_encode json_encode($value) ; } echo $friendList ;}Post data in user feed using Graph APIif ($session){ $uid = $facebook->getUser() ; // call publish stream API $api_call = array ( method => users.hasAppPermission users.hasAppPermission, uid => $uid, ext_perm => publish_stream ); $can_post = $facebook->api($api_call $api_call);Kamal Sharma Page 10
  11. 11. // check if user set wall posting permission if($can_post) { // call the Graph API - feed $facebook->api(/.$uid./feed post, array( /feed, message => message, name => app name, description => description description, picture => logo URL, link => application URL ));} (Wall Posting Format)Sample Application (Call via AJAX using JavaScript)Sample app that show the friends list.File – index.php (create the instance and call the AJAX function getFriends getFriends())File – friends.php (PHP file that generate friend list in JSON format format)File – data.js (Ajax call to PHP file that print the friend list in JSON)index.php<?php// Include facebook class filerequire facebook.php;// Application instance$facebook = new Facebook(array( (appId => 191265817573897,secret => 7422e8c6841edad43502edbcb1157810 7422e8c6841edad43502edbcb1157810,cookie => true,));$session = $facebook->getSession getSession();$user = null ;if ($session){ try { $uid = $facebook->getUser(); (); $user = $facebook->api(/me /me); } catch (FacebookApiException $e $e) { error_log($e) ; }}// login or logout url will be needed depending on current user state.if ($user)Kamal Sharma Page 11
  12. 12. { $logoutUrl = $facebook->getLogoutUrl();}else{ // generate login URL with custom permission in array. $loginUrl = $facebook->getLoginUrl(array( req_perms => email,status_update,publish_stream,user_photos,));}?><html> <head> <title>Sample App.</title> <script type="text/javascript" src="data.js"></script> </head> <body><style type="text/css"> .friendsDiv { padding : 1px 7px 1px 7px ; background : #F7F9FB ; border : 1px solid #D8DFEA ; vertical-align : top ; margin : 10px auto ; width : 510px ; color : #333 ; font-family : tahoma ; font-size : 11px ; text-align : left; }</style><script type="application/javascript">if(window.location == http://www.your-domain.com/your-app-name/){ top.location.href = https://www.facebook.com/dialog/oauth?client_id=APP- ID&redirect_uri=http://apps.facebook.com/YOUR_APP_NAME/index.php&scope= email,read_stream,publish_stream ;}</script><?phpif($user){ echo Hello . $user[name] ;}?><script type="text/javascript"> getFriends() ; // call the JavaScript function</script>Kamal Sharma Page 12
  13. 13. </body></html>friends.php<?phprequire facebook.php;$facebook = new Facebook(array( appId => YOUR APP ID, secret => YOUR SECRET KEY, cookie => true,));$session = $facebook->getSession();if($session){ $uid = $facebook->getUser() ; $friends = $facebook->api(/me/friends) ; foreach ($friends as $key=>$value) { $friendList = json_encode($value) ; } echo $friendList ;}else{ echo "Session not found" ;}?>data.js/** * @author KAMAL */function getFriends(){ var xhr; try { xhr = new ActiveXObject(Msxml2.XMLHTTP); } catch (e) { try { xhr = new ActiveXObject(Microsoft.XMLHTTP); } catch (e2) { try { xhr = new XMLHttpRequest(); } catch (e3) { xhr = false; } } } xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status == 200)Kamal Sharma Page 13
  14. 14. { // parse JSON data var data = JSON.parse parse(xhr.responseText) ; var mainDiv = document document.createElement(div) ; for(var i=0; i<data data.length; i++) { var friendDiv = document.createElement(div) ; // attach css class friendDiv.className = friendsDiv ; className // display name in Div friendDiv.innerHTML = data[i].name ; innerHTML // attach this div to main Div appendChild(friendDiv) ; mainDiv.appendChild } // finally attach main Div to body appendChild(mainDiv) ; document.body.appendChild } } else { // Ajax animate. } }; xhr.open("POST", "friends.php" true) ; "friends.php", "Content-Type", "application/x-www-form-urlencoded" ; xhr.setRequestHeader("Content urlencoded") xhr.send(null) ;} Final OutputSample website feed system like Facebookhttp://www.openclassworld.info/Source code of Quiz application:http://www.openclassworld.info/quiz.zip /quiz.zipKamal Sharma Page 14

×