Get photos with graph api - facebook

I've read a lot of tutorials/articles/questions here about this, as well as trying to find something useful in the fb documentation.
So far I've made no progress at all myself so any input would be greatly appreciated, I'm simply trying to access a list of my photos but all I get is an empty array.
I know I've added more req_perms than I need probably, I just copied the ones from a "working tutorial" that didnt work for me, and after reading a thread here I also added user_photo_video_tags because that had worked for the thread poster (again, not me).
I've gotten the dialog to allow photos sharing my photos with my app, login works without any problems, the access token I get seem to be correct, after logging in I have visited:
https://graph.facebook.com/me/photos?access_token= and the token, and gotten an empty array, if I wasnt logged in or the access_token wasnt linked to my app there would be some error, but all I get is an empty array.
Thanks in advance for any input.
Thanks to Chaney Blu I was able to validate my permissions:
{
"data": [
{
"installed": 1,
"status_update": 1,
"photo_upload": 1,
"video_upload": 1,
"create_note": 1,
"share_item": 1,
"publish_stream": 1
}
]
}
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once 'library/facebook.php';
$app_id = "xxxxxxxxxxxxxxxx";
$app_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
$loginLink = $facebook->getLoginUrl(array(
'scope' => 'user_status,publish_stream,user_photos,user_photo_video_tags'
));
$logOutLink = $facebook->getLogoutUrl();
$user = $facebook->getUser();
if ($user) {
try {
// User logged in, get token
$token = $facebook->getAccessToken();
//var_dump($token); dumped successfully
// Get public profile info
$user_profile = $facebook->api('/me');
//var_dump($user_profile); dumped successfully
$photos = $facebook->api('/me/photos?access_token=' . $token);
var_dump($photos); // Empty array, BAH!
} catch (FacebookApiException $e) {
$user = null;
}
}
?>
Click here to login if you aren't autoredirected<br /><br /><br />
Click here to logout

Not sure if this is the problem, but try this. It appears you're using the latest PHP SDK. In your getLoginUrl(); calls, try changing 'req_perms' to 'scope'.
Like this:
$loginLink = $facebook->getLoginUrl(array(
'scope' => 'user_status,publish_stream,user_photos,user_photo_video_tags'
));
You can verify that you've authorized the correct permissions by visiting https://graph.facebook.com/me/permissions/?access_token=XXXX

After testing some other permissions I noticed facebook weren't updating the permissions to my token, even when logging out of the app, logging in again and accepting new permissions nothing changed when I looked at the Graph permissions link I got from Chaney Blu.
I used that link to verify the token from facebooks graph api page http://developers.facebook.com/docs/reference/api/ and noticed that token had access to user_photos but not my token.
Going into my facebook settings and removing the app made facebook update my permissions the next time I signed into the app.
Thanks to Chaney Blu for putting me on the right track. Would vote you up if I had the reputation.

Related

CodeIgniter and Facebook Connect

I am trying to integrate my Codeigniter website with the Facebook PHP SDK. What I want to do is let a user share an article from my site on their facebook wall, if they are logged into a facebook account. My library appears to load correctly, but everytime I try to do something, I get some kind of error... primarily with the auth. getUser does not appear to return the correct results. I set up my facebook application and set the config vars for my library, but no luck. It says I am not logged into facebook. When I click on the "login" anchor, the link takes me to the same page, but with the facebook url, and doesn't ask me to login with the app. Here's my code:
function facebook($article_id){
$config = array(
'appId' => '276870792431073',
'secret' => '8d49eee575413fb9a8063d22f65dbf6a'
);
$this->load->library('facebook', $config);
$user = $this->facebook->getUser();
if($user){
try {
$user_profile = $this->facebook->api('/me');
} catch (FacebookApiException $e){
error_log($e);
$user = null;
}
}
if($user){
$article = $this->article->fetch_article($article_id);
$config = array(
'message' => 'I just read an '.anchor('articles/'.url_title($article['title']).'/'.$article_id, 'article').' on '.anchor('', 'TrackTheOutbreak.com').'!',
);
$this->facebook->api('/me/feed', 'post', $config);
} else {
$data['MESSAGE_TITLE'] = 'Authentication Error';
$data['MESSAGE_TEXT'] = 'You must be logged into an existing Facebook account to use this feature. Click '.anchor($this->facebook->getLoginUrl(), 'here').' to login.';
$this->parser->parse('error_body.tpl', $data);
}
}
In order to access a users information and post anything to their wall you first need to get a access token from them. To do that you need to make sure that you have gained their permission through Facebook's FB_login (and then Open Graph). I would double check with this guide and make sure that you have everything set up properly to post to their timeline.
https://developers.facebook.com/docs/reference/javascript/FB.login/
I hope this helps

