User ID / Owner Fan Page ID (Facebook Fan Page Application) - facebook

I am developing a facebook fan page application witch includes a form.
I have trouble retrieving the following information after the form is been sent:
User ID of user who filled in the form
User ID/Mail of the owner from the fan page

//i think this will help you
<?php session_start();?>
<?php require 'src/facebook.php';
$app_id = "your_app_id";
$app_secret = "your_secret_key";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret
));
$canvas_page = "https://www.facebook.com/page_name/app_appid"; //this is you facebook app url
$auth_url = "http://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 {
echo $data["user_id"];
$_SESSION['fbuser']=$data["user_id"];
}

I think you can use a FQL using the FB PHP SDK
example:
$pages = $facebook->api(array(
'method' => 'fql.query',
'query' => 'SELECT page_id FROM page_admin WHERE uid = '.$uid.''
));

Related

$_SESSION['fb_id'] lost while redirecting to a subdomain uri, after a facebook connect

I have several subdomains websites, and I wish to be facebook connected on each.
I've created my fb app for the main domain, and it works for it.
In each subdomains I use this link to connect (wrote by an ajax calling) :
<?php
echo "<a href=\"https://graph.facebook.com/oauth/authorize?type=user_agent&client_id=myID
&scope=email,publish_stream,status_update&redirect_uri=http://www.mydomain.com/fbConnect.php?ref=".$_SERVER['HTTP_REFERER']."\">
Connect with Facebook
</a>";
?>
My fbConnect.php
<?php
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"'); // Hack IE for POST params...
header("Cache-Control: no-cache");
header("Pragma: no-cache");
session_set_cookie_params(0, '/', '.mydomain.com', false); // If session is lost with subdomains...
session_start();
require('/home/....../facebook.php');
$facebook = new Facebook(array(
'appId' => 'myid',// changed for the example
'secret' => 'mysecret', // same
'cookie' => true,
));
$user = null;
$loginUrl=$facebook->getLoginUrl(
array(
'canvas' => 0,
'scope' => 'email,publish_stream,user_location'
)
);
$logoutUrl = $facebook->getLogoutUrl();
$user=$facebook->getUser();
if(!$user) echo "<script>top.location.href='".$login_url."'</script>";
if ($user) {
echo "Ok";
$user_profile = $facebook->api('/me');
$userInfo = $facebook->api("/$user");
$_SESSION['fb_id']=$userInfo['id'];
// Some stuff...
echo "<script type='text/javascript'>top.location.href = '".$_GET['ref']."';</script>";
}
?>
Scopes, connections and redirections are working, but I can't get back the $_SESSION['fb_id'] in the $_GET['ref'] page... however the session_id() is the same !
Finaly, there was some mistakes :
1. Sessions
They didn't followed in subdomains, so the trick was to change the php.ini or add ini_set("session.cookie_domain", ".myDomain.com"); (thanks #Tommy Crush)
2. redirect_uri
It seems that, in my case, it was not possible to send vars inside the redirect_uri=http://www.myDomain.com?var1=123&var2=456...
3. API use
I had to read the new beginner panel of the GRAPH API, and I was surprised by the number of changes...
I finaly used the following :
In each subdomains
// Simple link to the connection page
echo "Connect with FB";
// Record the current page whitch called this ajax
$_SESSION['connexion_ref']=$_SERVER['HTTP_REFERER'];
My new fbConnect.php
ini_set("session.cookie_domain", ".myDomain.com");
session_start();
$app_id = "myappid";
$app_secret = "myappsecret";
$my_url = "http://www.mydomain.com/fbConnect.php";
$code = $_REQUEST["code"];
if(empty($code)) {
$_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=email,publish_stream,status_update,offline_access";
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);
$_SESSION['access_token'] = $params['access_token'];
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
//var_dump($user);
$_SESSION['id_fb']=$user->id;
// Some stuff
// Then redirect to the subdomain page of connection
echo "<script type=\"text/javascript\">top.location.href =\"".$_SESSION['connexion_ref']."\";</script>";
}
Now it works like a charm.

