How to get Users Email Id in Facebook application using PHP? - php

I have created a simple Facebook application in PHP, that greets user by there user name,
I also want there Email id, to be displayed. But i am not able to do that. the code that i am using is,
require_once('facebook.php');
require_once('config.php');
$facebook = new Facebook(APIKEY, SECRETKEY);
$user=$facebook->require_login();
echo $user; // displaying the ID
<div style="padding: 10px;" id="greeting">
<fb:if-is-app-user uid="loggedinuser">
<h2>Hi <fb:name firstnameonly="true" uid="loggedinuser" useyou="false"/>! welcome to facebook</h2>
<fb:else>
<h2>Hi <fb:name firstnameonly="true" uid="loggedinuser" useyou="false"/>! welcome to facebook</h2>
</fb:else>
</fb:if-user-has-added-app>
</div>
the Output that i am getting is,
1000002020202020
Hi User! welcome to facebook
I want the Email address to be displayed along with the user name, i searched many code but did not get any solution. and if you any good facebook tutorial site please post the links too..

You can get the Email Address, directly without using the FQL.
// initialize facebook
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET));
$session = $facebook->getSession();
if ($session) {
try {
$fbme = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
else
{
echo "You are NOT Logged in";
}
//getting the login page if not signned in
if (!$fbme) {
$loginUrl = $facebook->getLoginUrl(array('canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'email,user_birthday,publish_stream',
'next' => CANVAS_PAGE,
'cancel_url' => CANVAS_PAGE ));
echo '<fb:redirect url="' . $loginUrl . '" />';
} else {
// $fbme is valid i.e. user can access our app
echo "You can use this App";
}
// getting the profile data
$user_id = $fbme[id];
$name=$fbme['name'];
$first_name=$fbme['first_name'];
$last_name=$fbme['last_name'];
$facebook_url=$fbme['link'];
$location=$fbme['location']['name'];
$bio_info=$fbme['bio'];
$work_array=$fbme['work'];
$education_array=$fbme["education"];
$email=$fbme['email'];
$date_of_birth=$fbme['birthday'];
This code worked for me..and i go all the information needed with the Email ID.
NOTE: User has to allow us to get their Information during the Approval of Application.

You need to ask for extended permissions when the user authorizes your application, so you can have access to the user email.
Here's an example using the new PHP SDK and the Graph API:
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/includes/config.php');
// initialize facebook
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET));
$user = $facebook->getUser();
$session = $facebook->getSession();
// in case we don't have a valid session, we redirect asking for email extended permissions
if ($user == null || $session == null) {
$params = array();
$params["canvas"] = "1";
$params["fbconnect"] = "0";
$params["next"] = CANVAS_URL;
$params["req_perms"] = "email";
$loginUrl = $facebook->getLoginUrl($params);
echo '<fb:redirect url="' . $loginUrl . '"/>';
exit();
}
// get user email via the new graph api, using the fql.query method
$url = "https://api.facebook.com/method/fql.query";
$url .= "?access_token=" . $session['access_token'];
$url .= "&query=SELECT email FROM user WHERE uid={$user}";
$userData = simplexml_load_file($url);
$userEmail = $userData->user->email;
echo 'The user ID is: ' . $user;
echo 'The user name is: <fb:name uid="' . $user . '" />';
echo 'The user email is: ' . $userEmail;

Thanks for all the help. I finally figure out how to do that.
first, I need to get the access token, NOT the user session one, but the one for admin.
So, here is the code:
$url = 'https://graph.facebook.com/oauth/access_token';
$ch = curl_init();
$params = array(
'grant_type'=>'client_credentials',
'client_id'=>$appId,
'client_secret'=>$secret,
);
$opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
// set URL and other appropriate options
curl_setopt_array($ch, $opts);
curl_setopt($ch, CURLOPT_URL, "$url");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
$adminAccessToken = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
And then, I can use the facebook API to get any user who accept the application and the extended permission like that:
$fql = "select name, hometown_location, sex, pic_square, email from user where uid=1000000001";
$param = array(
'method' => 'fql.query',
'query' => $fql,
'access_token' =>$adminAccessToken ,
'callback' => ''
);
$fqlResult2 = $facebook->api($param);
with the access token, i can also post things onto user's wall. :)

