I am trying to pull facebook posts onto my site so that I can save and display it in my own format. I am trying to use the facebook-php-sdk library, found on the Facebook Developer pages. I used the following code after I required the library:
$facebook = new Facebook(array(
'appId' => 'MY APP ID',
'secret' => 'MY APP SECRET',
));
// Get User ID
$user = $facebook->getUser();
print_r($facebook);
print_r($user);
The print_r into $facebook showed me a full facebook object, so I know its being created properly.
object(Facebook)#325 (9) { ["sharedSessionID":protected]=> NULL ["appId":protected]=> string(15) "[MYAPPID]" ["appSecret":protected]=> string(32) "[MYAPPSECRET]" ["user":protected]=> int(0) ["signedRequest":protected]=> NULL ["state":protected]=> NULL ["accessToken":protected]=> string(48) "[MYAPPID]|[MYAPPSECRET]" ["fileUploadSupport":protected]=> bool(false) ["trustForwarded":protected]=> bool(false) }
(I took my app id and app secret codes out of the quote above).
However, the print_r into $user displayed
int(0).
What am I missing here?
“What am I missing here?” Authenticating the user. You’re calling getUser(), but until you authenticate, Facebook doesn’t know which user to get details for. I’m also unsure why you’ve missed it, as it’s the example on the GitHub repo for the PHP SDK.
I don't know what this getUser() function is, but what you have to do is very very simple and you don't even have to use a huge library (I prefer to use what I can check easily, or what I have written, if I manage). It looks like a duplicate of this question, or the other way around. Anyhow, I am repeating it here too:
In order to get your feed, you have to use a token. To retrieve that token, make a cURL call to using this url https://graph.facebook.com/oauth/access_token?type=client_cred&client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET
Let's say you got it already and you called it $token. Use that to get your feed.
$pageFeed = someCURLfunction("https://graph.facebook.com/{$yourid}/feed?{$token}");
//you don't need a login. You have to get an auth token though
$jsonStuff = json_decode($pageFeed); //it's a json object. You need to decode it
foreach ($jsonStuff as $feed)
{
//loop through it and
// finish it here
}
Related
I'm going slightly mad because of my problem. I prepared facebook app based on facebook-php-sdk. My app's permisions are:
publish_acions, user_location, user_likes, friends_likes
Everything goes correct with that code:
$facebook = new Facebook(array(
'appId' => '####',
'secret' => '####',
));
I can also receive
$user = $facebook->getUser();
$user_profile = $facebook->api('/me');
$userId = $user_profile['id'];
But I can't receive
$user_likes = $facebook->api('/me/likes/');
It just gives me an empty array (I'm quite sure I like the page). So what's the reason?
Thanks in advance...
First of all: Use The JavaScript for the login process, it´s much easier to handle and debug. Also, it´s better for the usability, because it does not redirect: https://developers.facebook.com/docs/reference/javascript/FB.login/v2.1
Use the "scope" parameter as it is mentioned in the docs and check if the required permissions are really asked for in the authorization popups.
Btw, the correct endpoint would be /me/likes (without the slash at the end), just another idea why it does not work.
And then there is the review process, most permissions (like user_likes) need to get approved by Facebook before they can be used for other users (except for users with a role in the App settings). Check out the changelog and the review guidelines for more information:
https://developers.facebook.com/docs/apps/changelog
https://developers.facebook.com/docs/apps/review/login
Friend permissions are deprecated btw, there is no "friends_likes" anymore.
Hi I was looking around the web, but I couldn't find any simple answers on how to get JUST the facebook id from the current user viewing my application. I understand that I need to get the User object from the Graph API and just get the id from that field. I also understand that I do not need an access token for my case. I am trying to do this in perl/mason and I was wondering if anyone could help me out with this. I am sorry if this is a duplicate, but I couldnt find that many answers out there with perl / mason
Thank you
Is there something as simple as this in perl /mason?
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();
Check out this
Looks like it will get you what you need.
Though I'm a bit confused what getUser() would return for an application. You've not specified anything to tell it what user you want, but I'm no facebook expert.
Regarding needing access token, Yes and no
You don't need access token to fetch current use basic info just if you use facebook javascript sdk, I guess the example above you posted is facebook php sdk which work in combination with their javascript sdk so I think function getUser actually talk to the javascript side of the SDK
see facebook javascript sdk for example on how to use it
to get user data to your perl app I suggest you use ajax call
after initiating javascript sdk, to get user id
//-> /me is for current logged user
FB.api('/me', function(response) {
alert('Your name is ' + response.name);
//send response to your perl app
});
Other wise authorization process is required and access token is needed.
I'm not sure if there is a perl module that integrates facebook javascript sdk with any templating / mason but I guess this isn't hard to do manually
I see this has been asked a lot here but I still have yet to come up with a solution. I need to get the user's ID to determine if they have already filled out a form in my app. Here is my code..
require_once('facebook.php');
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'cookie' => false,
));
$signed_request = $facebook->getSignedRequest();
$page_id = "fb" . $signed_request['page']['id'];
$user_id = $facebook->getUser();
I don't know if this is related or not but I can grab the page id just fine. But $user_id keeps returning as 0 for all users except me. I'm guessing that's because I'm an admin of my page.
Does anybody know what the problem is here?
My guess is that most of the reported problems with $facebook->getUser() are related to CSRF (Cross Site Request Forgery) protection that is built into Facebook's PHP SDK and is implemented somewhat awkwardly.
What CSRF protection does is to make sure that a request to get user's data needs to originate from the same server. It does it by storing a random hash in the session. If you call to getUser() without this value set, getUser() will always return 0.
So the user needs to visit your site first, a CSRF token will be generated and stored in the session and only on the following requests you can successfully call getUser()
If you look at the PHP SDK source code you'll notice that the way to generate this CSRF token is to call a protected method called establishCSRFTokenState(). You can't call this method from outside and the only way it gets called is when calling $facebook->getLoginUrl(...)
So, either modify the SDK source to change this behavior (or to make establishCSRFTokenState() public) or just call getLoginUrl(...) when the user first visits your site. Make sure that you have session support enabled.
I think this isn't designed very well and documented even worse. And it doesn't help to protect the site against CSRF attacks in most cases unless people understand how to properly use it.
i has this problem too, the only solution was to use oauth before with permission request
"user_about_me". Since FB uses oauth 2.0, most user values are hidden and you have to request
all this sh*t :(
I sign in with FB fine if I directly create a page at domain.com/someurl.php
The moment I copy the same code (inc html) into a view file with codeigniter and go to domain.com/login/someurl.html it doesn't work. By it doesn't work I mean, I get an exception if i try to access /me after signing into facebook.
The message reads "An active access token must be used to query information about the current user"...
In my controller i have my index function and all it does is load the view with the facebook login code.
I thought I may be doing something wrong but I copied the sample.php from the facebook sdk and paste it into the view file and the same thing happens. If i copy the sample code into the file at someurl.php it then works as expected...given the situation I suspected it may be something to do with codeigniter and possibly some config option I have that causes that behaviour...
I've been looking up the error for a while now and have found a few resources:
http://benbiddington.wordpress.com/2010/04/23/facebook-graph-api-getting-access-tokens/
Facebook access_token invalid?
Facebook authentication issue
https://github.com/facebook/php-sdk/wiki/AccessToken
but none of the suggested fixes have worked.
Right from the sample:
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'APPID',
'secret' => 'SHHHH',
));
// 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();
}
It doesn't work in the view and I'm stumped as to why or why none of the fixes or "precautions" such as not using type or ensuring the redirect url is the same etc, work.
EDIT:
I'm trying to avoid using domain.com/somefile.php and instead use a view file like every other page...
The issue has cropped up in other places such as the Elliot Houghin fb/CI library.
I found a solution documented in a tutorial here:
http://www.dannyherran.com/2011/02/facebook-php-sdk-and-codeigniter-for-basic-user-authentication/
The problem could be cause from one of several issues pointed out on a an issue on Elliot's github repo. I tried many of the suggested "fixes" but the one that seemed to help was not using the facebook instance as a class property. After trying the tutorial at the above link I tried a fresh install of CI again and created a facebook instance inside the function, the API calls with the FB SDK then worked and had no problems so far.
Bug report with suggested fixes #
https://github.com/elliothaughin/codeigniter-facebook/issues/5
Maybe I searched completely in the wrong way, and the facebook documentation pretty much sucks in my opinion.
I was wondering, I'm connecting to facebook with the settings below and that works (I'm able to retrieve the profile information of the logged in user allows my application to access his profile.) Are there other options I can set, like the callback url and the expiration (which I want to set to never, so I can save the token in my db and re-use it)?
This is the config now:
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxx',
'cookie' => true
));
I'm also connection to twitter and there I'm able to this:
$this->configTwitter = array(
'callbackUrl' => 'xxxxxxxxxxxx',
'siteUrl' => 'http://twitter.com/oauth',
'consumerKey' => 'xxxxxxxxxxxx',
'consumerSecret' => 'xxxxxxxxxxxx'
);
Thanks in advance!
Facebook should take a look at Twitter
After trying a few days, spitting the documentation of the Graph OAuth 2.0 (which doesn't work as good as expected and searching the internet I found a solution which I used to create the following script:
// Config
$this->redirectUrl = 'http://www.mywebsite.com/facebook'
$this->clientId = 'APPLICATION_ID';
$this->permissions = 'publish_stream,offline_access';
// Check if a sessions is present
if(!$_GET['session'])
{
// Authorize application
header('Location: http://www.facebook.com/connect/uiserver.php?app_id='.$this->clientId.'&next='.$this->redirectUrl.'&perms='.$this->permissions.'&return_session=1&session_version=3&fbconnect=0&canvas=1&legacy_return=1&method=permissions.request');
}
else
{
$token = json_decode($_GET['session']);
echo $token->access_token; // This is the access_token you'll need!
// Insert token in the database or whatever you want
}
This piece of code works great and performs the following actions:
Log in if the user isn't logged in to facebook
Asks if the user wants to add the application and grants the requested permissions (in my case: publish_stream and offline_access) in one dialog
returns to the page you specified under redirectUrl with an access_token (and because we requested for offline access this one doesn't expire)
I then store the token in the database so I won't have to request it again
Now you can, if you wish use the facebook code, or you're own code to get the users data, or other information from facebook (be sure you requested the right permissions)
Don't now if this is facebook-valid code, but it works great and I can easily define the 'config' like I wanted....
There are many settings you can set at the point of authenticating. Extended permissions let you set the offline_access so that you can authenticate and store your session in a db. More info on extended permissions are at developers.facebook.com/docs/authentication/permissions and you can read my blog post for more info on how to use them at http://www.joeyrivera.com/2010/facebook-graph-api-app-easy-w-php-sdk/