facebook php-sdk providing same functionality as javascript FB.getLoginStatus

I am using javascript sdk to know if user is login and connected to our web-site' application by using FB.getLoginStatus() function.
I want to know if php-sdk provides me details about the user logged into facebook.
If user is logged in facebook and connected to our application, i have to make them to directly logged into our site.
How can this be done using php sdk.
Thanks in advance.
You can do the following:
$user_details=$fb->api_client->users_getInfo($fb_user, array('last_name','first_name','pic_square'));
And yes they do have a similar thing to the FB.getLoginStatus() :)
$params = array(
'ok_session' => 'https://www.myapp.com/',
'no_user' => 'https://www.myapp.com/no_user',
'no_session' => 'https://www.myapp.com/no_session',
);
$next_url = $facebook->getLoginStatusUrl($params);
Found it here: https://developers.facebook.com/docs/reference/php/facebook-getLoginStatusUrl/
Just check the Example/Usage at the GitHub-Page:
https://github.com/facebook/facebook-php-sdk
according to documentation ( https://github.com/facebook/facebook-php-sdk ), after doing:
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();
To check if the user is still logged in on facebook (kind of FB.getLoginStatus) you need to:
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;
}
}
As noted by #DMCS this function should be used:
http://developers.facebook.com/docs/reference/php/facebook-getLoginStatusUrl/
You generate an url: $next_url = $facebook->getLoginStatusUrl();
redirect the user to this url: header('Location: '.$next_url);
the user will be returned by FB with session information (POST) about the login status
the SDK will parse the return $_POST info
use $facebook->getUser(); to get the userid (if logged in)
So far so good. The only problem is, this function (point 4) is broken since the transition to oAuth2.0 by Facebook, see also this bug report:
http://developers.facebook.com/bugs/295348980494364
So please let FB know that you have the same issue by adding a reproduction.
Cheers!

Facebook status update code fails to update wall

I got the sample code from Facebook to post a message. At first it worked fine. The next day I tried to clean up the code and it stopped working. I brought back the sample code from Facebook, to take out all my changes, and it still did not work.
I put in print statements to follow the code.
$user_id is false, so it displayes a login in. The login in no longer goes to a login in screen. It calls my return url, which then sees $user_id as being false and diplays the login in again.
I did notice when my call back was being called, I had the following values:
v?state=452c9492a3d51962909f5e000bcb0965
and code
code=AQDucDgsdc3lZFVN2MC3Oj2oB0n1LT4FjOrG3MbgwL4uhh--LS-mRdtjU-6oSUZxsR6UhTKuUDVn3hrasJAe5r1I6ksIDJz1nnTo1mjCqEInJKvQ2qK5A-N3_Nt5buGLqsirb8ccg21N4nWVWkk_iRePwX9f68qK1j-2O6E_USpKvRJeNP3bcwLBiTBJpDVu7aA#=
I was wondering maybe when I was trying to clean up the code and kept running it, Facebook flagged my app as spamming? I posted 26 posts to my wall - is that too many? And how would I check if my app has been flagged as a spammy app?
This is the sample code I used
<?
// Remember to copy files from the SDK's src/ directory to a
// directory in your application on the server, such as php-sdk/
require_once('facebook.php');
$config = array(
'appId' => 'myappid',
'secret' => 'mysecret',
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
?>
<html>
<head></head>
<body>
<?
if($user_id) {
print ("tryinmg to do a poast");
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$ret_obj = $facebook->api('/me/feed', 'POST',
array(
'link' => 'www.example.com',
'message' => 'Posting with the PHP SDK!'
));
echo '<pre>Post ID: ' . $ret_obj['id'] . '</pre>';
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
print ("face book exception log in");
$login_url = $facebook->getLoginUrl( array(
'scope' => 'publish_stream'
));
echo 'Please login.';
error_log($e->getType());
error_log($e->getMessage());
}
// Give the user a logout link
echo '<br />logout';
} else {
print ("no user login in do login");
// No user, so print a link for the user to login
// To post to a user's wall, we need publish_stream permission
// We'll use the current URL as the redirect_uri, so we don't
// need to specify it here
$login_url = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
echo 'Please login.';
}
?>
</body>
</html>
Naturally, Facebook has a limit for the number of post per day your app can make to a user wall. And FB have policy for user to report spammy apps as well.
The exact maximum number of posts depends on your application FB ranking. In my experience, 26 posts on a user wall is near the limit for new application.
If that is the case, you should receive the error message from Facebook, which says something like "you have reached limit of posts..."
P/s: It seems you need time to refactoring your question, though. If I have not met this situation before, I won't understand your question.

