Facebook API - Retrieve my own albums and photos - facebook

I'm trying to retrieve my albums and photos from facebook using the Facebook api for php. I've created an app now i have my AppId and my AppSecretId. I don't need any login window because I want to display my own photos, not the ones from any other user, but everytime I try to retrieve them, I receive this message "An active access token must be used to query information about the current user."
I know that if I were going to show the photos from another users, then I should ask for their login and then generate the access token, but this is not the case.
I have tried generating an App token and tried to use this as an access token but it's not working either.
This is the code I'm using:
require_once("facebook/facebook.php");
try{
$facebook = new Facebook(array(
'appId' => '<APPID>',
'secret' => '<SECRETID>',
'cookie' => true
));
echo($facebook->getUser());
if(is_null($facebook->getUser()))
{
header("Location:{$facebook->getLoginUrl(array('req_perms' => 'user_status,publish_stream,user_photos'))}");
exit;
}
$me = $facebook->api('/me');
$albums = $facebook->api('/me/albums', array('access_token' => $facebook->getAccessToken()));
echo($albums);
}catch(Exception $e){
echo "THIS IS THE ERROR: " . $e->getMessage();
die;
}
I hope you can help me with this. Thank you so much!!

The easiest way to generate a Facebook access token for your personal account is to visit their Graph API Explorer. It will automatically generate an access token that you can copy/paste into your code.
https://developers.facebook.com/tools/explorer
Additionally, you can use the 'Get Access Token' button on that page to request an access token with specific permissions.

Related

Return User Token instead of Access Token

I'm using the php-sdk to create a session upon login of my site thru fb. Upon login, the user will be redirected to a file called fb_redirect.php. On that page, there is the following:
$facebook = new Facebook(array('appId' => '123456789',
'secret' => '123456789',
'cookie' => true));
$access_token = $facebook->getAccessToken();
//$facebook->setAccessToken($access_token); // you do not need to set the token if there is one, so this should be conditional to if your switching tokens or setting a token from an external sdk.
When the
$access_token
is echoed here, it display the user token. But, on another page, I need to take advantage of the publish_actions permission that my app has requested and post a custom action to the user's timeline. For that to happen, I need the access token to be set to the user token. But, for some reason, on other pages the $access_token is always set to the access token and not the user token. How can I manually set it back to the user token?
If you use the server-side flow, then you have to save it somewhere (a cookie, or a server-side session, or a DB table), and load it back when the user comes back.
Quick and dirty method, this does not handle expiry.
if (!$_SESSION['fb_YourAppID_access_token']) {
$access_token = $facebook->getAccessToken();
if ($access_token) {
$_SESSION['your_token'] = $access_token;
}
}else{
$access_token = $_SESSION['fb_YourAppID_access_token'];
$_SESSION['your_token'] = $access_token;
}
this will look for existing token in browser, if not found it will ask the php sdk what the current token is, if there is a token in the sdk, it sets your session token to the current access token, if not it will save it blank.

How to grant fan page permission to an app

Hi i have an application i got offline_access and manage_pages perms
i can upload photos by this code:
$phototoken='AAAAABya***sZAJ';
$photo_details = array(
'access_token' => $phototoken
);
$photo_details['image'] = '#' . realpath($img);
$upload_photo = $facebook->api('/me/photos', 'post', $photo_details);
}
but when i change my password my token will die and my app won't be able to access the to fan page am i right
http://smileychatcodes.com/facebook-smiley-chat-codes/
so how these sites access to fan pages as offline?
Changing your password will always invalidate the User Access Token, however as explained here you can get a long-lived User access token which will allow you to generate an infinite-life Page Access Token.

Creating facebook apprequests

