Facebook social graph API call for authenticated user - php

I'm trying to grab data about a user in Facebook that can only be fetched if the app is authenticated (for example /likes).
However, I can't seem to grab this data despite the fact that the user has authenticated the Facebook app (and the applicable specific permissions). I can only get data from a public context.
I'm assuming I must be missing some sort of authentication step, but I can't figure out how. When I call $fb->getAccessToken(), it returns a string value, so it seems like it does get an access token for making requests. I see some solutions to force the user to click on a login URL to authenticate, but hasn't that already been done if they have authenticated the FB dialog previous (via Javascript)?
Besides that, I need the script to run without any input from the user.
Current code:
$fbConfig = array(
'appId' => 'xx',
'secret' => 'xx',
);
//get facebook configuration parameters defined in admin backend
$fb = new facebook($fbConfig);
$access_token = $fb->getAccessToken();
$fbUid = '123456789'; // Known Facebook User Id
$likes = $fb->api('/' . $fbUid . '/likes&access_token=' . $access_token);
var_dump($likes);
// Result is always: array(0) { }

Here you just want to get a likes of user of your application, i m giving you some code which have been created from me and it's working, i test it. you don't have need to get access token because it will be taken at every time.
<?php
set_time_limit(0);
include_once '../src/facebook.php';
$config=array(
'appId'=>"xxxxxxx",
'secret'=>"xxxxxxx",
'cookie'=>true
);
$facebook = new Facebook($config);
$user=$facebook->getUser();
$accessToken=$facebook->getAccessToken();
$likes=$facebook->api('/me/likes');
var_dump($likes);
?>
Here, set time limit=0 because it'll take more time to get a every likes of user.

Related

Facebook PHP-SDK setAccessToken NOT WORKING

