How do I remove the Facebook login prompt when displaying images pulled with graph api on a page? - facebook

I recently started playing around with Facebook graph API and wanted to integrate images pulled from my Facebook page to display on my website. I have the images displaying properly but my problem is whenever anyone tries to view the page they are asked to log into Facebook first. Is there any way to display the images without prompting the user to log into Facebook?
Here is what I am using to make the session:
$app_id = 'id';
$app_secret = 'secret';
$redirect = 'my webpage';
// init app with app id and secret
FacebookSession::setDefaultApplication($app_id,$app_secret);
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper($redirect);
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
}
Any help would be appreciated.

Step one: familiarize yourself with the API. Read the docs, and play around with the Graph API Explorer
Step two: the code you provided has nothing to do with what you are trying to achieve (displaying page photos). That code is basically the getting started code used in the docs. If you need help, post the relevant code.
Step three: as mentioned by #CBroe, authenticating the visitor is not needed to display photos from a page. What you might want to explore:
The page admin authenticating your app with the right permissions (maybe manage_pages)
with the user access token you just got, you extend it to long-lived one
then you query the API to get a page access token that won't expire
you store this access token and query the API to get the relevant data and store it (GET /{PAGE-ID}/photos or GET /{PAGE-ID}/albums ... etc)
you show the stored data to your visitors
Notes:
Do not make these calls on client-side ... i.e. reveal your page access token, since you can do this in the backend.
Use the realtime updates to get notified when you should query the API and get new photos instead of periodically querying the API to pull new photos, or even worst, querying the API on each user visit.

Related

How to login user from inside Facebook Page Tab and get access_token on server side to post a carousel to the feed?

