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
Related
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
}
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've got some trouble with Facebook authentication. Even when I'm logged, the function getUser() returns 0
Here's my code :
$fb_params = array(
'appId' => APP_ID,
'secret' => SECRET_ID
);
$fb = new Facebook($fb_params);
echo $fb->getUser(); // UID
Someone's got an idea?
PS : 'I can no long access to $fb->api('/me'), it says it requires an access_token, I think it's linked to the authentication issue...'
Thanks
You are currently not authenticating as a user, only as an application. As a result, the Facebook API can't show you the /me page or respond to a getUser() call since it doesn't know what user you are trying to access the API on behalf of (ie. "Who is /me?"). You will also only be able to access publically-accessible information.
You need to get a user to authenticate your application through Oauth2, store the access_token you are returned, and then include it in any future calls (eg. WIRQjCey1.3600.1309525200.0-509450630|eD6SAR">https://graph.facebook.com/me?access_token=2227470867|2.AQB-_WIRQjCey1.3600.1309525200.0-509450630|eD6SAR...).
To do this using the PHP SDK you can do
$loginUrl = $fb->getLoginUrl();
echo "<a href='$loginUrl'>Login with Facebook</a>";
Clicking that link and having the user authenticate will store the access_token to the $_SESSION, and when you hit refresh the "new Facebook( $fb_params );" constructor will pick out the access token from the $_SESSION and use it for all future calls, so then calls like $fb->getUser(); will return correctly.
There's a functioning example in the examples folder of the SDK, here:
https://github.com/facebook/php-sdk.
You can use it to try calls while authenticated as an application (public data access only), and then as a user.
Problem is, when a user clicks on FB Login button on my site, Facebook API throws him with a window which ask for access permissions(which is the usual flow). But when the user chooses the proxy mail address (anonymous), then I want to force the user to login only using his real email id.
How am I supposed to handle this ?
I can detect that user used proxy email and prevent him from registering, but then I can't remove my app from his list of authorized apps - meaning I can't get him to that initial dialog for choosing which email he will provide.
You can't force the user to go through the authorization dialog again, because as far as Facebook is concerned, the user has installed your application and nothing else needs to happen. The best thing you can do here is write your own form which informs the user that the Facebook proxy e-mail address is unacceptable and you need a real e-mail address. Unfortunately, this does not force the user to give you their Facebook account e-mail address, or even a real e-mail address. This is the best we have via Facebook though, and it's just something we have to deal with.
UPDATE 5/10/11
I was browsing around the Facebook documentation, and found a method that exists in the old Legacy REST API which actually allows you to remove extended permissions for your app from a user. I think you could use this exact API call to manage getting non-proxy addresses from your Facebook user, while still using the native install dialog.
I tested this using the FB JS SDK and it worked! The method you need to use is the auth.revokeExtendedPermission method. Here are 2 examples of calling that method via the JS SDK and the PHP SDK.
Javascript:
<script>
FB.api({
method: 'auth.revokeExtendedPermission',
perm: 'read_stream'
}, function(response)
{
console.log(response)
});
</script>
PHP:
<?php
$facebook->api(array(
'method' => 'auth.revokeExtendedPermission',
'perm' => 'email',
'uid' => $uid
));
Because these use the Legacy REST API they're not as "supported" as the new Graph API. I've not seen anything regarding migrating this feature to the Graph API. Hopefully they will.
Invoke revocation of the app through graph api (as below) with the php sdk then redirect user back through your dialog with this non-proxy requirement explained.
private function revokeAccess() {
$access_token = $this->facebook->getAccessToken();
$result = $this->facebook->api(array(
'method' => 'auth.revokeAuthorization',
'uid' => $this->{facebook id here},
'access_token' => $access_token
));
return $result;
}
This code is php.
This completely removes the app.
Returns 1 on success; 0 on failure.
$this->facebook == facebook object from the facebook php sdk.
I know Omniauth is just for authentication and it doesn't really have FB or Twitter tools included.
However, let's say my Rails 3 app uses Omniauth and I now have some users registered in my system.
How can I then post to their wall? Or do I need some other type of authorization system?
Thanks for any pointers.
I found this link which allowed me to post to both Facebook and Twitter. Very good tutorial:
http://blog.assimov.net/post/2358661274/twitter-integration-with-omniauth-and-devise-on-rails-3
I used this guide while setting up my application to connect to twitter:
http://philsturgeon.co.uk/news/2010/11/using-omniauth-to-make-twitteroauth-api-requests
Helped me a ton, hope it does for you the same.
Original post
Posted: Nov 16, 2010
Using the brilliant user system gem Devise and a gem called OmniAuth you can make a Rails application that logs in or registers users via Twitter, Facebook, Gowalla, etc with amazing ease. But once the user is logged in, how do you go about actually interacting with the API on behalf of the account that has just been authorized?
This article starts where RailsCasts leaves off, so if you are not already up and running with Devise and OmniAuth then you might want to watch:
RailsCast #209: Introducing Devise
RailsCast #235: OmniAuth Part 1
RailsCast #236: OmniAuth Part 2
So, assuming we are all about at the point that the third video ends on, we are all ready to go. I'll be using the example of Twitter but really any of the providers using oAuth will use the same approach. Like in the "ye-olden days" when we used the Twitter username and password to authenticate an API request, we now use a Access Token and Token Secret. You can think of these as being basically the same thing as for the purpose of authenticating API requests, to us, they are.
To get the token and secret you need to add some fields to your authentications table:
rails g migration AddTokenToAuthentications token:string secret:string
rake db:migrate
Now the database is ready to save the credentials we can change the authentication code to populate the fields. Assuming you placed the method in user.rb like RailsCast #236 suggested then open user.rb and modify the following line:
authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid'])
and replace it with:
authentications.build(
:provider => omniauth['provider'],
:uid => omniauth['uid'],
:token => omniauth['credentials']['token'],
:secret => omniauth['credentials']['secret']
)
Now whenever anybody authenticates their account we can save their credentials which are passed back from the internal hidden magic that is OmniAuth.
The next step is to actually make some requests using these saved credentials, which is described almost perfectly in the Twitter Developer Documentation. You'll want to install the oauth gem (put it in your Gemfile and run bundle install) then you can use the following code to test-dump a list of tweets from the user:
class TwitterController < ApplicationController
def recent_tweets
# Exchange your oauth_token and oauth_token_secret for an AccessToken instance.
def prepare_access_token(oauth_token, oauth_token_secret)
consumer = OAuth::Consumer.new("APIKey", "APISecret"
{ :site => "http://api.twitter.com"
})
# now create the access token object from passed values
token_hash = { :oauth_token => oauth_token,
:oauth_token_secret => oauth_token_secret
}
access_token = OAuth::AccessToken.from_hash(consumer, token_hash )
return access_token
end
auth = current_user.authentications.find(:first, :conditions => { :provider => 'twitter' })
# Exchange our oauth_token and oauth_token secret for the AccessToken instance.
access_token = prepare_access_token(auth['token'], auth['secret'])
# use the access token as an agent to get the home timeline
response = access_token.request(:get, "http://api.twitter.com/1/statuses/user_timeline.json")
render :json => response.body
end
end
By pulling the content from current_user.authentications (im finding the first as in my application they should only have one) I can grab the credentials and have full permissions to get their recent tweets, post new ones, see friends tweets, etc.
Now I can tweak this, get stuff saved, faff with the JSON and take what I need. Working with Facebook or any other oAuth provider will work in an almost identical way, or you can install specific gems to interact with their API's if the direct approach is not as smooth as you'd like.
end of original post