Facebook fql not showing the photos and albums query

I am using php-sdk for showing facebook information of the user. I have successfully shown the user profile info but while fetching any album or photos I am getting the blank data to me. I read the photos requires access_token.
Also if I put this query in the facebook graph api explorer it showing me the perfect result. So query is right may be my way of passing the url is wrong.
I am not getting the issue.
Please help.
';
$app_secret = '';
$my_url = '';
$config = array(
'appId' => '<appid>',
'secret' => '<appsecrete>',
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
$code = $_REQUEST["code"];
if($user_id) {
//auth user
if(empty($code)) {
$dialog_url = 'https://www.facebook.com/dialog/oauth?client_id='
. $app_id . '&redirect_uri=' . urlencode($my_url) ;
echo("<script>top.location.href='" . $dialog_url . "'</script>");
}
//get user access_token
$token_url = 'https://graph.facebook.com/oauth/access_token?client_id='
. $app_id . '&redirect_uri=' . urlencode($my_url)
. '&client_secret=' . $app_secret
. '&code=' . $code;
$access_token = file_get_contents($token_url);
$fql_query_url = 'https://graph.facebook.com/'.'fql?q=SELECT+pid,src_small+FROM+photo+WHERE+aid+IN+(SELECT+aid+FROM+album+WHERE+owner=+me())&'.$access_token;
$fql_query_result = file_get_contents($fql_query_url);
$fql_query_obj = json_decode($fql_query_result, true);
//display results of fql query
echo '<pre>';
print_r("query results:");
print_r($fql_query_obj);
echo '</pre>';
}
?>
One parameter needs to be add for $dialog_url variable which is 'scope' which defines permissions to be given for application
$dialog_url = 'https://www.facebook.com/dialog/oauth/?client_id='.$app_id.'&redirect_uri='.urlencode($my_url).'&scope=user_photos';
echo("<script>top.location.href='" . $dialog_url . "'</script>");
for reference,
http://developers.facebook.com/docs/reference/dialogs/oauth/
Thanks
Shreyas

getUser() return 0 on the first page load

When a user is connected with Facebook and came on my page getUser() return 0.
I use this code:
include 'includes/php/facebook.php';
$app_id = "APP_ID";
$app_secret = "SECRET_KEY";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
$user = $facebook->getUser();
if($user){
try {
$user_profile = $facebook->api('/me');
}catch(FacebookApiException $e) {
error_log($e);
}
}
When the page is loaded completely the FB.Event return "connected".
FB.Event.subscribe('auth.login', function(response) {
FB.api('/me', function(response) {
window.location.reload();
});
});
And then the page loaded twice. After this the User is connected with my page.
Is that correct, the page must loaded twice ? I think this is not user friendly. Knows someone another possibility ?
Why getUser() return 0 on the first page load ?
EDIT 2:
When I use the example from the Server-Side Authentication. And the User ist connected with Facebook, i get the user-details.
<?php
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$my_url = "YOUR_URL";
session_start();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'];
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_REQUEST['state'] == $_SESSION['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);
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
echo("Hello " . $user->name);
}
else {
echo("The state does not match. You may be a victim of CSRF.");
}
?>
When the user is not connected with Facebook, I get the dialog before i came back to my page. Can i also query the connection to facebook without the dialog ? Or can i on an other way genereate the CSRF ?
I'm not sure if you just did not post the code with which you authenticate the user, or you just don't do that part..
It's not enough to construct a Facebook object, you need to authenticate the user with facebook.
Have you read the authentication documentation?
There are two types of flows you can take, the Server-Side and Client-Side, from your code it seems like you need to use the server side flow in order to have an access token for the user on the php side, then the call for the getUser method should return the user object you want.
If I'm mistaken and you are authenticating the user, then please edit your question and add the code you use for that.

Using Facebook Object in Multiple PHP Files

I am creating a Facebook Application containing multiple PHP pages. If I reinstantiate Facebook objects in all the files I get an Error Invalid OAuth access token signature.
I have tried a number of alternatives, also the $facebook->getSession() function doesn't work in the new framework and is deprecated.
So I tried to keep the access token in the session and use the same access token in my next PHP file's Facebook object.
On my first page i Have instantiated my App using:
$app_id = "107684706025330";
$app_secret = "__SECRET__";
$my_url = "http://www.sentimentalcalligraphy.in/wp-content/then_n_now/";
$config = array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true,
);
session_start();
$facebook = new Facebook($config);
$access_token = $facebook->getAccessToken();
echo $access_token;
$_SESSION['fob'] = $access_token;
On the next PHP file were I need to use the Facebook object for the second time:
$config = array(
'appId' => '107684706025330',
'secret' => '__SECRET__',
);
$facebook = new Facebook($config);
$access_tocken = $_SESSION['fob'];
echo $access_token;
$facebook->setAccessToken($access_token);
I still get an error that the access token is not valid. How am I supposed to use this. I need to use the following code in my second PHP file:
$friends = $facebook->api('/me/friends','GET');
Thanking you in Advance,
Nasir
I have a some code for Facebook API. I want to share with you.
// App user account and password
$app_id = 'blabla';
$app_secret = 'blabla';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
// Get User ID
$user = $facebook->getUser();
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
$access_token = $facebook->getAccessToken();
if(isset($_GET["code"])){
// Get our app user feed
$user_profile_feed = $facebook->api('/me');
// Insert user id into users table while user login our app
// We have to control user who inserted our users table after before
$query_is_user = mysql_query("SELECT * FROM `users` WHERE `user_id` = ".$user_profile_feed['id']) or die("hata 1");
$count = mysql_num_rows($query_is_user);
if($count == 0) {
mysql_query("INSERT INTO `users`(`user_id`) VALUES (".$user_profile_feed['id'].")") or die("hata 2");
echo '<script language=Javascript>alert("Uygulamamiza Basariyla Giris Yaptiniz...");</script>';
}
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . "http://apps.facebook.com/machine_learning/"
. "&client_secret=" . $app_secret . "&code=" . $_GET["code"];
$response = #file_get_contents($token_url);
$params = null;
parse_str($response, $params);
mysql_query("UPDATE users SET access_token='$params[access_token]' WHERE user_id='$user_profile_feed[id]'") or die("hata 4");
}
$url = "https://graph.facebook.com/oauth/authorize?"
."client_id=262609310449368&"
."redirect_uri=http://apps.facebook.com/machine_learning/&scope=read_stream";

