facebook application

14
Integrate App with Facebook (Integrate app with Facebook using Facebook API’s) Kamal Sharma

Upload: kamal-sharma

Post on 17-May-2015

3.631 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: Facebook Application

Integrate App with Facebook

(Integrate app with Facebook using Facebook API’s)

Kamal Sharma

Page 2: Facebook Application

Kamal Sharma

Requirement

• PHP 5

• Web Hosting running PHP (Facebook not providing that you to store your application

server. They just provide IFrame

Using facebook API in PHP. Download the PHP SDK provide by facebook

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

Register your application in Facebook

• Open http://developers.facebook.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)

Facebook not providing that you to store your application

which call URL and display pages in IFrame)

Download the PHP SDK provide by facebook

Register your application in Facebook and obtain Key

cebook.com/. Go to My Apps section

Fill your desired app name. Click Create App button

Description about your application

16x16 pixel Icon for application (Optional)

Page 2

Facebook not providing that you to store your application files on Facebook

Page 3: Facebook Application

Kamal Sharma

• Site URL - Provide your website address

• Canvas Page - if your application

provide directory name like http://www.mysite.com/my

contain source file of your application.

• Click Save Changes

Application details are now registered with Facebook. Facebook Provide

Some important function details about Facebook PHP

Provide your website address

application is in root directory of your web hosting, leave this field blank otherwise

http://www.mysite.com/my-first-app . Where my-first

contain source file of your application.

now registered with Facebook. Facebook Provide App ID and API Key

function details about Facebook PHP Class file

Page 3

leave this field blank otherwise

first-app is folder which

App ID and API Key for using in SDK.

Page 4: Facebook Application

Kamal Sharma

• public function getSession()

Session object. This function looks

• public function getUser()

Return the UID from session

• public function getLoginUrl($params=array())

Generate URL for login and display Facebook login page with HTTPS.

custom permission such as

� email – request user email address

� publish_stream – publish on user wall.

By default Facebook not provide this option. You need

where permission box will appear with your custom permission when user signing the application

Full list of custom permissions are available in Facebook website:

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

• public function getLogoutUrl()

Generate logout URL if user is logged in

• public function api(‘/me’)

If you have an authenticated user

You can get user object which contain properties of user profile information such as

Full list of properties which contain in

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

This function looks for session that already exists. Return details in

public function getLoginUrl($params=array())

display Facebook login page with HTTPS. You can extend the permission box with

request user email address

publish on user wall. etc.

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

(Default Permission Box)

(Extend Permission Box)

ilable in Facebook website:

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

user is logged in.

authenticated user, get their User Object using Graph API. me is current authenticated user.

You can get user object which contain properties of user profile information such as

Full list of properties which contain in Object:

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

Page 4

. Return details in Array otherwise return 1.

You can extend the permission box with

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.

is current authenticated user.

You can get user object which contain properties of user profile information such as id, name, gender etc.

Page 5: Facebook Application

Kamal Sharma Page 5

Implementing in file

File index.php (default file)

<?php

// include facebook class file

require '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 session

variable 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

}

Page 6: Facebook Application

Kamal Sharma

else

{

?>

<a href="<?php echo $logoutUrl

<img src="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.

not signed the permission box.

<?php

if($user)

{

echo $user ;

}

else

{

echo " You are not connected with app"

}

?>

Folder structure

• Root(www)

� Your-app-name(Folder)

- index.php

- facebook.php

and execute it

You see Connect with Facebook button while

Connect with Facebook button, Facebook show error message because

app is hosted) and URL redirect back to Facebook

$logoutUrl; ?>">

http://static.ak.fbcdn.net/images/fbconnect/logout-

// Check if user Object return otherwise show Not connected with App.

" You are not connected with app" ;

Upload files on server

and execute it with apps.facebook.com/your-app-name/

button while I already logged in, but not signed the permission

Connect with Facebook button, Facebook show error message because Facebook try to open a

and URL redirect back to Facebook in IFrame while Facebook blocked this feature.

Page 6

-

// Check if user Object return otherwise show Not connected with App. Which means user

not signed the permission box. if you try

