facebook php-sdk providing same functionality as javascript FB.getLoginStatus - facebook

I am using javascript sdk to know if user is login and connected to our web-site' application by using FB.getLoginStatus() function.
I want to know if php-sdk provides me details about the user logged into facebook.
If user is logged in facebook and connected to our application, i have to make them to directly logged into our site.
How can this be done using php sdk.
Thanks in advance.

You can do the following:
$user_details=$fb->api_client->users_getInfo($fb_user, array('last_name','first_name','pic_square'));
And yes they do have a similar thing to the FB.getLoginStatus() :)
$params = array(
'ok_session' => 'https://www.myapp.com/',
'no_user' => 'https://www.myapp.com/no_user',
'no_session' => 'https://www.myapp.com/no_session',
);
$next_url = $facebook->getLoginStatusUrl($params);
Found it here: https://developers.facebook.com/docs/reference/php/facebook-getLoginStatusUrl/

Just check the Example/Usage at the GitHub-Page:
https://github.com/facebook/facebook-php-sdk

according to documentation ( https://github.com/facebook/facebook-php-sdk ), after doing:
require 'facebook-php-sdk/src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
));
// Get User ID
$user = $facebook->getUser();
To check if the user is still logged in on facebook (kind of FB.getLoginStatus) you need to:
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}

As noted by #DMCS this function should be used:
http://developers.facebook.com/docs/reference/php/facebook-getLoginStatusUrl/
You generate an url: $next_url = $facebook->getLoginStatusUrl();
redirect the user to this url: header('Location: '.$next_url);
the user will be returned by FB with session information (POST) about the login status
the SDK will parse the return $_POST info
use $facebook->getUser(); to get the userid (if logged in)
So far so good. The only problem is, this function (point 4) is broken since the transition to oAuth2.0 by Facebook, see also this bug report:
http://developers.facebook.com/bugs/295348980494364
So please let FB know that you have the same issue by adding a reproduction.
Cheers!

Related

CodeIgniter and Facebook Connect

I am trying to integrate my Codeigniter website with the Facebook PHP SDK. What I want to do is let a user share an article from my site on their facebook wall, if they are logged into a facebook account. My library appears to load correctly, but everytime I try to do something, I get some kind of error... primarily with the auth. getUser does not appear to return the correct results. I set up my facebook application and set the config vars for my library, but no luck. It says I am not logged into facebook. When I click on the "login" anchor, the link takes me to the same page, but with the facebook url, and doesn't ask me to login with the app. Here's my code:
function facebook($article_id){
$config = array(
'appId' => '276870792431073',
'secret' => '8d49eee575413fb9a8063d22f65dbf6a'
);
$this->load->library('facebook', $config);
$user = $this->facebook->getUser();
if($user){
try {
$user_profile = $this->facebook->api('/me');
} catch (FacebookApiException $e){
error_log($e);
$user = null;
}
}
if($user){
$article = $this->article->fetch_article($article_id);
$config = array(
'message' => 'I just read an '.anchor('articles/'.url_title($article['title']).'/'.$article_id, 'article').' on '.anchor('', 'TrackTheOutbreak.com').'!',
);
$this->facebook->api('/me/feed', 'post', $config);
} else {
$data['MESSAGE_TITLE'] = 'Authentication Error';
$data['MESSAGE_TEXT'] = 'You must be logged into an existing Facebook account to use this feature. Click '.anchor($this->facebook->getLoginUrl(), 'here').' to login.';
$this->parser->parse('error_body.tpl', $data);
}
}
In order to access a users information and post anything to their wall you first need to get a access token from them. To do that you need to make sure that you have gained their permission through Facebook's FB_login (and then Open Graph). I would double check with this guide and make sure that you have everything set up properly to post to their timeline.
https://developers.facebook.com/docs/reference/javascript/FB.login/
I hope this helps

I want to get user access token rather than application access token

I want to get user access token because I need to get user's posts and comments.
When I use Graph API Explorer, the access token it generates is correct one and shows me my posts and comments and some other data. But when try to get posts and comments by using this code than it does not return me posts and comments and return some other data only which i don't need.
require_once('facebook.php');
$config = array(
'appId' => '383128895071077',
'secret' => '6a9ab479186f53db5c531a3fa5f91be0',
);
$facebook = new Facebook($config);
$access_token = $facebook->getAccessToken();
$result = $facebook->api('/me/feed/', array('access_token' => $access_token));
I searched all the google and get access token by different ways but I could not get posts and comments of me. I must be doing something wrong and need to sort out this as soon as possible.
Thanks in advance.
You should check this example
Facebook php sdk example
you should check whether we have user access token like this
// Get User ID
$user = $facebook->getUser();
// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
Once we get the user details, you can ensure that user is logged into app and authorized the app.
For feeds
You should have extended permissions read_stream
then you can read the wall feed.