$facebook->getSession() in Facebook page iframe app/tab only works when app admin logged in

I am developing some custom iframe/canvas pages (or now known as "apps") for a Facebook business page. For my purposes, I would like to pull the users first and last name that is currently logged in (and currently likes the page) and output it on the page. This script works just fine when I am logged in as the app admin, but when I try login as my personal account or a a couple of my friends account - it seems that $session is null. Why is this happening and how do I fetch a first and last name without having the user go through any additional authentication?
<?php
require_once '../db/connect.php';
require_once '../../lib/facebook.php';
$signed_request = $_REQUEST["signed_request"];
$secret = "***********************************";
$facebook = new Facebook(array(
'appId' => '**************',
'secret' => $secret,
'cookie' => true
));
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
echo "\$session is not null!";
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
echo $me['name'];
?>
Unfortunately, this is not possible (reference):
As with a Canvas Page, you will not
receive all the user information
accessible to your app in the
signed_request until the user
authorizes your app.
So you need the user to authorize your application first, this can be found here:
<?php
$app_id = YOUR_APP_ID;
$canvas_page = YOUR_CANVAS_PAGE_URL;
$auth_url = "http://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 {
echo ("Welcome User: " . $data["user_id"]);
}
?>
After authorizing your application and getting the User ID, the process is trivial I suppose.