IDEA: Get event information without user interaction from various facebook pages (clubs,bars,etc..). However some pages have set that info not to be public.
WORKING PRINCIPLE: I have the latest facebook PHP-SDK on my site and an APP on facebook, so usually i call
$facebook = new Facebook(array(
'appId' => '387262991341732',
'secret' => '09014d999f6e34d80ca3e62e331834cc',
));
$events = $facebook->api("$page_url/events");
PROBLEM:
When a page is not public I have to use an access_token.
1) This is an APP access-token, which is not permitted to view the events.
$app_token = $facebook->getAccessToken();
So I figure I need to get user access_token and add more code:
if (!$user) {
$args['scope'] = 'offline_access';`<br>`
$loginUrl = $facebook->getLoginUrl($args);`<br>`
}
<?php if (!$user): ?>
Login with Facebook
<?php endif ?>`
I click the link by myself and use getAccessToken() to get the user access_token:
$user_token = $facebook->getAccessToken();// I store this in my database
I check this with:
file_get_contents('http://graph.facebook.com/privatepage/events?access_token=$user_token');
// Everything works, im very happy
2) Now I delete all cookies, etc and try to use $facebook->setAccessToken($user_token) and then $events = $facebook->api("$page_url/events"); and get nothing. I assure you one more time that AccessToken is valid.
After quite a long research im stuck with this.
???) *Any Ideas how use $facebook->api(...) and not file_get_contents?

facebook php sdk - Error #200 when trying to use setExtendedAccessToken

I have been trying for several days now to successfully post to a client's Facebook Page wall from their website. I need to be able to do this without having a user logged in, which I was able to achieve with an extended access token generated by going to the URL provided in the docs.
What I am trying to do is to fetch an extended token using the PHP SDK as in this question - Facebook PHP SDK: getting "long-lived" access token now that "offline_access" is deprecated, however I receive the following error:
(#200) The user hasn't authorized the application to perform this action
The debug of the auth token generated by the Graph API Explorer shows myself as the User and includes the needed manage_pages and status_update scopes. However, if I run me/accounts, the perms array does not list these under the data for the page in question - not sure if this is relevant.
Here is the code that I have attempted to use:
$facebook = new Facebook(array('appId' => 'xxxxxxx', 'secret' => 'xxxxxx'));
$pageID = 'xxxxxxxx';
$facebook->setExtendedAccessToken();
$accessToken = $facebook->getAccessToken();
try {
$page_info = $facebook->api("/$pageID?fields=access_token");
print_r ($page_info);
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
if( !empty($accessToken) ) {
$args = array(
'access_token' => $accessToken,
'message' => "Catch phrase!"
);
$facebook->api("/$pageID/feed","post",$args);
} else {
// Handle error
}
UPDATE
I found that if I echoed the output of getAccessToken() the result was the app ID and the secret separated by an | - is this what I should be receiving? Seems odd to me since all of the other tokens I have seen are random and much longer.
ANY help at all would be appreciated, I have wasted so much time on this so far. It just seems to work for everyone else.
UPDATE 2
Hi Warren! Looks like you're new around these parts, welcome! Thanks for your research into this, do I need to save these tokens into a DB table and check to see if they are expired every time I try to post? I am ONLY posting to a Page as the Page, apparently this requires the Page access_token rather than what I am assuming is the USER access_token. I believe I also read somewhere that the Page access token never expires, although it changes if I refresh the Graph API Explorer page or request a new user token. Very puzzling.. do not know if I even need to deal with getting new tokens in this app or just use a Page access_token that appears to work?
Also just looking at the base_facebook.php file and the following function:
/**
* Returns the access token that should be used for logged out
* users when no authorization code is available.
*
* #return string The application access token, useful for gathering
* public information about users and applications.
*/
protected function getApplicationAccessToken() {
return $this->appId.'|'.$this->appSecret;
}
Shows what you are experiencing the function setExtendedAccessToken() calls getAccessToken() which calls the function above to do the following inside setExtendedAccessToken:
$access_token_response = $this->_oauthRequest(
$this->getUrl('graph', '/oauth/access_token'),
$params = array(
'client_id' => $this->getAppId(),
'client_secret' => $this->getAppSecret(),
'grant_type' => 'fb_exchange_token',
'fb_exchange_token' => $this->getAccessToken(),
)
);
the return of this function is then {"error":{"message":"No user access token specified","type":"OAuthException","code":1}} but because there is no access_token the function just returns false
the fb_exchange_token can not be the app id and app secret combined.
I have done some testing and what I have found out is if you get the user to login, you can get there access token. If you pass this token into setAccessToken then run setExtendedToken. If you then save the toke by running getAccessToken you can use this token later when the user is logged out.
$facebook->setAccessToken($facebook->getAccessToken());
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken(); // save this for later use
You need to get the user to login to ask them for permission to get access to there account. If you need to get access to a facebook page make sure they are an admin and ask for the manage_page permission.
Hope this helps
From what I have found so far the extended token that is returned when the user is logged in does not expire as you do not get back a unix timestamp so you would have no way of knowing when it expires.
This is what I have done in my application.
Request the user to login to facebook and except the access permissions. Use getAccessToken to get the current access token. With this I pass into getExtendedAccessToken then run getAccessToken again to finally get the extended access token which I store in a database for later use.
$facebook = new Facebook(array(
'appId' => 'YOURAPPID',
'secret' => 'YOURSECRET',
));
$params = array(
'scope'=>'publish_stream,manage_pages'
);
$loginUrl = $facebook->getLoginUrl($params); // Use this to request them to login in then when they are do the following you will need them to return to your app
$facebook = new Facebook(array(
'appId' => 'YOURAPPID',
'secret' => 'YOURSECRET',
));
$facebook->setAccessToken($facebook->getAccessToken());
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken(); // store $access_token for later use

Retrieving user information with access token - Facebook developer

I'm developing a Facebook application, and I want to retrieve some of the user's information on a side server while they are using the application.
In order to make that possible, I store the users access token in my database and pass it to the other server.
However, I am not sure how to use the access token to retrieve the user information. I am using the PHP SDK, and here is the usual code:
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => '',
'secret' => '',
));
// Get User ID
$user = $facebook->getUser();
Where can I declare the access token?
It's very simple. If you enter a url like https://graph.facebook.com/me?access_token=theuseraccesstoken (in your browser) you will receive a json file with the user information.
I'm pretty sure the facebook php sdk have a built in mechanism to do that (I'm a c# coder), but you are looking in the wrong place, because no api key or secret is necessary to access user information using a access token.
UPDATE1:
I think it works like this in the sdk
$facebook->setAccessToken($access_token);
$user = $facebook->getUser();
UPDATE2:
Or like this
$user = $facebook->api('me?access_token='.$access_token);
If the user is logged in, make:
$facebook->api('/me');
I will give you an array with information about the user.

Post to Facebook Page Wall without logged in user

I have a Facebook app that I want to use to post on my customer's Facebook Page Walls on their behalf. I have it setup now so that when they authenticate my app I get the Access token, but when I go to post to the wall I am getting the following error: "OAuthException: Error validating access token: The session is invalid because the user logged out."
How can I post from my script without being logged in?
Here is my code:
include_once('fb-php-sdk/src/facebook.php');
$facebook = new Facebook(array(
'appId' => 'XXX',
'secret' => 'XXX',
));
try {
$page_id = '215133535279290'; //page id of the customer's facebook page
$args = array(
'access_token' => 'XXX', //access token received when user authenticated app
'message' => 'A test message'
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
} catch (FacebookApiException $e) {
echo "Error:" . $e;
}
The new facebook API has what is called an extended access token (it replaces offline access: https://developers.facebook.com/roadmap/offline-access-removal/ I think) which I believe lasts upto 60 days (or something like that). To use it simply get the access token when the logs in through your website:
$token = $facebook->getAccessToken();
Save it to Db and use this token later:
$facebook = new Facebook();
$facebook->setAccessToken($accessTokenFromDB);
Then you should be able to continue as though the user is logged in.
As for the user being logged out part, make sure you are using the latest version of the API and not an old version and also make sure the stuff under the "Scenario 2: If you have been previously requesting offline_access - updated 4/30/2012" heading of the page I linked.
You could carry on using offline_access until 3rd of October, but then why if it's being turned off for real in 2 months time and would have to rewrite your code.
Get the publish_stream extended permission. Once you have this permission you can post feed stories using your app access token while the user is offline. There is no need for offline_access permissions or saving and using a user access token in this scenario.

Facebook PHP SDK - User not authenticated

I am using Facebook PHP SDK to authenticate the user. After generating the LoginUrl using the PHP SDK, the user clicking on that LoginUrl gets redirected to the Facebook page asking for permission. After clicking on the Go to App link, the user gets redirected back to my website http://www.mydomain.com/login/facebook_connect.
Problem: After being 'authenticated' by Facebook, the PHP script at http://www.mydomain.com/login/facebook_connect is unable to determine that the user has logged in via Facebook. At this point, $user = $facebook->getUser(); is 0.
Did I do something wrong? Thanks!
PHP Code for page that generates LoginUrl
require 'libs/fb-php-sdk/facebook.php';
// Create our Application instance
$facebook = new Facebook(array(
'appId' => '123',
'secret' => '123'
));
// Get User ID
$user = $facebook->getUser();
// Get Login URL
$loginUrl = $facebook->getLoginUrl(array(
"scope" => "email,user_education_history,user_work_history",
"redirect_uri" => "http://www.mydomain.com/login/facebook_connect/"
));
$data['fb_login_url'] = $loginUrl;
$this->load->view('splash', $data);
PHP Code for page user is redirected to after Facebook authentication
*http://www.mydomain.com/login/facebook_connect/*
require 'libs/fb-php-sdk/facebook.php';
$facebook = new Facebook(array(
'appId' => '123',
'secret' => '123',
));
// See if there is a user from a cookie
$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;
}
}
print_r($user_profile);
echo $user;
All seems correct.
Questions:
1.- I supposed that http://www.mydomain.com/ contains all your scripts, right?
2.- Are you using codeigniter? Or a codeigniter-based CMS? In that case maybe you have a session problem (very common in CI). Check it and we continue...
EDIT 2: In case of being a cookie related problem. Here is an image showing as you can use firebug with a cookie module to easily track your cookies:
So you can check how facebook cookies are being generated.
EDIT 3: Ok. So you are using CI and your FB cookies are being deleted. Maybe is a session problem. Here is a related answer where I explain how to use a session CI library replacement that generally solve all these kind of painful issues. Believe me, give it a try!
a.- Here it is: Codeigniter's Native session (there is a download link at the bottom)
b.- BUT, due that it is an old library you MUST made some hacks. You can check those simple hacks in the library's forum
c.- Just drop this file in codeigniter's library directory.
$facebook->getUser() uses a cookie to get the user. If you use CodeIgniter, or another library that "eats" cookies that PHP assigns automatically, you need to create a proxy page outside CI, that would pick up the cookie the redirect back into CI.
In other words, take to code you currently have in
http://www.mydomain.com/login/facebook_connect/
and create a copy in a regular PHP file:
http://www.mydomain.com/facebook_pickup.php
do not echo anything from the script (remove print_r), just redirect to
http://www.mydomain.com/login/facebook_connect/
and it would magically start working.

Categories