Get photos with graph api

I've read a lot of tutorials/articles/questions here about this, as well as trying to find something useful in the fb documentation.
So far I've made no progress at all myself so any input would be greatly appreciated, I'm simply trying to access a list of my photos but all I get is an empty array.
I know I've added more req_perms than I need probably, I just copied the ones from a "working tutorial" that didnt work for me, and after reading a thread here I also added user_photo_video_tags because that had worked for the thread poster (again, not me).
I've gotten the dialog to allow photos sharing my photos with my app, login works without any problems, the access token I get seem to be correct, after logging in I have visited:
https://graph.facebook.com/me/photos?access_token= and the token, and gotten an empty array, if I wasnt logged in or the access_token wasnt linked to my app there would be some error, but all I get is an empty array.
Thanks in advance for any input.
Thanks to Chaney Blu I was able to validate my permissions:
{
"data": [
{
"installed": 1,
"status_update": 1,
"photo_upload": 1,
"video_upload": 1,
"create_note": 1,
"share_item": 1,
"publish_stream": 1
}
]
}
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once 'library/facebook.php';
$app_id = "xxxxxxxxxxxxxxxx";
$app_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
$loginLink = $facebook->getLoginUrl(array(
'scope' => 'user_status,publish_stream,user_photos,user_photo_video_tags'
));
$logOutLink = $facebook->getLogoutUrl();
$user = $facebook->getUser();
if ($user) {
try {
// User logged in, get token
$token = $facebook->getAccessToken();
//var_dump($token); dumped successfully
// Get public profile info
$user_profile = $facebook->api('/me');
//var_dump($user_profile); dumped successfully
$photos = $facebook->api('/me/photos?access_token=' . $token);
var_dump($photos); // Empty array, BAH!
} catch (FacebookApiException $e) {
$user = null;
}
}
?>
Click here to login if you aren't autoredirected<br /><br /><br />
Click here to logout
Not sure if this is the problem, but try this. It appears you're using the latest PHP SDK. In your getLoginUrl(); calls, try changing 'req_perms' to 'scope'.
Like this:
$loginLink = $facebook->getLoginUrl(array(
'scope' => 'user_status,publish_stream,user_photos,user_photo_video_tags'
));
You can verify that you've authorized the correct permissions by visiting https://graph.facebook.com/me/permissions/?access_token=XXXX
After testing some other permissions I noticed facebook weren't updating the permissions to my token, even when logging out of the app, logging in again and accepting new permissions nothing changed when I looked at the Graph permissions link I got from Chaney Blu.
I used that link to verify the token from facebooks graph api page http://developers.facebook.com/docs/reference/api/ and noticed that token had access to user_photos but not my token.
Going into my facebook settings and removing the app made facebook update my permissions the next time I signed into the app.
Thanks to Chaney Blu for putting me on the right track. Would vote you up if I had the reputation.

How to login with OFFLINE_ACCESS using the new Facebook PHP SDK 3.0.0?

with the old (2.x) SDK I used this to log someone with offline_access:
$session = array
(
'uid' => $userdata['fb_uid'],
'sig' => $userdata['fb_sig'],
'access_token' => $userdata['fb_access_token']
);
$facebook->setSession($session);
In the new SDK this function doesnt exist anymore. I think I need to login using:
setPersistentData($key, $value)
but this function is protected and I dont know what 'code' is? Do I need this to log the user in or not? And what's going on with 'sig'? Don't I need this anymore?
Hope someone already figured this out because the documentation really doesn't help!
With the Facebook PHP SDK v3 (see on github), it is pretty simple. To log someone with the offline_access permission, you ask it when your generate the login URL. Here is how you do that.
Get the offline access token
First you check if the user is logged in or not :
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
// The access token we have is not valid
$user = null;
}
}
If he is not, you generate the "Login with Facebook" URL asking for the offline_access permission :
if (!$user) {
$args['scope'] = 'offline_access';
$loginUrl = $facebook->getLoginUrl($args);
}
And then display the link in your template :
<?php if (!$user): ?>
Login with Facebook
<?php endif ?>
Then you can retrieve the offline access token and store it. To get it, call :
$facebook->getAccessToken()
Use the offline access token
To use the offline access token when the user is not logged in :
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$facebook->setAccessToken("...");
And now you can make API calls for this user :
$user_profile = $facebook->api('/me');
Hope that helps !
With PHP SDK 2.0 (I guess), I just use it like
$data = $facebook->api( '/me', 'GET', array( 'access_token' => $userdata['fb_access_token'] ) );
This should work with the newer one to as it seems to be more of a clean approach than rather setting up sessions by ourself. Can you try?
Quentin's answer is pretty nice but incomplete, I think. It works nice, but I for example getUser() isn't working in that time because userId (which is getUser() returning) is cached.
I have created a new method to clear all caches and save it persistently.
public function setPersistentAccessToken($access_token) {
$this->setAccessToken($access_token);
$this->user = $this->getUserFromAccessToken();
$this->setPersistentData('user_id', $this->user);
$this->setPersistentData('access_token', $access_token);
return $this;
}

