I was making a facebook application in which i have to show news feeds of the user who is using it. I am using graph API to do this. The problem is that its not getting me feeds.
I used it to show friends like this:
$friends = $facebook->api('/me/friends');
and it is working fine.
For news feeds i use this:
$feeds = $facebook->api('/me/home');
it shows me an error:
Fatal error: Uncaught IDInvalidException: Invalid id: 0 thrown in
/home/content/58/6774358/html/test/src/facebook.php on line 560
when i try to get Profile feed (Wall) by using this:
$feeds = $facebook->api('/me/feed');
it shows me an empty array.
These API calls are showing me results in the graph API page but don't know why not working in my application.Can any one help me please..
My full code is as follows
require_once 'src/facebook.php';
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => 'xxxxx',
'secret' => 'xxxxx',
'cookie' => true,
));
$session = $facebook->getSession();
$fbme = null;
// Session based graph API call.
if (!empty($session)){
$fbme = $facebook->api('/me');
}
if ($fbme) {
$logoutUrl = $facebook->getLogoutUrl();
echo 'Logout';
}else{
$loginUrl = $facebook->getLoginUrl();
echo 'Logout';
}
$friends = $facebook->api('/me/friends?access_token='.$session["access_token"]);
$feeds = $facebook->api('/me/feed?access_token='.$session["access_token"]);
print('<pre>Herere:');print_r($feeds);die;
Did you ask for the read_stream permission during authentication?
What type of Authentication / "Allow" process did you go through?
JavaScript SDK? Facebook PHP SDK? XFBML Login Button?
EDIT- Here are helpful link that will get you started up:
Facebook PHP SDK
Authentication Process
Building Apps on Facebook.com
These are all official docs in Facebook and github.
EDIT: Follow this step by step:
From your original code, look for:
$loginUrl = $facebook->getLoginUrl();
Change it to:
$loginUrl = $facebook->getLoginUrl(array('req_perms'=>'read_stream'));
Uninstall your application first from your account:
http://www.facebook.com/settings/?tab=applications
Then try it again to show new Allow pop-up
EDIT:
It's also about the arrangement of code in the if statements. Use this code:
<?php
require_once 'src/facebook.php';
$session = $facebook->getSession();
$fbme = null;
if($session){
$fbme = $facebook->api('/me');
$friends = $facebook->api('/me/friends');
$feeds = $facebook->api('/me/feed');
$logoutUrl = $facebook->getLogoutUrl();
echo 'Logout';
echo "<pre>".print_r($feeds,TRUE)."</pre>";
}else{
$loginUrl = $facebook->getLoginUrl(array('req_perms'=>'read_stream','canvas'=>1,'fbconnect'=>0));
echo '<script> top.location.href="'.$loginUrl.'"; </script>>';
}
Uninstall your app again from
http://www.facebook.com/settings/?tab=applications
and re-open the application
The Facebook PHP SDK should handle your access token for you, you don't need to append it to your graph API endpoint in you Facebook::api() call.
As #dragonjet pointed out, you need to request the read_stream extended permission from your FB User in order to get access to their feed. Though, the exception you pasted doesn't really match that kind of problem, and your request to /me/home doesn't throw a similar exception (or one about not having access).
I still think this is a permissions issue, so start here for trying to fix it. Here's an example of how to request the appropriate permission.
$facebook = new Facebook(array(
'appId' => FB_APP_ID, //put your FB APP ID here
'secret' => FB_APP_SECRET, //put your FB APP SECRET KEY here
'cookie' => true
));
$session = $facebook->getSession();
if ($session)
{
//check to see if we have friends_birthday permission
$perms = $facebook->api('/me/permissions');
}
//we do this to see if the user is logged & installed
if (empty($session) || empty($perms['read_stream']))
{
//get url to oauth endpoint for install/login
$loginUrl = $facebook->getLoginUrl(array(
//put the URL to this page, relative to the FB canvas
//(apps.facebook.com) here vvv
'next' => 'http://apps.facebook.com/path_to_your_app/index.php',
'req_perms' => 'read_stream'
));
//use javascript to redirect. the oauth endpoint cant be loaded in an
//iframe, so we have to bust out of the iframe and load it in the browser
//and tell the oauth endpoint to come back to the fb canvas location
echo "<script>window.top.location='{$loginUrl}';</script>";
exit;
}
print_r($facebook->api('/me/home'));
print_r($facebook->api('/me/feed'));
Related
So this is working fine... But when I refresh the page twice(or click on two pages who include this script fast) it gives this error
OAuthException: An active access token must be used to query information about the current user.
Any ideas?
<?php
$app_id = '***************';
$app_secret = '**************';
$app_namespace = '****************';
$app_url = 'http://apps.facebook.com/' . $app_namespace . '/';
$scope = 'email,publish_actions';
// Init the Facebook SDK
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
// Get the current user
$user = $facebook->getUser();
// If the user has not installed the app, redirect them to the Login Dialog
if (!$user) {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => $scope,
'redirect_uri' => $app_url,
));
print('<script> top.location.href=\'' . $loginUrl . '\'</script>');
}
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me', 'POST');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
//<img src="https://graph.facebook.com/?php echo $user; ?/picture">
//?php print_r($user_profile); ?
?>
I personally find it easier to manage the access_token myself. Facebook's Graph API secures protected endpoints by requiring that an access_token be passed in. The PHP SDK abstracts this away, but I have never been comfortable with Facebook handling the information because sometimes it just doesn't work. This isn't to say that the library is bad, but only that I haven't been using it correctly. Keep this caveat in mind.
It looks like you're working with a Facebook Canvas App. When the user successfully authenticates for the first time, Facebook will send an access_token in $_GET. At this point, you should save this to your database, since that access token is good for 3 months or so.
At the point, from then on, you can pass in the access_token in the call parameters:
try {
$user_profile = $facebook->api('/me', 'POST', array(
"access_token" => '' // access token goes here
));
} catch (FacebookApiException $e) {
// error handling
}
Given that Facebook is returning the error that you need an access token in order to call the /me resource, it looks like $facebook->getUser(); is returning something. You may want to double-check what it is.
While I'm here, you're using this logic:
if (!conditional) {
// do something
}
if (conditional) {
// do something else
}
Confusing. Use else:
if (conditional) {
// do something
} else {
// do something else
}
I have crawled around lots of various answers but am still a bit confused with how I should be dealing with facebook access tokens.
One of the main problems I'm having is due to what information is being stored in my browser. For example, I log onto the app, the token expires, I can't logon again unless I clear cookies/app settings in browser.
I stumbled across this thread: How to extend access token validity since offline_access deprecation
Which has shown me how to create an extended access token through php.
My questions are:
1. Do I need to store the access token anywhere?
2. What happens when the access token expires or becomes invalid? At the moment, my app simply stops working when the short term access ones expire.
3. Is there a way I should be handling them to check if they have expired?
I am using the php sdk and have basically used the standard if( $user )... Like this:
require 'sdk/src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'XXXXXXXXXXXXXXXXXXXXX',
'secret' => 'XXXXXXXXXXXXXXXXXXXXX',
));
$user = $facebook->getUser();
if( $user ){
try{
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if (!$user){
$params = array(
'scope' => 'email',
);
$loginUrl = $facebook->getLoginUrl( $params );
echo '<script type="text/javascript">
window.open("'. $loginUrl .'", "_self");
</script>';
exit;
}
if( $user ){
$access_token = $facebook->getExtendedAccessToken();
$get_user_json = "https://graph.facebook.com/me?access_token="
. $access_token;
// Rest of my code here...
}
Is there anything else I should be doing to handle tokens?
. Should I be passing the access token between pages or is it ok to just call it again at the top of each page like this:
$facebook = new Facebook(array(
'appId' => 'XXXXXXXXXXXX',
'secret' => 'XXXXXXXXXXXX',
'redirect_uri' => 'http://localhost:8000/',
));
$token = $facebook->getExtendedAccessToken();
Let's go through your questions:
Do I need to store the access token anywhere?
This depends on your application. First of all ask yourself, do you need to perform actions on behalf of the user while he is not present (not logged in to your app)?
If the answer is yes, then you need to extend the user token which can be done using the PHP-SDK by calling this method while you have a valid user session: setExtendedAccessToken().
Also you should refer to this document: Extending Access Tokens
What happens when the access token expires or becomes invalid? ...
Is there a way I should be handling them to check if they
have expired?
This is where the catch clause in your code comes in handy, while facebook example only logs the error (error_log($e);) you should be handling it!
Facebook already has a tutorial about this: How-To: Handle expired access tokens.
Also you should refer to the Errors table and adjust your code accordingly.
Is there anything else I should be doing to handle tokens?
See above.
Should I be passing the access token between pages or is it ok to just
call it again at the top of each page
You shouldn't need to do any of that, because the PHP-SDK will handle the token for you; have you noticed that you are calling: $user_profile = $facebook->api('/me'); without appending the user access_token?
The SDK is adding it from its end so you don't have to worry about it.
I just had the same issue, but i solve it with some of your help. I'm using the php-sdk to connect to the Facebook API, so i just made this.
$facebook = new Facebook(array(
'appId' => 'API_ID',
'secret' => 'SECRET',
));
// Get User
$user = $facebook->getUser();
// Verifing if user is logged in.
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;
}
}
// Verify if user is logged in, if it is... Save the new token.
if($user){
// Request the access_token to the
$access_token = $facebook->getAccessToken()
// Saving the new token at DB.
$data = array('access_token' => $access_token);
$this->db->where('userid',$user);
$this->db->update('facebook', $data);
}
I have looked at the developers' page but there tons of tons stuff. Application authentication (will my PHP called app?), setting permissions, how to make post after authentication?, where to store authentication? etc etc and so on I wasn't able to get all what all they mean, and what is need in all that stuff.
I only want to make a wall post to the community/fan page's wall as community/fan page. What steps should my PHP application follow to make a wall post?
I've written an in-depth tutorial about this subject: How To: Post On Facebook Page As Page Not As Admin User Using PHP-SDK
In short:
You need at least the publish_stream and manage_pages permissions
Query your page object to get a page access token
And post!
A starting code from my tutorial:
<?php
// This code is just a snippet of the example.php script
// from the PHP-SDK <http://github.com/facebook/php-sdk/blob/master/examples/example.php>
require '../src/facebook.php';
// 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();
if ($user) {
try {
$page_id = 'page_id';
$page_info = $facebook->api("/$page_id?fields=access_token");
if( !empty($page_info['access_token']) ) {
$args = array(
'access_token' => $page_info['access_token'],
'message' => "I'm a Page!"
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
}
} 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(array('scope'=>'manage_pages,publish_stream'));
}
?>
Note: you may need the offline_access if you want to post while you are not connected to Facebook (e.g.: from your CMS)
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
facebook app getting redirected out canvas view
I have developed an Facebook Application. I have posted the index.php over here. When I click on the App icon from my facebook account i am redirected to the www.mywebsite.com/facebook/index.php page. It should redirect me to the canvas URL of my App - apps.facebook.com/example/, but even after I interchange the appBaseUrl and baseUrl addresses in the code it still gets redirected to my website.
I have used official php-sdk 3.0 that can be downloaded from https://github.com/facebook/php-sdk .
What is the problem? Why is the app not going to my canvas page on Facebook?
What changes I have to make in the code below to resolve my problem?
If Any one can help me on this, please do answer.
$fbconfig['appid' ] = "XXXXXXXXXXX";
$fbconfig['secret'] = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";
$fbconfig['appBaseUrl'] = "https://apps.facebook.com/example/";
$fbconfig['baseUrl'] = "http://www.mywebsite.com/facebook/";
include_once "facebook.php";
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
$loginUrl = $facebook->getLoginUrl(
array('scope'=>'email,publish_stream,user_birthday,user_location'));
if (!(isset($_GET['code'])))
echo "<script type='text/javascript'>top.location.href = '".$loginUrl."';</script>";
else
{
$user = $facebook->getUser();
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
err($e);
$user = null;
}
$userInfo = $facebook->api("/$user");
function err($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}
}
Check your facebook developer settings, make the site_url setting as blank and set the url for facebook app integration.
you should check your Canvas URL, which will display content in facebook app page.
if you didn't specify this url in app settings, facebook will redirect user to your Site URL.
I'm integrating my web-based game to a Facebook Game . Facebook login, getting user id, getting user profile picture is OK . But i need to post somethings to wall (For example, John Doe earned 50 point!) .
I have offline_access and publish_Stream permissions for my Facebook App.
Now i want to publish some links automatically. I'm using Facebook PHP SDK with Yii.
I can get Facebook User ID etc... But i don't know how can i post somethings to user's wall, automatically (for example when user is offline).
I'm looking Graph API Post document's Publishing title. But i need access_token parameter for use this. And i'm not sure where is this access_token .
PHP-SDK 3.1.1
To generate app and user tokens. $app_access_token & $access_token
*The user access_token if you have offline access will never expire, unless user deAuthorizes your app. You would need to use for posting to a users wall when they are offline or not interacting with your application.*
<?php
require './src/facebook.php';
$facebook = new Facebook(array(
'appId' => '135669679827333',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
));
$user = $facebook->getUser();
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;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
// Create Application Access Token
$app_access = "https://graph.facebook.com/oauth/access_token?client_id=135669679827333&client_secret=xxxxxxxxxxxxxxxxxxxxxxxx&grant_type=client_credentials";
$app_access_token = file_get_contents($app_access);
// If we have a user who is logged in, create access_token with session.
if ($user) {
$access_token = $_SESSION['fb_135669679827333_access_token'];
}
?>
Take a look at the authentication doc which will show you how to get an access token.
you can get access token like this
$access_token = $session['access_token'];
now use $access_token where u need it
$my_friends_ids=file_get_contents("https://graph.facebook.com/me/friends?access_token=".$access_token);
here i am getting ids of all my friends