Get Facebook user's profile picture prior to authenticating app - facebook

Summary:
I am working on a website that connects to Facebook through the Graph API. I was asked whether I can get a user's profile picture if they are already logged into Facebook, but prior to the user authenticating the app. Is this possible?
EDIT:
I know you can get people's profile picture by going to http://graph.facebook.com/USERNAME_OR_USERID/picture?type=large, but would I be able to get a user's username or ID if they are logged into Facebook, but have not authorized my app?
Details:
According to the Facebook API User documentation, you can get their Facebook ID without an access_token, and I know if you go directly to a user's /me URL you can see their basic information. With the Facebook ID, I can grab their profile pic.
However, when I try to call it from the website using the following code, I get an OAuthException error.
FB.api('/me', function(response) {
console.log(response);
});
I'm guessing that they have to authenticate the app, but I'm looking to see if I may have missed a way of getting their profile pic.
Thanks for your help!

You can get everyone's Facebook profile picture without authentication.
You just call http://graph.facebook.com/USERID/picture?type=large.
This URL redirects you to image URL.
Edit: Querying by username is not allowed anymore, so I updated USERNAME_OR_USERID as USERID.

yes you can get..
http://graph.facebook.com/naseer.panhwer/picture?type=normal
http://graph.facebook.com/naseer.panhwer/picture?type=small
http://graph.facebook.com/naseer.panhwer/picture?type=large

You can generate an access token using an application id and secret as follows:
https://graph.facebook.com/oauth/access_token?client_id={appID}&client_secret={appSecret}&grant_type=client_credentials
NOTE: Don't do this on the client side as you risk having your application getting hijacked.
The resulting token can be user to query users with the graph API without a login prompt.