Related

Facebook publish_stream code ends up in a loop

I have the following code which works fine as long as in a previous part of the application, the user accepts the applications request to publish_stream.
# The facebook library
require_once("/var/www/facebook-php-sdk-master/src/facebook.php");
# Create facebook object
$config = array();
$config['appId'] = 'appId_here';
$config['secret'] = 'secret_here';
$config['fileUpload'] = false; // optional
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if ($user_id) {
try {
$user_profile = $facebook->api('/me','GET');
#check permissions
$api_call = array(
'method' => 'users.hasAppPermission',
'uid' => $user_id,
'ext_perm' => 'publish_stream'
);
#set to true if true...
$can_offline = $facebook -> api( $api_call );
#is it true?
if( $can_offline ) {
$post = array(
'message' => 'post_a_message'
);
$facebook->api('/' . $_GET["id"] . '/feed', 'POST', $post);
} else {
// can't post message - don't have permission
}
} catch (FacebookApiException $e) {
error_log($e);
exit;
}
} else {
error_log("user not logged in");
exit;
}
To try to resolve this, I attempted to insert the following code into the else statement which currently in the code above only contains the comment // can't post message - don't have permission
The code I tried to insert into that else was this:
$loginUrl = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
header("Location: ".$loginUrl);
That works as long as the user accepts to allow my app to publish_stream. However, if the user does not accept, my app will keep asking the user to accept publish_stream. How do I stop that loop from happening if the user decides not to accept?
As far as i remember, $facebook -> getLoginUrl can take parameter cancel_url, which contains the link, where user should be redirected if he doesn't give your app permissions.
So the code will be something like this
$login_url = $facebook -> getLoginUrl( array(
'scope' => 'publish_stream',
'cancel_url' => YOUR_LINK_HERE
));
Here is the working code : Please check it :
Page name : events.php
You can see $redirect_uri = https://localhost/facebook_page/events.php it is returning back to same page.
<?php
$facebook_appid = "your appid"; // Facebook appplication id
$facebook_secret = "your app secret"; // Facebook secret id
$redirect_uri = "https://localhost/facebook_page/events.php"; // return url to our application after facebook login ## should be SAME as in facebook application
$scope = "publish_stream"; // User permission for facebook
$profile_id = "profile_id";// Where do you want to post it(profile id - It is a number)
$code = $_REQUEST["code"]?$_REQUEST["code"]:"";
if(empty($code)) {
$_SESSION['state'] = rand(); // CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id=". $facebook_appid . "&redirect_uri=" . urlencode($redirect_uri) . "&state=". $_SESSION['state'] . "&scope=".$scope;
header("location:".$dialog_url);
}
if($_SESSION['state'] && ($_SESSION['state'] == $_REQUEST['state'])) {
$token_url = "https://graph.facebook.com/oauth/access_token?". "client_id=" . $facebook_appid . "&redirect_uri=" . urlencode($redirect_uri). "&client_secret=" . $facebook_secret . "&code=" . $code;
$response = #file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
}
?>
<!-- Here you can use
message, picture, link, name, caption, description, source, place, tags
as input fields-->
<form enctype="multipart/form-data" method="POST" action="https://graph.facebook.com/<?php echo $profile_id;?>/feed?access_token=<?php echo $access_token; ?>">
<input type="text" name="message" value="test" />
<input type="submit" name="submit" value="Submit" />
</form>
You can post it using jquery also.
I use the following code to check if the user has allowed publishing permisions or not:
$permissions = $facebook->api('me/permissions');
if( array_key_exists('publish_stream', $permissions['data'][0]) ) {
//Continue with posting on users wall
} else {
//Continue without posting on users wall
}