Facebook iFrame app - how to fetch Preload FQL result using PHP SDK?

since few years I have an FBML app (a small Flash game) which I'm now trying to convert to an iFrame app. Unfortunately there aren't many docs for Facebook iFrame apps yet.
For my game I need the user's first name, picture, gender and the city.
In my old version I had this preload FQL (created once by a PHP script):
$fql = array('info' => array('pattern' => 'facebook',
'query' => 'SELECT first_name, sex, pic_big, current_location
FROM user WHERE uid={*user*}'));
$fb->api_client->admin_setAppProperties(
array('preload_fql' => json_encode($fql)));
and then my FBML app script had been as simple as:
<?php
require_once('facebook.php');
define('FB_API_ID', 'XXX');
define('FB_AUTH_SECRET', 'YYY');
$fb = new Facebook(FB_API_ID, FB_AUTH_SECRET);
$viewer_id = $fb->require_login();
$data = json_decode($fb->fb_params['info'], true);
$first_name = $data[0][0];
$last_name = $data[0][2];
$female = ($data[0][3] != 'male');
$avatar = $data[0][3];
$city = $data[0][4]['city'];
# and then I'd just construct flashvars attribute
# for the <fb:swf ...> tag and print it
?>
Does anybody please have hints on how to recreate the same script for the iFrame version - i.e. how can I fetch the result of Preload FQL by my iFrame app?
According to an older Facebook blog entry Preload FQL should be accessible by the iFrame apps.
Thank you!
Alex
My own answer after long searching is that Preload FQL results aren't sent to iframe Facebook apps.
That is why Facebook performance doc says:
"Preload FQL Query and Multiquery.
This section applies to FBML canvas pages, but not to websites or IFrame canvas pages."
As Facebook said for Preload FQL
"Facebook will send the result of these FQL queries as JSON-encoded POST parameters to your Canvas URL"
print_r your $_POST and see which variable is the "json-encoded results". You convert json into php object using json_decode
JSON looks like this: {"var":"val","var":"val"}
Also, Facebook already has great docs for iframes. Then you might have missed these great docs:
Facebook Docs Home
http://developers.facebook.com/docs/
Authentication
http://developers.facebook.com/docs/authentication/
Signed Request
http://developers.facebook.com/docs/authentication/signed_request/
iFrame Canvas Apps
http://developers.facebook.com/docs/guides/canvas/
PHP SDK
https://github.com/facebook/php-sdk
Graph API
http://developers.facebook.com/docs/reference/api/
You don't need to call any FQL for the information you are getting. For iFrame you just need to do following steps
Download the PHP SDK of graph api https://github.com/facebook/php-sdk/
Create the object and authorize the app from user
$fbconfig['appid' ] = "your application id";
$fbconfig['api' ] = "your application api key";
$fbconfig['secret'] = "your application secret key";
try{
include_once "facebook.php";
}
catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
// User location extended permission allow you to get user's current location
$loginparams = array('canvas' => 1,'fbconnect' => 0,'req_perms' => 'user_location');
$loginUrl = $facebook->getLoginUrl($loginparams);
// We may or may not have this data based on a $_GET or $_COOKIE based session.
// If we get a session here, it means we found a correctly signed session using
// the Application Secret only Facebook and the Application know. We dont know
// if it is still valid until we make an API call using the session. A session
// can become invalid if it has already expired (should not be getting the
// session back in this case) or if the user logged out of Facebook.
$session = $facebook->getSession();
$fbme = null;
// Session based graph API call.
if ($session) {
try {
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
} catch (FacebookApiException $e) {
d($e);
}
}
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}
// You can found all the data in this array.
print_r($fbme);
For more detail you can follow this tutorial http://thinkdiff.net/facebook/php-sdk-graph-api-base-facebook-connect-tutorial/
Hope it works for you