Using Facebook Object in Multiple PHP Files - facebook

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";

Related

Facebook application access for the public

Ive created my first facebook app. Basically the canvas/iframe version.
It all seems ok ..except:
I can only access the apps page: (http://apps.facebook.com/hoo_promo/) when im logged in as the administrator user of the app. It should be viewable by everone. Ive submiited it to the appstore...does this matter? is this the issue?
My like-gate doesnt seem to work, even though ive followed several examples. My admin user, who im logged in with, has the page liked, but the code
$signed_request = $facebook->getSignedRequest();
$like_status = $signed_request["page"]["liked"];
for page-like is never set in the signed_request obj.
Any help much appreciated....ive added my current code...maybe this can also help others...
$app_id = "secretblahblahhiddenthis";
$secret = 'secretblahblahhiddenthis';
$canvas_page = "http://www.houseofoak.co.uk/facebook_app/";
$auth_url = "http://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($canvas_page);
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $secret,
'cookie' => true,
));
$signed_request = $facebook->getSignedRequest();
$like_status = $signed_request["page"]["liked"];
$user = $facebook->getUser();
$page = 'unliked';
$loginUrl = $facebook->getLoginUrl(array('scope' => 'user_likes'));
$logoutUrl = $facebook->getLogoutUrl();
if (($user) && ($like_status)){
$page = 'liked';
}
For your problems:
Check to make sure you aren't in sandbox mode. Visit https://developers.facebook.com/apps/YOUR_APP_ID/advanced to check.
What you're trying to do is no longer allowed. Facebook has deprecated most of the methods that make a like gate possible. See Facebook Platform Policies Section IV. Point 1 says "You must not ... gate content behind ... Facebook social channels...."

Getting facebook user access token / PHP SDK 3.1.1

since this article is not answering the question ( How to get user access token? ), I wanted to ask how to get the user access token.
I already have my app access token, easy. I also saw in the latest php sdk Base_facebook class there is an getUserAccesstoken function, but its useless because in the end you only get the app access token.
This is my authentification flow:
user gets into the fanpage app, and at some point, he has to authorize permissions:
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $secret,
'cookie' => true
));
$user = $facebook->getUser();
if($user == 0) {
$login_url = $facebook->getLoginUrl($params = array('scope' => "publish_stream", 'redirect_uri' => "https://www.facebook.com/pages/PAGENAME/PAGE-ID?sk=app_APP-ID0&app_data=af"));
echo ("<script> top.location.href='".$login_url."'</script>");
}
This works, fine, app_data "af" param is set to get back the page inside the fanpage app.
Because I realize, that when I remove the app, and get back to the auth page, the user cookie ($user) is still set and so the user wont be asked for permissions again.
For that reason I wanted to check permissions as well, and therefore I need the user access token
try{
$permissions = $facebook->api("/me/permissions", 'GET', array('access_token' => "$access_token" ));
}
catch (Exception $e) {echo ("<script> top.location.href='".$login_url."'</script>"); }
if( array_key_exists('publish_stream', $permissions['data'][0]) ) {
// Permission is granted!
} else {
echo ("<script> top.location.href='".$login_url."'</script>");
}
So I tried the server side auth example (https://developers.facebook.com/docs/authentication/server-side/), but of course this won't work here as you are not able to read the $_REQUEST from inside the app, so I am gonna stuck here. - How do you guys check for the permission inside an app?
$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 = "https://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.");
}
TIA & cheers,
daniel
See the section of the Facebook Developer Docs about Server-Side authentication: https://developers.facebook.com/docs/authentication/server-side/
Or you can use a hybrid client-server authentication:
http://developers.facebook.com/blog/post/534/

$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.

Simple Iframe based facebook authentication

I wrote a facebook application but authentication is not working properly. Despite of googling several hours it did not solve.
please please write the script which authenticates the user properly and if the user clicks the allow button simply display the text "Welcome" assuming that i have written all basic suff aas..
require 'sdk/src/facebook.php';
$app_id = 'MY APP ID';
$canvas_page = "MY CANVAS URL";
// Create our Application instance (replace this with your appId and secret).
$auth_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page) ."&scope=email,read_stream&installed=1";
$facebook = new Facebook(array(
'appId' => $app_id ,
'secret' => MY APP SECRET,
'cookie' => true,
));
///... your code to solve !
Nobody provides the ultimate solution: Finally I solved it by myself.
what I do is. Facebook sends an "installed=1" parameter with the url when the user allows the application. SO I checked this parameter and redirected again to the application. I m extremely happy on finding extremely nice and efficient solution. Nobody answered me any votable answer.
if(isset($_REQUEST['installed']))
echo("<script>top.href.location='http://apps.facebook/myapp' </script>");
It seems that you are mixing the examples from the documentations and the PHP-SDK, dropping the example from the PHP-SDK should work.
Following the code in this answer:
<?php
require '../src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'XXXXXXX',
'secret' => 'XXXXXXXX',
'cookie' => true,
));
$session = $facebook->getSession();
$loginUrl = $facebook->getLoginUrl();
$me = null;
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
echo "Welcome User: " . $me['name'] . "<br />";
} catch (FacebookApiException $e) {
error_log($e);
}
} else {
echo("<script> top.location.href='" . $loginUrl . "'</script>");
}
?>

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

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.''
));