How to login with OFFLINE_ACCESS using the new Facebook PHP SDK 3.0.0?

with the old (2.x) SDK I used this to log someone with offline_access:
$session = array
(
'uid' => $userdata['fb_uid'],
'sig' => $userdata['fb_sig'],
'access_token' => $userdata['fb_access_token']
);
$facebook->setSession($session);
In the new SDK this function doesnt exist anymore. I think I need to login using:
setPersistentData($key, $value)
but this function is protected and I dont know what 'code' is? Do I need this to log the user in or not? And what's going on with 'sig'? Don't I need this anymore?
Hope someone already figured this out because the documentation really doesn't help!
With the Facebook PHP SDK v3 (see on github), it is pretty simple. To log someone with the offline_access permission, you ask it when your generate the login URL. Here is how you do that.
Get the offline access token
First you check if the user is logged in or not :
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
// The access token we have is not valid
$user = null;
}
}
If he is not, you generate the "Login with Facebook" URL asking for the offline_access permission :
if (!$user) {
$args['scope'] = 'offline_access';
$loginUrl = $facebook->getLoginUrl($args);
}
And then display the link in your template :
<?php if (!$user): ?>
Login with Facebook
<?php endif ?>
Then you can retrieve the offline access token and store it. To get it, call :
$facebook->getAccessToken()
Use the offline access token
To use the offline access token when the user is not logged in :
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$facebook->setAccessToken("...");
And now you can make API calls for this user :
$user_profile = $facebook->api('/me');
Hope that helps !
With PHP SDK 2.0 (I guess), I just use it like
$data = $facebook->api( '/me', 'GET', array( 'access_token' => $userdata['fb_access_token'] ) );
This should work with the newer one to as it seems to be more of a clean approach than rather setting up sessions by ourself. Can you try?
Quentin's answer is pretty nice but incomplete, I think. It works nice, but I for example getUser() isn't working in that time because userId (which is getUser() returning) is cached.
I have created a new method to clear all caches and save it persistently.
public function setPersistentAccessToken($access_token) {
$this->setAccessToken($access_token);
$this->user = $this->getUserFromAccessToken();
$this->setPersistentData('user_id', $this->user);
$this->setPersistentData('access_token', $access_token);
return $this;
}

problem extended permission using php sdk

I am developing a facebook application. I am not sure about getting extended permission from the user. I have seen a code related to this but it is not working well. The code has the problem that if there is a new user and comes to application,, he will be asked for all extended permissions to authorize. But one he authorize and i again add some extra extended permission and want to get that data, the pop window will not be displayed and i cannot access the user data of that newly added permission. I am using the following code for this
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxx',
'cookie' => true,
));
session = $facebook->getSession();
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'email,publish_stream,offline_access,sms,user_location,friends_birthday'
)
);
$fbme=null;
if (!$session) {
echo "top.location.href = '$loginUrl';";
exit;
}
else {
try {
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo "top.location.href = '$loginUrl';";
exit;
}
}
Now if any user comes on this point he will be asked for all permission and I can get data for all those permission. But if i add new extended permission, the user that has already authorized my application will not be asked for new permission and I cannot get the data for newly added permission.
I think if you got the extended permission then facebook will not ask for the same again when that user login to your application after some time.You can see the application that you authorized in the application page.
So to ask the permission again from same user he/she must remove the permission or remove the application from his/her account.
And if the user already give permission to your application then you can use that access token.Check this