I have a Page Tab facebook app. I want to post to users timeline from it.
After login on client side with javascript sdk (I use angularjs module for that Ciul/angular-facebook (sorry, cannot post github link here)):
https://gist.github.com/Sevavietl/7e363fdfd0e714a12a43
I retrieve access_token on server side and trying to post a carousel to the users feed:
https://gist.github.com/Sevavietl/cec5fa434837312adfd3
I have two problems:
While first call I get
Graph returned an error: (#210) Param id must be a page.
After browsing, I found that this can be caused by wrong token usage. Not user_access_token. But I login the user on the client side.
And for next calls I get
Graph returned an error: This authorization code has been used.
Again, after browsing, I found that token can be used only once in order to be OAuth compliant.
Please, advise me how to do this right?
Thank you in advance.
Best regards,
Vsevolod
After spending some time on this, I am writing my solution, as it was not really obvious, at least for me. But, actually, all info is present in the documentation.
Starting with problem number 2: And for next calls I get Graph returned an error: This authorization code has been used.
As it was mentioned in the comments, I indeed was confusing access_token with authorization code. As I understand in really simplified form, the mechanism is:
When you login with facebook-javascript-sdk it writes authorization code to cookies.
Then on the server side you can retrieve access_token from javaScriptHelper available in facebook-php-sdk. This helper has getAccessToken() method, which retrieves access_token using authorization code from cookies. This is the place where I was confused. I was trying to use getAccessToken() on every request. As requests were made with AJAX the authorization code was not changed, and as you can use it only once I was getting an error. The solution to this was pointed in many places on the Internet, but somehow I was able to misunderstand this.
Here is the code excerpt that uses sessions to store access_token, and uses getAccessToken() method only if access_token is not set in the session.
$fb = new Facebook([
'app_id' => $widget->app_id,
'app_secret' => $widget->app_secret,
'default_graph_version' => 'v2.5',
]);
$helper = $fb->getJavaScriptHelper();
if ($request->session()->has('facebook_access_token')) {
$accessToken = $request->session()->get('facebook_access_token');
} else {
$accessToken = $helper->getAccessToken();
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
$request->session()->put('facebook_access_token', (string) $longLivedAccessToken);
$request->session()->save();
}
if ($accessToken) {
$fb->setDefaultAccessToken($accessToken);
} else {
die('No Access Token');
}
I use Laravel, so the session handling is not framework agnostic. This code is only for example, it is better to create service and move logic there.
Now. About the first problem: While first call I get Graph returned an error: (#210) Param id must be a page.
Again I was confusing two things '{user-id}/feed' and '{page-id}/feed'. My aim was to post a carousel with images and links. To create a carousel you have to provide child_attachments in the fields array. While you can send a Post like this to '{page-id}/feed', you cannot do so for '{user-id}/feed'. So at the moment you cannot post a carousel to users feed.
So when Graph Api was getting a Post data applicable for '{page-id}/feed', it was assuming that I have passed the {page-id}. And when getting the {user-id} instead, the Graph Api yelled back "(#210) Param id must be a page.".

Generate access token Instagram API, without having to log in?

So I am building a restaurant app and one of the features I want is to allow a user of the app to see photos from a particular restaurant's Instagram account.
And I want a user to be able to see this without having to login to their Instagram account, so they shouldn't even need an Instagram account for this to work.
So I have read this answer How can I get a user's media from Instagram without authenticating as a user?
And I tried what it said and used the client_id(which I recieved when I registered my app using my personal Instagram account), but I still get an error back saying :
{
meta: {
error_type: "OAuthAccessTokenException",
code: 400,
error_message: "The access_token provided is invalid."
}
}
The endpoint I am trying to hit is :
https://api.instagram.com/v1/users/search?q=[USERNAME]&client_id=[CLIENT ID]
So do I absolutely need an access token for this to work(and thus have to enforce a user to log in) ?
If I do, then is there way to generate an access token somehow without forcing the user log in?
I believe there is a way around this, as the popular dating app Tinder has this desired functionality I am looking for, as it allows you to see photos from people's Instagram account without having to log in! (I have just verified this 5 minutes ago!)
Any help on this would be much appreciated.
Thanks.
Edit April 2018: After facebook privacy case this endpoint is immediately put out of service. It seems we need to parse the JSON embedded in <script> tag directly within the profile page:
<script type="text/javascript">window._sharedData = {"activity_counts":...
Any better ideas are welcome.
You can use the most recent link
GET https://www.instagram.com/{username}/?__a=1
to get latest 20 posts in JSON format. Hope you put this to good use.
edit: other ways aren't valid anymore:
https://www.instagram.com/{username}/media/
Instagram used to allow most API requests with just client_id and without access_token, the apps registered back in the day still work with way, thats how some apps are able to show instagram photos without user login.
Instagram has changes the API specification, so new apps will have to get access_token, older apps will have to change before June 2016.
One way you can work around this is by using access_token generated by your account to access photos. Login locally and get access_token, use this for all API calls, it should not change, unless u change password,if it expires, regenerate and update in your server.
Since the endpoints don't exist anymore I switched to a PHP library -
https://github.com/pgrimaud/instagram-user-feed
Installed this lib with composer:
composer require pgrimaud/instagram-user-feed "^4.0"
To get a feed object -
$cache = new Instagram\Storage\CacheManager();
$api = new Instagram\Api($cache);
$api->setUserName('myvetbox');
$feed = $api->getFeed();
Example of how to use that object -
foreach ($feed->medias as $key => $value) {
echo '<li><img src="'.$value->thumbnailSrc.'"></li>';
}

MVC5 Facebook get users photos

I am building a website app in MVC5 that allows a user to login using Facebook/Twitter. Once they are logged in we will look through their photos for ones marked with a certain hashtag.
I have the login working for both FB and Twitter - and using Linq2Twitter I can get the and post photos.
However with Facebook I am having some problems. My understanding with Facebook is that after the login I have to make a second call to https://graph.facebook.com/oauth/access_token in order to get a short lived access token.
However this call requires a "code" and a returnUri. I am unsure what this code is or how to get it, and what return URI to use.
My startup.Auth.cs looks like this
var facebookOptions = new FacebookAuthenticationOptions();
facebookOptions.Scope.Add("user_photos");
facebookOptions.AppId = ConfigurationManager.AppSettings["facebookAppId"];
facebookOptions.AppSecret = ConfigurationManager.AppSettings["facebookAppSecret"];
app.UseFacebookAuthentication(facebookOptions);
And everything logs in fine and I end back at ExternalLoginCallback
So where do I go from here. How do I find this code and what returnUri do I use in order to get the access code.
Once I have this access code I plan to call (https://developers.facebook.com/docs/graph-api/reference/v2.1/user/photos)
Hopefully I am going about this the correct way and my question makes sense
Many thanks.
Okay - This solves my problem
http://blogs.msdn.com/b/webdev/archive/2013/10/16/get-more-information-from-social-providers-used-in-the-vs-2013-project-templates.aspx

Facebook: Permanent Page Access Token?

I work on a project that has Facebook pages as one of its data sources. It imports some data from it periodically with no GUI involved. Then we use a web app to show the data we already have.
Not all the information is public. This means I have to get access to the data once and then keep it. However, I don't know the process and I haven't found a good tutorial on that yet. I guess I need an access_token, how can I get it from the user, step by step? The user is an admin of a facebook page, will he have to add some FB app of ours to the page?
EDIT: Thanks #phwd for the tip. I made a tutorial how to get a permanent page access token, even with offline_access no longer existing.
EDIT: I just found out it's answered here: Long-lasting FB access-token for server to pull FB page info
Following the instructions laid out in Facebook's extending page tokens documentation I was able to get a page access token that does not expire.
I suggest using the Graph API Explorer for all of these steps except where otherwise stated.
0. Create Facebook App
If you already have an app, skip to step 1.
Go to My Apps.
Click "+ Add a New App".
Setup a website app.
You don't need to change its permissions or anything. You just need an app that wont go away before you're done with your access token.
1. Get User Short-Lived Access Token
Go to the Graph API Explorer.
Select the application you want to get the access token for (in the "Application" drop-down menu, not the "My Apps" menu).
Click "Get Token" > "Get User Access Token".
In the pop-up, under the "Extended Permissions" tab, check "manage_pages".
Click "Get Access Token".
Grant access from a Facebook account that has access to manage the target page. Note that if this user loses access the final, never-expiring access token will likely stop working.
The token that appears in the "Access Token" field is your short-lived access token.
2. Generate Long-Lived Access Token
Following these instructions from the Facebook docs, make a GET request to
https://graph.facebook.com/v2.10/oauth/access_token?grant_type=fb_exchange_token&client_id={app_id}&client_secret={app_secret}&fb_exchange_token={short_lived_token}
entering in your app's ID and secret and the short-lived token generated in the previous step.
You cannot use the Graph API Explorer. For some reason it gets stuck on this request. I think it's because the response isn't JSON, but a query string. Since it's a GET request, you can just go to the URL in your browser.
The response should look like this:
{"access_token":"ABC123","token_type":"bearer","expires_in":5183791}
"ABC123" will be your long-lived access token. You can put it into the Access Token Debugger to verify. Under "Expires" it should have something like "2 months".
3. Get User ID
Using the long-lived access token, make a GET request to
https://graph.facebook.com/v2.10/me?access_token={long_lived_access_token}
The id field is your account ID. You'll need it for the next step.
4. Get Permanent Page Access Token
Make a GET request to
https://graph.facebook.com/v2.10/{account_id}/accounts?access_token={long_lived_access_token}
The JSON response should have a data field under which is an array of items the user has access to. Find the item for the page you want the permanent access token from. The access_token field should have your permanent access token. Copy it and test it in the Access Token Debugger. Under "Expires" it should say "Never".
Here's my solution using only Graph API Explorer & Access Token Debugger:
Graph API Explorer:
Select your App from the top right dropdown menu
Select "Get User Access Token" from dropdown (right of access token field) and select needed permissions
Copy user access token
Access Token Debugger:
Paste copied token and press "Debug"
Press "Extend Access Token" and copy the generated long-lived user access token
Graph API Explorer:
Paste copied token into the "Access Token" field
Make a GET request with "PAGE_ID?fields=access_token"
Find the permanent page access token in the response (node "access_token")
(Optional) Access Token Debugger:
Paste the permanent token and press "Debug"
"Expires" should be "Never"
(Tested with API Version 2.9-2.11, 3.0-3.1)
In addition to the recommended steps in the Vlasec answer, you can use:
Graph API explorer to make the queries, e.g. /{pageId}?fields=access_token&access_token=THE_ACCESS_TOKEN_PROVIDED_BY_GRAPH_EXPLORER
Access Token Debugger to get information about the access token.
Another PHP answer to make lives easier. Updated for Facebook Graph API 2.9 . Just fill 'er up and load.
<?php
$args=[
/*-- Permanent access token generator for Facebook Graph API version 2.9 --*/
//Instructions: Fill Input Area below and then run this php file
/*-- INPUT AREA START --*/
'usertoken'=>'',
'appid'=>'',
'appsecret'=>'',
'pageid'=>''
/*-- INPUT AREA END --*/
];
echo 'Permanent access token is: <input type="text" value="'.generate_token($args).'"></input>';
function generate_token($args){
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.9/oauth/access_token?grant_type=fb_exchange_token&client_id={$args['appid']}&client_secret={$args['appsecret']}&fb_exchange_token={$args['usertoken']}")); // get long-lived token
$longtoken=$r->access_token;
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.9/me?access_token={$longtoken}")); // get user id
$userid=$r->id;
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.9/{$userid}?fields=access_token&access_token={$longtoken}")); // get permanent token
if($r->id==$args['pageid']) $finaltoken=$r->access_token;
return $finaltoken;
}
?>
Addendum: (alternative)
Graph 2.9 onwards , you can skip much of the hassle of getting a long access token by simply clicking Extend Access Token at the bottom of the Access Token Debugger tool, after having debugged a short access token. Armed with information about pageid and longlivedtoken, run the php below to get permanent access token.
<?php
$args=[
/*-- Permanent access token generator for Facebook Graph API version 2.9 --*/
//Instructions: Fill Input Area below and then run this php file
/*-- INPUT AREA START --*/
'longlivedtoken'=>'',
'pageid'=>''
/*-- INPUT AREA END --*/
];
echo 'Permanent access token is: <input type="text" value="'.generate_token($args).'"></input>';
function generate_token($args){
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.9/{$args['pageid']}?fields=access_token&access_token={$args['longlivedtoken']}"));
return $r->access_token;
}
?>
Although the second code saves you a lot of hassle, I recommend running the first php code unless you are in a lot of hurry because it cross-checks pageid and userid. The second code will not end up working if you choose user token by mistake.
Thanks to dw1 and Rob
I made a PHP script to make it easier. Create an app. In the Graph API Explorer select your App and get a user token with manage_pages and publish_pages permission. Find your page's ID at the bottom of its About page. Fill in the config vars and run the script.
<?php
$args=[
'usertoken'=>'',
'appid'=>'',
'appsecret'=>'',
'pageid'=>''
];
echo generate_token($args);
function generate_token($args){
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/oauth/access_token?grant_type=fb_exchange_token&client_id={$args['appid']}&client_secret={$args['appsecret']}&fb_exchange_token={$args['usertoken']}")); // get long-lived token
$longtoken=$r->access_token;
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/me?access_token={$longtoken}")); // get user id
$userid=$r->id;
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/{$userid}/accounts?access_token={$longtoken}")); // get permanent token
foreach($r->data as $d) if($d->id==$args['pageid']) return $d->access_token;
}
I tried these steps:
https://developers.facebook.com/docs/marketing-api/access#graph-api-explorer
Get Permanent Page Access Token
Go to Graph API Explorer
Select your app in Application
Paste the long-lived access token into Access Token
Next to Access Token, choose the page you want an access token for. The access token appears as a new string.
Click i to see the properties of this access token
Click “Open in Access Token Tool” button again to open the “Access Token Debugger” tool to check the properties
One Tip, it only worked for me when the page language is english.
As all the earlier answers are old, and due to ever changing policies from facebook other mentioned answers might not work for permanent tokens.
After lot of debugging ,I am able to get the never expires token using following steps:
Graph API Explorer:
Open graph api explorer and select the page for which you want to obtain the access token in the right-hand drop-down box, click on the Send button and copy the resulting access_token, which will be a short-lived token
Copy that token and paste it in access token debugger and press debug button, in the bottom of the page click on extend token link, which will extend your token expiry to two months.
Copy that extended token and paste it in the below url with your pageId, and hit in the browser url
https://graph.facebook.com/{page_id}?fields=access_token&access_token={long_lived_token}
U can check that token in access token debugger tool and verify Expires field , which will show never.
Thats it
Most of the answers above now doesn't give permanent token, they only extend it to 2 months. Here's how I got it:
From Graph Explorer tool, select the relevant permissions and get the short lived page access token.
Go to debugger tool and paste your access token. Then, click on 'Extend Token' button at the bottom of the page.
Copy the the extended token and use it in this API:
https://graph.facebook.com/v2.10/me?fields=access_token&access_token=<extended_access_token>
This should return you the permanent access token. You can verify it in debugger tool, the expires at field should say 'Never'.
If you are requesting only page data, then you can use a page access token. You will only have to authorize the user once to get the user access token; extend it to two months validity then request the token for the page. This is all explained in Scenario 5. Note, that the acquired page access token is only valid for as long as the user access token is valid.
While getting the permanent access token I followed above 5 steps as Donut mentioned. However in the 5th step while generating permanent access token its returning the long lived access token(Which is valid for 2 months) not permanent access token(which never expires). what I noticed is the current version of Graph API is V2.5. If you trying to get the permanent access token with V2.5 its giving long lived access token.Try to make API call with V2.2(if you are not able to change version in the graph api explorer,hit the API call https://graph.facebook.com/v2.2/{account_id}/accounts?access_token={long_lived_access_token} in the new tab with V2.2) then you will get the permanent access token(Which never expires)
In addition to mentioned methods it is worth mentioning that for server-to-server applications, you can also use this form of permanent access token:
app_id|app_secret
This type of access token is called App Token. It can generally be used to call Graph API and query for public nodes within your application back-end.
It is mentioned here: https://developers.facebook.com/docs/facebook-login/access-tokens
If you have facebook's app, then you can try with app-id & app-secret.
Like :
access_token={your-app_id}|{your-app_secret}
it will don't require to change the token frequently.
Thanks to #donut I managed to get the never expiring access token in JavaScript.
// Initialize exchange
fetch('https://graph.facebook.com/v3.2/oauth/access_token?grant_type=fb_exchange_token&client_id={client_id}&client_secret={client_secret}&fb_exchange_token={short_lived_token}')
.then((data) => {
return data.json();
})
.then((json) => {
// Get the user data
fetch(`https://graph.facebook.com/v3.2/me?access_token=${json.access_token}`)
.then((data) => {
return data.json();
})
.then((userData) => {
// Get the page token
fetch(`https://graph.facebook.com/v3.2/${userData.id}/accounts?access_token=${json.access_token}`)
.then((data) => {
return data.json();
})
.then((pageToken) => {
// Save the access token somewhere
// You'll need it at later point
})
.catch((err) => console.error(err))
})
.catch((err) => console.error(err))
})
.catch((err) => {
console.error(err);
})
and then I used the saved access token like this
fetch('https://graph.facebook.com/v3.2/{page_id}?fields=fan_count&access_token={token_from_the_data_array}')
.then((data) => {
return data.json();
})
.then((json) => {
// Do stuff
})
.catch((err) => console.error(err))
I hope that someone can trim this code because it's kinda messy but it was the only way I could think of.
Application request limit reached (#4) - FB API v2.1 and greater
This answer led me to the "ultimate answer for us" and so it is very much related so I am appending it here. While it's related to the above it is different and it seems FB has simplified the process some.
Our sharing counts on our site stopped worked when FB rolled over the api to v 2.1. In our case we already had a FB APP and we were NOT using the FB login. So what we needed to do was get a FB APP Token to make the new requests. This is as of Aug. 23 2016.
Go to: https://developers.facebook.com/tools/explorer
Select the api version and then use GET and paste the following:
/oauth/access_token?client_id={app-id}&client_secret={app-secret}&grant_type=client_credentials
You will want to go grab your app id and your app secret from your app page. Main FB Apps developer page
Run the graph query and you will see:
{
"access_token": "app-id|app-token",
"token_type": "bearer"
}
Where "app-id" and "app-token" will be your app id from your FB app page and the generated FB App HASH you just received.
Next go test your new APP access token: FB Access Token tester
You should see, by pasting the "app-token" into the token tester, a single app based token without an expiration date/time.
In our case we are using the FB js sdk so we changed our call to be like so (please note this ONLY gets the share count and not the share and comment count combined like it used to be):
FB.api(
'/','GET',{
// this is our FB app token for our FB app
access_token: FBAppToken,
"id":"{$shareUrl}","fields":"id,og_object{ engagement }"
}
This is now working properly. This took a lot of searching and an official bug report with FB to confirm that we have to start making tokenized requests to the FB api. As an aside I did request that they (FB) add a clue to the Error code (#4) that mentions the tokenized request.
I just got another report from one of our devs that our FB comment count is broken as well due to the new need for tokenized requests so I will update this accordingly.
Many of these examples do not work, not sure if it's because of 2.9v coming out but I was banging my head. Anyways I took #dw1 version and modified it a little with the help of #KFunk video and got this working for me for 2.9. Hope this helps.
$args=[
/*-- Permanent access token generator for Facebook Graph API version 2.9 --*/
//Instructions: Fill Input Area below and then run this php file
/*-- INPUT AREA START --*/
'usertoken'=>'',
'appid'=>'',
'appsecret'=>'',
'pageid'=>''
/*-- INPUT AREA END --*/
];
echo 'Permanent access token is: <input type="text" value="'.generate_token($args).'"></input>';
function generate_token($args){
$r = json_decode(file_get_contents("https://graph.facebook.com/v2.9/oauth/access_token?grant_type=fb_exchange_token&client_id={$args['appid']}&client_secret={$args['appsecret']}&fb_exchange_token={$args['usertoken']}")); // get long-lived token
$longtoken=$r->access_token;
$r=json_decode(file_get_contents("https://graph.facebook.com/{$args['pageid']}?fields=access_token&access_token={$longtoken}")); // get user id
$finaltoken=$r->access_token;
return $finaltoken;
}
As of April 2020, my previously-permanent page tokens started expiring sometime between 1 and 12 hours. I started using user tokens with the manage_pages permission to achieve the previous goal (polling a Page's Events). Those tokens appear to be permanent.
I created a python script based on info found in this post, hosted at github.com/k-funk/facebook_permanent_token, to keep track of what params are required, and which methods of obtaining a permanent token are working.
I created a small NodeJS script based on donut's answer. Store the following in a file called get-facebook-access-token.js:
const fetch = require('node-fetch');
const open = require('open');
const api_version = 'v9.0';
const app_id = '';
const app_secret = '';
const short_lived_token = '';
const page_name = '';
const getPermanentAccessToken = async () => {
try {
const long_lived_access_token = await getLongLivedAccessToken();
const account_id = await getAccountId(long_lived_access_token);
const permanent_page_access_token = await getPermanentPageAccessToken(
long_lived_access_token,
account_id
);
checkExpiration(permanent_page_access_token);
} catch (reason) {
console.error(reason);
}
};
const getLongLivedAccessToken = async () => {
const response = await fetch(
`https://graph.facebook.com/${api_version}/oauth/access_token?grant_type=fb_exchange_token&client_id=${app_id}&client_secret=${app_secret}&fb_exchange_token=${short_lived_token}`
);
const body = await response.json();
return body.access_token;
};
const getAccountId = async (long_lived_access_token) => {
const response = await fetch(
`https://graph.facebook.com/${api_version}/me?access_token=${long_lived_access_token}`
);
const body = await response.json();
return body.id;
};
const getPermanentPageAccessToken = async (
long_lived_access_token,
account_id
) => {
const response = await fetch(
`https://graph.facebook.com/${api_version}/${account_id}/accounts?access_token=${long_lived_access_token}`
);
const body = await response.json();
const page_item = body.data.find(item => item.name === page_name);
return page_item.access_token;
};
const checkExpiration = (access_token) => {
open(`https://developers.facebook.com/tools/debug/accesstoken/?access_token=${access_token}&version=${api_version}`);
}
getPermanentAccessToken();
Fill in the constants and then run:
npm install node-fetch
npm install open
node get-facebook-access-token.js
After running the script a page is opened in the browser that shows the token and how long it is valid.
I found this answer which refers to this tool which really helped a lot.
I hope this answer is still valid when you read this.

Facebook status update with PHP

My requirement was to update members status from my site, i am also thinking about displaying their friends photos and their last status update.
I have looked all over the docs and cant decide which works for my need. RESTful API, JavaScript API, FQL, XFBML, FBML, FBJS ?? whcin one works best? or best way?
It should be like, when they first go to the page,there will be nothing but a login option. when they click on it, a pop up should appear and when they are authorized, we display a text area to post update. Here, i wanted to show their friends pics too
when they came back later, they should able to post right away, must not ask for login again.
Can some one help me with the code?? I dont expect you to write everything, get the friends pic and their last update into a PHP array would be nice.
Many thanks
If u need to update users data stored at ur database so u will use the facebook API to check user signed in and get his data. i have an ifram application at facebook and i am using C# code (asp.net application) and when the user request the application i authenticate that he is signed in to facebook and check if he is already exist in my database? if not so i get his information(by using facebook API) and add the user in my data base and each time he visits the application i update his information.
With respect to his friends i get all facebook ids of the user friends and then loop these IDs and get the pic of each ID.
Download Facebook Developer Toolkit that enables u communicate with facebook and use facebook API to get user information.
hope that is will help u
Visit my application in facebook and u will see these features at the following link :
http://apps.facebook.com/hanggame/
Getting the session Key :
protected void Page_Load(object sender, EventArgs e)
{
//Facebook code for integration with facebook users:
_fbService.ApplicationKey = "Application Key";
_fbService.Secret = "Secret Key";
_fbService.IsDesktopApplication = false;
string sessionKey = (string)Session["Facebook_session_key"];
if (Session["Facebook_userId"] != null)
userId = (long)Session["Facebook_userId"];
// When the user uses the Facebook login page, the redirect back here will will have the auth_token in the query params
string authToken = Request.QueryString["auth_token"];
if (!String.IsNullOrEmpty(sessionKey))
{
_fbService.SessionKey = sessionKey;
_fbService.uid = userId;
}
else if (!String.IsNullOrEmpty(authToken))
{
_fbService.CreateSession(authToken);
Session["Facebook_session_key"] = _fbService.SessionKey;
Session["Facebook_userId"] = _fbService.uid;
Session["Facebook_session_expires"] = _fbService.SessionExpires;
}
else
{
Response.Redirect(#"http://www.Facebook.com/login.php?api_key=" + _fbService.ApplicationKey + #"&v=1.0");
}
userId = _fbService.uid;
//End of Facebook code
}