Facebook PHP post to fan page with cronjob?

I am using the following code to post to my facebook fan page and it is working fine. Now I want to use cronjob in order to post to Facebook. I know I have to use as access token but I am not sure how to set it up. I tried to use echo my own access token and the page's access token and use it in the post api but that did not work I got this error:
Uncaught OAuthException: An active access token must be used to query information about the current user.
Here is my code that I tried:
require_once('scripts/facebook.php');
$config = array('appId' => 'xxx','secret' => 'xxx');
$params = array('scope'=>'user_likes,publish_actions,email,offline_access,publish_stream,manage_pages');
$facebook = new Facebook($config);
$user = $facebook->getUser();
if($facebook->getUser()) {
try {
$user_profile = $facebook->api('/me');
$access_token = $facebook->getAccessToken();
//echo "1. ".$access_token;
} catch(FacebookApiException $e) {
$login_url = $facebook->getLoginUrl($params);
error_log($e->getType());
error_log($e->getMessage());
}
} else {
$login_url = $facebook->getLoginUrl($params);
}
$page_id = "xxxxxxxxxxxxx";
$page_access_token = "";
$result = $facebook->api("/me/accounts");
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {
$page_access_token = $page["access_token"];
//echo '<br>';
//echo "2. ".$page_access_token;
break;
}
}
$args = array(
'access_token' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'message' => stripslashes($image_caption).$animaged_gif,
'name' => stripslashes($image_caption).$animaged_gif,
'link' => "http://www.example.com/images.php?i=".$image_name,
'picture' => "http://www.example.com/thumbnails/".$image_name.".png",
'actions' => array(
'name' => 'See Pic',
'link' => "http://www.example.com/images.php?i=".$image_name
)
);
$post = $facebook->api("/$page_id/feed","post",$args);
As you can see that I tried to use the actual access token that I got when I echo out my own access token. But that did not work. I also used the page's access token, but that also did not work. Can you please tell what I am missing here or what is the proper way to do this ?
After some further search I did, I came across setAccessToken and $page_info = $fb->api("/".$sInfo['pageId']."?fields=access_token"); but there is very limited resources on how to use them. I am not even sure if those will be appropriate to this problem. All I need to know is which access token I need to use and what is the appropriate code to set it up ?
This is how you can do it :
Get a short lived accesstoken.
Extend it.
Get a long lived page accesstoken. (Doesn't matter, here we are going to fetch new accesstoken every time. Less complicated, and reliable.)
Thought I would go with an algo, instead I am adding all the possible codes and documentations since this may help someone else too.
Getting short lived access token and extending it:
fetchtoken.php
<?php
//read more : https://developers.facebook.com/docs/howtos/login/server-side-login/
session_start();
$app_id = "xxxxxxxxxxxxxx";
$app_secret = "xxxxxxxxxxxxxxxx";
$my_url = "www.stackoverflow.com/"; // redirect url
$code = $_REQUEST["code"];
if(empty($code)) {
// Redirect to Login Dialog
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); // CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'] . "&scope=publish_stream,read_friendlists,email";
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_SESSION['state'] && ($_SESSION['state'] === $_REQUEST['state'])) {
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$longtoken=$params['access_token'];
//save it to database
}
?>
So you now have a long lived accesstoken ready in your database, a text file or whatever.
cronjob.php
<?
require_once('scripts/facebook.php');
// Pull access token from the file/db
$access_token = "access token from file or db";
$facebook->setAccessToken($access_token); // sets our access token as the access token when we call something using the SDK, which we are going to do now.
$config = array('appId' => 'xxx','secret' => 'xxx');
$params = array('scope'=>'user_likes,publish_actions,email,publish_stream,manage_pages');
$facebook = new Facebook($config);
$user = $facebook->getUser();
if($facebook->getUser()) {
try {
$user_profile = $facebook->api('/me');
} catch(FacebookApiException $e) {
$login_url = $facebook->getLoginUrl($params);
error_log($e->getType());
error_log($e->getMessage());
}
}
else {
$login_url = $facebook->getLoginUrl($params);
}
$page_id = "xxxxxxxxxxxxx";
$page_access_token = "";
$result = $facebook->api("/me/accounts");
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {
$page_access_token = $page["access_token"];
//echo '<br>';
//echo "2. ".$page_access_token;
break;
}
}
$args = array(
'access_token' => $page_access_token,
'message' => stripslashes($image_caption).$animaged_gif,
'name' => stripslashes($image_caption).$animaged_gif,
'link' => "http://www.example.com/images.php?i=".$image_name,
'picture' => "http://www.example.com/thumbnails/".$image_name.".png",
'actions' => array(
'name' => 'See Pic',
'link' => "http://www.example.com/images.php?i=".$image_name
)
);
$post = $facebook->api("/$page_id/feed","post",$args);
?>
Make sure you don't grab access_token(user access token / $access_token) again in the script.
Also, the access_token in $args which is the page access token should be inserted by the $page_access_token variable, and not manually.
Having offline_access in the scope does nothing than showing them on the permission dialogue box that their data can be accessed any time which can be done without that notification anyway.
This should work as long as you visit the fetch.php once at the start, and once every 60 days manually.
Let me know.
This should probably fix it.
offline_access is deprecated. It is now being replaced by a system where you get an extended expiry access_token.
When you run it manually, You generate a live access token, which is invalid after 1-2 hours after you acutally run it. And there is no way you can generate another access_token with a cron. Generating access token should be done manually.
So to fix it, have a read : https://developers.facebook.com/roadmap/offline-access-removal/
and implement this : https://developers.facebook.com/docs/howtos/login/server-side-login/
And save the Access token to your database. When you run the cron, get the token from your database.
P.S : The access_token is valid for 60 days, and it should be extended again and can be done by the user logging in manually. The access_token generally "may" not change but just gets the expiry extended.
ADD :
Scheduling Posts :
You can also schedule the post for upto 6 months too. Just read about it and thought I would point out.
Read : https://developers.facebook.com/docs/reference/api/page/ scroll down to Posts Create sections
You can scrap the entire overhead of the Facebook API and follow this extremely simple approach.
Check what your page-specific email address is in the "Mobile" section of your page settings (https://www.facebook.com/pages/edit/?id=INSERT_YOUR_PAGE_ID_HERE&sk=mobile) and then use it here:
<?php
mail("thatEmailAddress#facebook.com", "New Status Update!", "");
?>
The body is empty because Facebook says "to update your status, write in the email subject line and leave the email body blank."
You can take a look here https://github.com/newbacknew/owloo.com. This is a base of scripts from owloo.com for get data from Facebook via the "ADS" Dashboard, also have to retrive analytics data from Twitter and Instagram.
With the base script you can get trends, interests, behavior, demographic, ages, gender qty of every country, city, stage, fanpage from facebook
The base of all script are in the WSERVICE folder of the backups folders.

Create Auto-POST by Facebook-SDK

I want to enable Facebook Auto Post in my website.
first I created an app, then follow the facebook docs I used the facebook-sdk for PHP, I inserted APP-ID and APP-SECRET, create LOGIN-URL and... to my script (everything like the facebook docs), but I still have problem!!
The problem is:
for first time when user visit my page, he see the login link. when he click on it he will redirect to facebook dialog page for allowing app activities. after this, when facebook redirect user to my canvas page, he see the login link again!! (It seems the getUser() function not worked correctly in my script!).
base on facebook guides the user must see the user profile details... but still the login link is visible.
how can I fix this problem...?
<?php
require_once("libs/facebook.php");
$config = array(
'appId' => 'XXXX',
'secret' => 'XXXX'
);
$fbConnect = new Facebook($config);
$user_id = $fbConnect->getUser();
if($user_id)
{
try {
$userProfile = $fbConnect->api('/me', 'GET');
echo "Name: " . $userProfile['name'];
} catch (FacebookApiException $e) {
$loginUrl = $fbConnect->getLoginUrl();
echo "<a href='" . $loginUrl . "'>LOGIN 2</a>";
}
}
else
{
$loginUrl = $fbConnect->getLoginUrl(array( 'scope' => 'publish_stream' ));
echo "<a href='" . $loginUrl . "'>LOGIN 1</a>";
}
?>
User always see "LOGIN 1"! it means the $user_id is always null (before and after app allowing activities)!! after app allowing (when user for first time click on loginUrl link) I have 'stat' and 'code' in my url query string! but still "LOGIN 1" is visible!
I guess you want to publish a message like "Hey guys, I am now using Aref's superawsome Facebook app now", right?
This can be accomplished with the following lines :
<?php
require_once("/FBAPI/src/facebook.php");
$config = array();
$config['appId'] = 'your_app_id';
$config['secret'] = 'your_app_secret';
$facebook = new Facebook($config);
$user = $facebook->getUser();
if(!$user){
$loginUrl = $facebook->getLoginUrl(array('scope'=>'publish_stream', 'redirect_uri'=>'http://www.example.com'));
}
if($user){
try{
$user_profile = $facebook->api('/me');
$access_token = $facebook->getAccessToken();
$vars = array(
'caption' => 'Aref\'s Facebook Application',
'message' => 'Hey guys, I am now using Aref\'s superawsome Facebook App :D',
'name' => 'Test',
'link' => 'http://www.example.com',
'description' => 'Aref\'s Facebook Canvas App',
'picture' => 'http://fbrell.com/f8.jpg'
);
$result = $facebook->api('/me/feed', 'post', $vars);
if($result){
echo "Post was set";
}
else{
echo "Error!";
}
}
catch(FacebookApiException $e){
error_log($e);
$user = NULL;
}
}
else{
echo '<img src="img/login.png"/>';
}
?>

How to check user like the facebook Application or not?

How can we check user liked the facebook application or not?
I am trying to create a Facebook app, in it there are two different pages , if user liked then page_1 will be show, otherwise page_2 show.
<?php
$user = $facebook->getUser();
if ($user) {
try{
$user_profile = $facebook->api('/me');
$likeID = $facebook->api(array( 'method' => 'fql.query',
'query' => 'SELECT url FROM url_like WHERE user_id = "'.$user_profile['id'].'" AND url="myurl/"'; ));
}
catch(FacebookApiException $e) { }
}
if(count($likeID)>0) echo "User likes this page";
else echo "User doesn\'t like this page";
?>
credible and/or official sources:
http://www.zuberi.me/2011/how-to-check-if-user-liked-the-application-or-page.html
http://www.chilipepperdesign.com/2011/02/15/reveal-fan-gate-like-gate-facebook-iframe-tab-tutorial-with-php
How to check if a user likes my Facebook Page or URL using Facebook's API
Facebook how to check if user has liked page and show content?
Facebook Check if user "Liked" the page
A better approach to the problem can be:
// to generate user access token after the user is logged in
$USER_ACCESS_TOKEN = $facebook->getExtendedAccessToken();
$isFan = curl("https://api.facebook.com/method/pages.isFan?format=json&access_token=" . $USER_ACCESS_TOKEN . "&page_id=" . $FACEBOOK_PAGE_ID);
function curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
require 'facebook.php';
$app_id = "your app id";
$app_secret = "your app secret";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true,
));
$signed_request = $facebook->getSignedRequest();
$like_status = $signed_request["app"]["liked"];
if ($like_status == 1){
echo 'User likes this page';
}
else{
echo 'User doesn\'t like this page';
}
Maybe you should try somethng like this, check Facebook's PHP SDK reference page for the exact approach.