Facebook try to open a original URL (Where

in IFrame while Facebook blocked this feature.

Page 7: Facebook Application

Kamal Sharma

You cannot use Facebook website in IFrame

www.your-domain.com/your-app this will work.

Solution for displaying permission dialog box

JavaScript top.location method. If user open

redirect the whole browser window with

URL there’s no issue with IFrame.

client_id = App ID

redirect_uri = Facebook App URL

Place this code in body tag in index file.

<script type="application/javascript">

if(window.location == 'http://www.

{

top.location.href = 'https://www.facebook.com/dialog/oauth?client_id=

ID&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

After Allow Request for Permission. Facebook

connected with App. And user Object returns

You cannot use Facebook website in IFrame. If you are using this in your own domain like

this will work.

splaying permission dialog box is, catch the address bar URL from window.location

method. If user open your app in Facebook URL like apps.facebook.com/your

with JavaScript with permission parameters. Otherwise opening from domain

<script type="application/javascript">

www.your-domain.com/your-app-name/')

'https://www.facebook.com/dialog/oauth?client_id=

&redirect_uri=http://apps.facebook.com/YOUR_APP_NAME/index.php&scope=

email,read_stream,publish_stream' ;

execute, it automatically reload with permission dialog with custom parameters

. Facebook logout button will appear, also message removed

user Object returns user’s properties in PHP Array.

Page 7

. If you are using this in your own domain like

from window.location and reload with

apps.facebook.com/your-app-name/

. Otherwise opening from domain

'https://www.facebook.com/dialog/oauth?client_id=APP-

&redirect_uri=http://apps.facebook.com/YOUR_APP_NAME/index.php&scope=

with custom parameters.

removed you are not

Page 8: Facebook Application

Kamal Sharma

Print the Array information with PHP print_r

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'

<?php

if($user)

{

echo "User ID : " . $user['id'

echo "Name : " . $user['name'

echo "Location : " . $user['location'

}

?>

PHP print_r(Array) function for checking what information contain in user Object

with user Object like.

'name']

'id'] ."<br>" ;

'name'] . "<br>" ;

'location']['name'] ;

Page 8

information contain in user Object.

Page 9: Facebook Application

Kamal Sharma

Using Facebook Login in Website

If u want to show the data in your website when user logged in with Facebook, the all coding

necessary. You just need to check with user Object.

if($user)

{

// Display protected data while user logged}

else

{

// Display data while user not logged}

Working with Graph API (connections

Full list of connections name:

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

Getting user’s friend list with call to Graph API

<?php

if($user)

{

$friends = $facebook->api('/me/friends'

echo "<pre>" ;

print_r($friends);

echo "</pre>" ;

}

?>

$friends Object return in PHP Array format

// counting total friends.

echo count($friends['data']);

Using Facebook Login in Website

If u want to show the data in your website when user logged in with Facebook, the all coding

. You just need to check with user Object.

while user logged-in.

Display data while user not logged-in.

connections)

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

with call to Graph API.

'/me/friends') ;

Array format

Page 9

If u want to show the data in your website when user logged in with Facebook, the all coding which describe at top is

Page 10: Facebook Application

Kamal Sharma

Generate JSON data of friend list with PHP foreach Loop which represent key

generates JSON from PHP Array.

if($user)

{

$friends = $facebook->api('/me/friends'

foreach ($friends as $key=>$value

{

$friendList = json_encode

}

echo $friendList ;

}

Post data in user feed using Graph API

if ($session)

{

$uid = $facebook->getUser()

// call publish stream API

$api_call = array

(

'method' => 'users.hasAppPermission'

'uid' => $uid,

'ext_perm' => 'publish_stream'

);

$can_post = $facebook->api($api_call

with PHP foreach Loop which represent key-value pairs

'/me/friends') ;

$value)

json_encode($value) ;

using Graph API

;

'users.hasAppPermission',

'publish_stream'

$api_call);

Page 10

value pairs. json_encode function

Page 11: Facebook Application

Kamal Sharma

// check if user set wall posting permission

if($can_post)

{

// call the Graph API - feed

$facebook->api('/'.$uid.'/feed'

'message' => 'message',

'name' => 'app name',

'description' => 'description'

'picture' => 'logo URL',

'link' => 'application URL'

));

}

Sample Application (Call via AJAX

Sample app that show the friends list.

File – index.php (create the instance and call the AJAX function getFriends

File – friends.php (PHP file that generate friend list in JSON

File – data.js (Ajax call to PHP file that print the friend list in JSON)

index.php

<?php

// Include facebook class file

require 'facebook.php';

// Application instance

$facebook = new Facebook(array(

'appId' => '191265817573897',

'secret' => '7422e8c6841edad43502edbcb1157810'

'cookie' => true,

));

$session = $facebook->getSession

$user = null ;

if ($session)

{

try

{

$uid = $facebook->getUser();

$user = $facebook->api('/me'

}

catch (FacebookApiException $e

{

error_log($e) ;

}

}

// login or logout url will be needed depending on current user state.

if ($user)

set wall posting permission

feed

'/feed', 'post', array(

'description',

'

(Wall Posting Format)

AJAX using JavaScript)

(create the instance and call the AJAX function getFriends

friends.php (PHP file that generate friend list in JSON format

data.js (Ajax call to PHP file that print the friend list in JSON)

(

'7422e8c6841edad43502edbcb1157810',

getSession();

();

'/me');

$e)

// login or logout url will be needed depending on current user state.

Page 11

(create the instance and call the AJAX function getFriends())

format)

data.js (Ajax call to PHP file that print the friend list in JSON)

// login or logout url will be needed depending on current user state.

Page 12: Facebook Application

Kamal Sharma Page 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>

<?php

if($user)

{

echo 'Hello ' . $user['name'] ;

}

?>

<script type="text/javascript">

getFriends() ; // call the JavaScript function

</script>

Page 13: Facebook Application

Kamal Sharma Page 13

</body>

</html>

friends.php

<?php

require '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)

Page 14: Facebook Application

Kamal Sharma

{

// parse JSON data

var data = JSON.parse

var mainDiv = document

for(var i=0; i<data

{

var friendDiv =

// attach css class

friendDiv.className

// display name in Div

friendDiv.innerHTML

// attach this div to main Div

mainDiv.appendChild

}

// finally attach main Div to body

document.body.appendChild

}

}

else

{

// Ajax animate.

}

};

xhr.open("POST", "friends.php"

xhr.setRequestHeader("Content

xhr.send(null) ;

}

Sample website feed system like Facebook

http://www.openclassworld.info/

Source code of Quiz application:

http://www.openclassworld.info/quiz.zip

parse(xhr.responseText) ;

document.createElement('div') ;

data.length; i++)

document.createElement('div') ;

// attach css class

className = 'friendsDiv' ;

// display name in Div

innerHTML = data[i].name ;

// attach this div to main Div

appendChild(friendDiv) ;

// finally attach main Div to body

appendChild(mainDiv) ;

"friends.php", true) ;

"Content-Type", "application/x-www-form-urlencoded"

Final Output

system like Facebook

/quiz.zip

Page 14

urlencoded") ;