How to get FB images w/o oauth or access tokens:
I was trying to get only images of few members but I was stuck then wrote this snippet and worked for me,
The HTML tag
<img src="getFbImage.php?id=<fbid_of_the_person>&type=[small|large]" />
The PHP code
<?php
$remoteImage = !isset($_GET['id']) ? "../images/default.png" : getImg($_GET['id']);
$imginfo = getimagesize($remoteImage);
header("Content-type: ".$imginfo['mime']);
readfile($remoteImage);
function getImg($id){
$dom = new DOMDocument;
$dom->loadHTML(getData($id));
$tags = $dom->getElementsByTagName('img');
$img = '';
foreach ($tags as $tag) {
$img =$tag->getAttribute('src');
if($img=='')
continue;
else if(isset($_GET['type']) && $_GET['type']=='large')
break;
}
//This iteration has a lot of images try your luck.
return $img;
}
function getData($id){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://www.facebook.com/photo.php?fbid='.$id);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 Firefox/39.0');
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
?>
I only had to use a 30x30 image and I got what I wanted. Check out it also provides you a large image.
Cheers!
Joy

Related

Yahoo oauth2 - getting access token from code

I am trying to integrate my application with Yahoo oauth2 login. I am not using any external libraries and following the instructions in https://developer.yahoo.com/oauth2/guide/
I generated authorization URL, redirected user to the login page of yahoo and got the code (completed steps 1-3 in the Yahoo guide).
Now I have to pass this code and get the access token. (Step 4: Exchange authorization code for Access Token)
For that, I am using the code as given below
$fields_string = 'grant_type=authorization_code&redirect_uri='.$CALLBACK_URL.'&code='.$code;
$fieldCount=3;
$ch = curl_init();
$headers = array(Authorization: Basic '. base64_encode($CONSUMER_KEY.':'.$CONSUMER_SECRET),
'Content-Type:x-www-form-urlencoded'
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, $fieldCount);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_exec($ch);
result = curl_exec($ch);
But this is not working and I am not getting any response from Yahoo. Any help is appreciated. Thanks.
Ok, solved it. Call was made similar to get_access_token method inside https://github.com/saurabhsahni/php-yahoo-oauth2/blob/master/YahooOAuth2.class.php

how to get post_id of a Facebook post (programmatically)

How to get post_id of a Facebook post programmatically, for example, I see a post on my wall, what is the best way to get its post_id programmatically.
thanks Gurus.
This is obviously extremely difficult to due since the nature of facebook's feed and the framework it uses (reactjs). They do not want you to get post_ids and they do not want you to mimic their service. The most you'll get is id's like r.2.15, etc, which will mean nothing to you.
See, whenever you post a comment (using Graph API), you get the post_id in return.
But if you want the post id of a feed that was not published using Graph API, you can do-
get all the feeds with \GET /user-id/feed You'll get message, description, id and other details
check for for your post and get the id
You can get the post ids using graph api. If you have a valid access token you can try this below code to get the post ids. Here we are using page /feed to get the posts. you can use page /posts to get only page posts.
$fb_page = ''; //your page name
$access_token = ''; //your access token
$url = "https://graph.facebook.com/v2.2/".$fb_page.'/feed?access_token='.$access_token;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
curl_close($curl);
$details = json_decode($result,true);
$posts = $details['data'];
foreach ($posts as $post)
{
echo "<p>".$post['id']."</p>";
}

How can you use data from facebook's graph API without having to login?

I am creating a personal website about myself and i would like to have it pull images and wall posts from facebook and display them on the page, at the moment this all works fine.....for one hour which is how long an access token lasts for.
I dont want to use access_tokens because the posts and profile picture are public and the point of this website is that it updates itself as i update my facebook profile
Can the facebook API do what i ask of it (which is to allow the photos to be pulled all the time without fear of expiration or even having to log in), or does the facebook API not allow that and is only really used for people wanting to use thair facebook account on your website to comment or like?
I hope i was clear enough...
to summerize, i would like to my website to pull pictures of my profile when people visit the website and not have to deal with access_tokens
If you configure your "Facebook app" as a "web application" you will get an AppID and an AppSecret. Using these values you can dynamically request a new token every time your page loads and use that token for all of your requests. I believe facebook will return the same token if you continue to request a new token before the old one has expired.
Here is a PHP function to achieve this:
public static function GetNewAccessToken(){
try{
$url = "https://graph.facebook.com/oauth/access_token?client_id=" . \Core\Config::FB_APPID . "&client_secret=" . \Core\Config::FB_APPSECRET . "&grant_type=client_credentials";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //to suppress the curl output
$response = curl_exec($ch);
curl_close($ch);
//response will be access_code=<CODE> so we need to strip off the access_code part at the front/
$token = "";
if (isset($response) && $response !== FALSE && substr($response, 0, 13) === "access_token="){
$token = substr($response, 13);
}
return $token;
}
catch(\Exception $exc){
return "";
}
}

Created album as a page but can't upload Photos using Graph API

I have searched intensively but I only can find similar topics but no one leads me to a working solution.
As my topic says i created an album as a page using following code.
$page_token = $facebook->api('/'.$page['id'],'GET',array('fields'=> 'access_token'));
$facebook->setAccessToken($page_token['access_token']);
$facebook->setFileUploadSupport(true);
$args = array(
'message'=> 'test album',
'name'=> 'Test Album'
);
$ch = curl_init();
$url = 'https://graph.facebook.com/'.$page['id'].'/albums?access_token='.$page_token['access_token'];//APP_ID.'|'.APP_SECRET;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
$newAlbum =json_decode($data,true);
$newAlbumID = $newAlbum['id'];
Ok that works so far, I am receiving an album ID. but when I look into the JSON object or look up graph.facebook.com/ALBUM_ID i receive nothing even on the page there is no album.
I have manage_pages read_stream photo_upload publish_stream create_event rsvp_event permissions. Creating an event on the page works pretty fine. What I am doing wrong?
When I try to upload some pictures and create albums it only works for my own profile but I would need it for my page. I don't understand why I am receiving an ID which isn't working when I look it up.
I hope you can help me guys.
Hello everybody I think I have solved my problem. At first it's important to know I have tested nad tried some weeks to finally get the solution.
As I said I was able to create Events and Questionings on a page. Today I compared creating an album on my profile with creating one on a page and I got to know that this also works fine for both.
But when I tried to upload a photo into the album or on the page wall it failed with this lovely exception: "An unexpected error has occurred. Please retry your request later"
Today I tried to remove some permissions. as you can see below
OLD --> define('PERMISSIONS', 'offline_access read_stream photo_upload user_photos friends_photos user_photo_video_tags publish_stream read_friendlists ads_management create_event user_online_presence friends_online_presence rsvp_event manage_pages');
NEW --> define('PERMISSIONS', 'photo_upload user_photos friends_photos publish_stream create_event manage_pages');
and now it works!

Is there a way to check if Facebook access token is still valid?

My site utilizes lifetime access tokens (offline_access). However, if the user changes his/her password, the access token gets reset. Is there a method to check if the current access token is valid before making calls to the Graph API? Thanks for your time.
Offline, without sending anything to facebook - I don't think so. The easiest way is probably to send a request to:
https://graph.facebook.com/me?access_token=...
Facebook also supports subscriptions for real-time updates, but I am not sure how to apply them to this situation.
If you want to know the token expiry time you can pass a open graph url using appid and token as below it will work .
https://graph.facebook.com/oauth/access_token_info?client_id=APPID&access_token=xxxxxxxxx
Basically, FB wants you to poll for it, or to detect the case and redirect the user to get a reauth to occur. Annoying, but official:
(Old, out of date link. See below) https://developers.facebook.com/blog/post/500/
Edit: Facebook changed their link structure without redirects. Not surprised.
https://developers.facebook.com/blog/post/2011/05/13/how-to--handle-expired-access-tokens/
You can check the token using the token debug service , take a look here
https://graph.facebook.com/debug_token?input_token=INPUT_TOKEN&access_token=ACCESS_TOKEN
https://developers.facebook.com/docs/howtos/login/debugging-access-tokens/
The real time updates would allow you to solve this problem, but it would be pretty complicated. Basically, you can subscribe to updates that will tell you 1) if the user removed the app or 2) if the user removed permissions. You could use this to store the current permissions of the faceboook user. This way, if the user removed your app you would know that the access token is expired.
Real time updates is actually facebooks recommended way of handling permissions. Many apps make api calls every time a page is loaded to check for permissions. This tends to be slow and unreliable.
I went through these posts, bud I found very good solutions like this:
GET graph.facebook.com/debug_token?
input_token={token-to-inspect}
&access_token={app_id}|{app_secret}
Response from this request provides you everything you need:
your app ID - this verifies that token is from your application
application name - which can be also checked
expires_at - token expiration time
is_valid - boolean for check up
user_id - which you can also compare and check
Just note that "|" sign must be there as a letter
//When user access token expires user must be logged in and renew the access token him self.it is a Facebook policy
//you can overcome this by sending email to users who have expired access token.
//create a table of successful sending to monitor sending process
//if any failure happened with the user an email is sent to him to ask him to activate there account again.with a link to your subscription page.
//and here is the code should be written on that page.
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$my_url = "YOUR_POST_LOGIN_URL";
// known valid access token stored in a database
$access_token = "YOUR_STORED_ACCESS_TOKEN";
$code = $_REQUEST["code"];
// If we get a code, it means that we have re-authed the user
//and can get a valid access_token.
if (isset($code)) {
$token_url="https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code . "&display=popup";
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
}
// Attempt to query the graph:
$graph_url = "https://graph.facebook.com/me?"
. "access_token=" . $access_token;
$response = curl_get_file_contents($graph_url);
$decoded_response = json_decode($response);
//Check for errors
if ($decoded_response->error) {
// check to see if this is an oAuth error:
if ($decoded_response->error->type== "OAuthException") {
// Retrieving a valid access token.
$dialog_url= "https://www.facebook.com/dialog/oauth?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode($my_url);
echo("<script> top.location.href='" . $dialog_url
. "'</script>");
}
else {
echo "other error has happened";
}
}
else {
// success
echo("success" . $decoded_response->name);
echo($access_token);
}
// note this wrapper function exists in order to circumvent PHP's
//strict obeying of HTTP error codes. In this case, Facebook
//returns error code 400 which PHP obeys and wipes out
//the response.
function curl_get_file_contents($URL) {
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c);
$err = curl_getinfo($c,CURLINFO_HTTP_CODE);
curl_close($c);
if ($contents) return $contents;
else return FALSE;
}
Offline - it is not possible
Ask that user has given permission or not:
https://graph.facebook.com/{facebook-id}/permissions?access_token={access-token}
If access token is invalid then it will give error:
{
error:{
message:"The access token could not be decrypted",
type:"OAuthException",
code:190
}
}
Otherwise it will give list of permission that user has given:
data:[
{
installed:1,
...... permission list.........
bookmarked:1
}
]
Updating this as things have changed since OP:
You can debug access tokens here: https://developers.facebook.com/tools/debug/accesstoken?version=v2.5&q={access_token}
Otto's answer of the facebook post seems to be the official response on this question, however it uses straight PHP instead of the SDK and also uses JS to resolve the issue instead of PHP. If you are using PHP to check for a valid session you often need a PHP method of ensuring a valid session in order to continue.
The following code checks for the me object with the graph API. If an exception is thrown it destroys* the current Facebook session.
try{
$facebook->api('/me');
}
catch( FacebookApiException $e ){
$facebook->destroySession();
}
This forces later graph calls to instantiate a new Facebook session. This at least gives you access to public data so that you can render pages do not require FB user permissions:
$facebook->api('/userName');
To reobtain user permission access the user will need to login to your app (this is distinct from being logged into Facebook itself). You can do this with JS or with PHP:
$facebook->getLoginUrl();
*Note the destroySession() call is not in a tagged release of the PHP SDK yet. Use the master branch or patch it in.