I'm trying to send a message from an app to a user when a specific event happens. Right now I have this code
$param = array(
'message' => 'XYZ shared a file with you',
'data' => 'additiona_string_data',
'access_token' => $facebook->getAccessToken(),
);
$tmp = $facebook->api("/$uid/apprequests", "POST", $param);
but I always get Uncaught OAuthException: (#2) Failed to create any app request thrown
I don't know where is the problem.
You should read the requests documentation.
In there is an explination about two different types of requests.
user initiated (with the request dialog )
app generated (with the Graph API)
What you need is the app generated requests, that means you'll need the apps access token and not the users.
I assume that you are using the users access token because you did not include the initiation of the facebook object in your code sample and have probably verified the user already hence the getAccessToken() call will return the users access token and not the applications access token.
I'm a little confused as to "I'm trying to send a message from an app to a user when a specific event happens. Right now I have this code" means.
Sending an email to a user when someone posts on their wall
Sending an event invite to a user
Sending an app invite to a user
Writing on a users wall when something happens like 'XYZ shared a file with you'.
To answer
You need email and read_stream permissions of the user. Monitor his wall using the RealTime Updates and then email him using your server SMTP.
See http://developers.facebook.com/docs/reference/api/event/#invited on how to create an event invite
As #Lix pointed out, see https://developers.facebook.com/docs/channels/#requests
You should accomplish this using the new Open Graph object/actions. See this example: https://developers.facebook.com/docs/beta/opengraph/tutorial/
You can receive Facebook app access token via:
https://graph.facebook.com/oauth/access_token?client_id=FB_APP_ID&client_secret=FB_APP_SECRET&grant_type=client_credentials
Working code sample to post app-to-user request using Facebook PHP SDK (add error handling where required):
$facebook = new Facebook(array(
'appId' => FB_APP_ID,
'secret' => FB_APP_SECRET,
));
$token_url = "https://graph.facebook.com/oauth/access_token?" ."client_id=" .
FB_APP_ID ."&client_secret=" . FB_APP_SECRET ."&grant_type=client_credentials";
$result = file_get_contents($token_url);
$splt = explode('=', $result);
$app_access_token =$splt[1];
$facebook->setAccessToken($app_access_token);
$args = array(
'message' => 'MESSAGE_TEXT',
);
$result = $facebook->api('/USER_ID/apprequests','POST', $args);

Upload to specific Fan Page Album without user perms

I'm trying to replicate the same functionality as someone else has already achieved on this page here:
http://www.facebook.com/PowerPhotoUploader?sk=app_152884604799537
am not bothered about the forced like fangate part, can do that no probs.
I need to achieve this without requesting any user perms the same way they have
I've got close, but not quite right yet.
Have created a test album on this page: http://www.facebook.com/pages/Demo-Album-Upload/227979503931257?sk=app_153866511376478
The code I have is uploading my specified image, however it is ignoring the album id I input and instead, uploading to an album on my own profile.
Code so far is:
<?php
$app_id = "XXXXXXXXXXX";
$app_secret = "XXXXXXXXXXXX";
require 'facebook.php';
$facebook = new Facebook(array( 'appId' => $app_id, 'secret' => $app_secret, 'cookie' => true, 'fileUpload' => true,));
$signed_request = $facebook->getSignedRequest();
//print_r ($signed_request);
$page_id = $signed_request["page"]["id"];
//Upload To Page Album
$facebook->setFileUploadSupport(true);
$album_id ='59125';
$file_path ='image2.gif';
$args = array('message' => 'Photo Caption');
$args['image'] = '#' . realpath($file_path);
$data = $facebook->api('/'.$album_id.'/photos', 'post', $args);
print_r($data);
?>
Have already read through a lot of forum material, have set the filuploadsupport, set file upload to true, but most of the info I can find so far reuires perms & access token, however sample above has managed to achieve with neither - any thoughts?
Regards Tony
Tony the trick here is that you only need one access token, not a new one for each user. The idea is that the user is not posting to the page, you are posting to the page, so you do not need an access token from the user. However since this is a secure call to Facebook you still need to provide an access token that has the ability to publish to the page.
The simplest route to get an access token that you can use would be to manually give the application the manage_pages and offline_access permissions for your account. Then just grab the access token for for your account and use it for all calls.

Facebook access_token: how do I get it once the user accepted my app?

When a user visits my site which contains a facebook app the first time, it requires him to allow it and he gets promted to do that, then I get the code which I can convert to an access_token. So far so good.
But how do I get the token once the user has already visited the site?
As long as this token form the first time is active everything is fine. But how do I get another token when the user had already allowed the app a week ago and is only visiting my page again?
Now that Facebook is migrating to Oauth2, the cookie created by the Javascript is different. I got it to work for me and added it to a fork of the FGraph plugin for Rails - https://github.com/imme5150/fgraph
One of the tricks is that when you request the access_token from the "code" parameter stored in the cookie, you have to pass in "redirect_uri", but you want it to be blank.
On the client-side flow, you can redirect the user to the OAuth dialog with the permissions in the scope parameter. If the user already accepted your App and permissions he will be redirected to your "redirect_uri" with the access_token in the URI fragment, otherwise the needed permissions will be prompt.
https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&scope=email,read_stream&response_type=token
On the server-side flow you should have the "code" so you can redeem it for an access_token on the OAuth endpoint:
https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&redirect_uri=YOUR_URLclient_secret=YOUR_APP_SECRET&code=THE_CODE_FROM_ABOVE
Documentation: https://developers.facebook.com/docs/authentication/
I use the cookie method to store the access_token on the user's computer.
FB.init({appId: 'your app id', status: true, cookie: true, xfbml: true});
In your facebook.php file you need to set cookieSupport to true then:
private $cookieSupport = true;
Or use the get_facebook_cookie function found here: Single sign-on with the JavaScript SDK
The access_token is then stored in a cookie called "fbs_APPID" (with expire). If you want the cookie to last more then a couple of hours you need to ask the extended permission 'offline_access':
Enables your application to perform authorized requests on behalf of the user at any time. By default, most access tokens expire after a short time period to ensure applications only make requests on behalf of the user when the are actively using the application. This permission makes the access token returned by our OAuth endpoint long-lived.
you can also use this:
$access_token = $facebook->getAccessToken();
https://developers.facebook.com/docs/reference/php/facebook-getAccessToken/
using php
session_start();
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_APP_SECRET,
'cookie' => true,
'domain' => 'example.com'
));
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
$_SESSION['me'] = $me;
$_SESSION['uid'] = $uid;
$_SESSION['session'] = $session;
} catch (FacebookApiException $e) {
error_log($e);
}
}
you can reference the access_token via $_SESSION['session']['access_token'] within your app,, for more theres tutorials over at fbdevtutorials.com