authenticating facebook canvas application returns ?code=

i have a problem with my facebook canvas app that is currently on development i'm working on http://localhost:8080
my canvas url is http://localhost:8080/fbcanvas/
on facebook the url is set to http://apps.facebook.com/app_name/
the problem is i'm getting a code as an $_GET['code'] variable after a user approves my app.
in facebook documentation it doesnt say anything about getting a $_GET['code'] it just says getting signed_request
this is the code i'm using from facebook examples.
require_once($_SERVER['DOCUMENT_ROOT'] . '/classes/Page.php');
require($_SERVER['DOCUMENT_ROOT'] . '/core/config.fb.php');
$canvas_page = 'http://apps.facebook.com/khawamusic/';
$auth_url = 'https://www.facebook.com/dialog/oauth?client_id=' . $app_id . '&redirect_uri=' . urlencode($canvas_page);
$signed_request = $_REQUEST['signed_request'];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if(empty($data['user_id'])) {
echo('<script> top.location.href="' . $auth_url .'";</script>');
} else {
$page = new Page;
$styles = array('reset.css', 'fbcanvas.css');
$scripts = array(
'https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js',
'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js',
'http://connect.facebook.net/en_US/all.js#xfbml=1',
'/sources/js/fbcanvas.js'
);
$page->set_title('Khawa');
$page->set_styles($styles);
$page->set_scripts($scripts);
$page->start_page();
require($_SERVER['DOCUMENT_ROOT'] . '/fbcanvas/fb.tpl');
$page->end_page();
}
so what happens is a user approves my app then he gets redirected to http://apps.facebook.com/khawamusic/?code=blabla
i'm cnfused because in the documentation it doesn't say i'm suppose to get a $_GET['code']
If the user presses Allow, your app is authorized. The OAuth Dialog will redirect (via HTTP 302) the user's browser to the URL you passed in the redirect_uri parameter with an authorization code:
http://YOUR_URL?code=A_CODE_GENERATED_BY_SERVER
With this code in hand, you can proceed to the next step, app authentication, to gain the access token you need to make API calls.
Refer: https://developers.facebook.com/docs/authentication/
EDIT:
Here's a sample of the authentication, this won't show ?code=Blabla..
First download the latest Facebook PHP SDK from here: https://github.com/facebook/php-sdk/tree/master/src
Make sure you save all 3 files, facebook.php, base_facebook.php and fb_ca_chain_bundle.crt
Now replace the text "YOUR_APP_ID" and ""YOUR_APP_API_SECRET" with your Application ID and App Secret from facebook, I've added sample wall posting using graph api, if you don't want, you can remove it, if you go through my codes and comments, you'll understand what it does and you don't want to do anything to get access token, just use $access_token variable and it'll give you the access_token of the current user and if you want the user's ID then use $user variable, if you want user's basic information, use $userInfo variable and it'll fetch user's data using graph api and returns all information in an array, you'll get the current user's info like id,name,first_name,last_name,link,hometown,location,bio,work,education,gender,timezone.etc.
Change $RedirectUrl with your landing page URL or your canvas page url
<?php
require 'facebook.php';
define('FACEBOOK_APP_ID', "YOUR_APP_ID"); // Your App ID
define('FACEBOOK_SECRET', "YOUR_APP_API_SECRET"); // Your App API Secret
$RedirectUrl = "http://apps.facebook.com/myapp/"; // Your Landing Page URL, User's will be redirect to this URL after they allow your app.
function d($d){
echo "<pre>";
print_r($d);
echo "</pre>";
}
$user = null;
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
'cookie' => true,
));
$user = $facebook->getUser(); // Get the UID of the connected user, or 0 if the Facebook user is not connected.
if(isset($_GET['code'])){
header("Location: $RedirectUrl");
}
if($user == 0) {
// If User is not connected to your app, then redirect User to Authentication Page.
/**
* Get a Login URL for use with redirects. By default, full page redirect is
* assumed. If you are using the generated URL with a window.open() call in
* JavaScript, you can pass in display=popup as part of the $params.
*
* The parameters:
* - redirect_uri: the url to go to after a successful login
* - scope: comma separated list of requested extended perms
*/
$login_url = $facebook->getLoginUrl($params = array('scope' => "publish_stream", 'redirect_uri' => $RedirectUrl));
echo("<script> top.location.href='" . $login_url . "'</script>");
} else {
// If User is connected to your app, then do something.
$signed_request = $facebook->getSignedRequest(); // Get the data from a signed_request token.
$access_token = $facebook->getAccessToken(); // Determines the access token that should be used for API calls.
$userInfo = $facebook->api("/me"); // Get's User Info
try {
// Posts to user's wall after the user allows your app.
$wallpost = array(
'message' => "I like this",
'link' => 'http://google.com',
'picture' => 'http://i.imgur.com/8iz6L.png',
'name' => 'This is cool',
'description'=> 'Checkout this cool app'
);
$publishStream = $facebook->api("/$user/feed", "post", $wallpost); // WallPost to User's Wall using Graph API
echo "Your post was successfully posted to UID: $user";
}
catch (FacebookApiException $e) {
d($e);
}
}
?>
i'm not yet sure but i think i have the answer to the process of authorizing / authenticating a facebook app...
step 1 : the first time a user access your app facebook sends you a signed request and you need to parse it validate it and check if the $data['user_id'] is set.
the code:
$data = $canvas->parse_signed_request($signed_request);
$auth_url = 'http://www.facebook.com/dialog/oauth?client_id=' . $app_id . '&redirect_uri=' . urlencode($canvas_page);
if(empty($data['user_id'])) {
echo '<script>top.location.href="' . $auth_url . '"</script>';
}
so if the $data['user_id'] is empty go authenticate.
step 2: the user authorizes your app facebook sends you a signed request and a code
if(isset($_REQUEST['code'])) {
$access_token = $canvas->get_access_token($_REQUEST['code']);
$user = $canvas->getUser($access_token);
$user_info = array(
'user_id' => $user->id,
'user_username' => $user->username,
'user_name' => $user->name
);
// install the application for the new user.
$user_obj = new User($user_info);
// registered or allready exists.
if($user_obj) {
echo '<script>top.location.href="' . $canvas->canvas_page . '";</script>';
}
exit();
}
so from what i understood facebook sends you $_REQUEST['code'] just one time: when the user approves your canvas application.
that's it the user is installed so now every time a user re enters your application you will get a signed_request
but this time because the user already approves the application the signed request will include an user_id and oauth_token with it u can get stuff from the graph api.
IF THE SIGNED_REQUEST HAVE A USER_ID THIS IS WHAT U DO.
if(isset($data['user_id'])) {
$user = false;
if(!$user) {
$user = $canvas->getUser($data['oauth_token']);
}
if(!ob_start('ob_gzhandler')) ob_start();
$styles = array(
'reset.css', 'jplayer.fbcanvas.css', 'fbcanvas.css'
);
$scripts = array(
'http://connect.facebook.net/en_US/all.js#xfbml=1',
'http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js',
'/sources/js/jplayer/jquery.transform.js',
'/sources/js/jplayer/jquery.grab.js',
'/sources/js/jplayer/jquery.jplayer.js',
'/sources/js/jplayer/mod.csstransforms.min.js',
'/sources/js/jplayer/circle.player.js',
'/sources/js/fbcanvas.js'
);
$results = $canvas->getLatestSongs();
// the canvas.
$page->set_title('Khawa');
$page->set_styles($styles);
$page->set_scripts($scripts);
$page->start_page();
require($_SERVER['DOCUMENT_ROOT'] . '/fbcanvas/fb.tpl');
$page->end_page();
ob_end_flush();
}
again i'm not sure but i think this is the process of authentication for FACEBOOK CANVAS APPS.

Categories