Facebook access user info if they are not logged in - facebook

Ok, so what I am trying to do is a bit odd, so I can't find anything that gives me even a remote idea about how to do this.
I need to access my personal profile posts:
FB.api("/" + myPersonalUserId + "/feed", {limit: 5}, function(data){
console.log(data);
// do stuff with my user info
});
in order to display them on my personal webite, similar to a dynamic blog. But I want it to automatically retrieve these posts without my having to be signed in on each computer that wants to view my site.
Before you get sidetracked on the init, I am using an app and app id that my personal user account has verified access to all permissions.
I know it will require the use of an access token, but how do I get a valid access token without being logged into that computer?
Honestly, I'm starting to question if it is even possible, but if anyone knows how I could accomplish this, that would be awesome!

The best way to achieve this is to just cache the data in your own database and refresh it whenver the user uses your App again.
If that´s not good enough, you have to generate and store an Extended User Token. How to create one is explained in the docs:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
Extended User Tokens are valid for 60 days, there is no User Token that is valid forever. And you should never use Tokens directly on the client, because some user could just copy it from the source. Tokens are meant to be secret, so use it on the server only. You don´t need to use the PHP SDK, a simple CURL call to the Graph API will do it:
https://graph.facebook.com/[your-app-scoped-id]/feed?access_token=[extended-user-token]

Ok, so I found a solution similar to the one above, but offers a permanent access token.
first, build a url:
url = 'https://graph.facebook.com/v2.5/' + {app user Id, not public Id} + '/feed';
url += '?access_token=' + {app Id} + '|' + {app secret};
url += '&fields=id,name,message,full_picture,created_time'; // these scopes should be approved by corresponding user
url += '&limit=5';
then run it by calling a simple ajax request. These variables should be served from the server through ajax, not hardcoded on the client

Related

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>';
}

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.

Can we get a facebook access token by providing email and password in the code?

I would like to get the photo urls from the from this album:
https://graph.facebook.com/175758929145317/photos
If you access it without providing an access token, then you will get empty data:
{
"data": [
]
}
But if you first generate an access token here:
http://developers.facebook.com/tools/explorer?method=GET&path=175758929145317%2Fphotos
And then you append it to the url like this, you can get the data:
https://graph.facebook.com/175758929145317/photos?access_token=your_access_token
However, this access token cannot be used forever, it will expire.
I would like to dynamically take the photo urls from https://graph.facebook.com/175758929145317/photos and display the images on a webpage, the person who views this webpage does not need to have a facebook account.
So every time the webpage is viewed, I am thinking about if it's possible to simply use my facebook account to login (by hardcoding the email and password) and then obtain a new access token so that I can get the photo urls.
Is this possible? Or is there a better solution to my problem? (I cannot ask the album owner to change his album to public)
it's not possible, you cannot authenticate in FB using hardcoded (or stored) login/password - as per Facebook policy:
I. Features and Functionality
...
3 - You must not include functionality that proxies, requests or
collects Facebook usernames or passwords.
what you can do instead:
Get (and then extend) token for yourself (see scenario 4 in this document: https://developers.facebook.com/roadmap/offline-access-removal/). That extended token should be good for 60 days - and then you might be able to extend it again.
Try to get those photos using APPLICATION token - and if it works, then the token is good forever: https://developers.facebook.com/docs/authentication/applications/

Extend auth token without refreshing the page

Users want to use my facebook app for many hours without refreshing the browser.
But token expires in 2 hours. Now I ask users to refresh the page but that's annoying.
I don't want to ask offline access permissions because it will scare some users.
The best solution will be somehow "relogin" and get new token without refreshing the page.
Is it possible?
I would subscribe to the expiry trigger (I think this is authResponseChange), then automate another login check. It won't be a perfect solution as it could trigger a pop up (if they have logged out for example) automatically, which a lot of browsers may block. You could instead, when the token expires, check if they will need to complete a pop up, and display a notification on your page somewhere saying 'Facebook needs your attention to continue', then only launch the pop up from their response, which would stop the pop up being blocked.
FB.Event.subscribe('auth.authResponseChange', function(response) {
// do something with response
FB.login(){
// refresh their session - or use JS to display a notification they can
// click to prevent pop up issues
}
});
An algorithm to workout on this
Ask for permission from the user
Save the token
Periodically check for an access token is near to expire or not
If its in verse of expiry, embed some dummy iframe, which redirects to the facebook homepage. - Extend auth token without refreshing the page
This should refresh the token. You might need to generate another token or continue with the same. Whatever be required, can be done without refreshing the page.
Have you thought of using ajax? After two hours you will check, if user is still active. If so, you send axax request to URL, where his session details will be updated. example:
$(document).ready(function(){
setInterval('update_session()', 5500000);
})
update_session(){
$.post({
URL: ..., // script to update session on server
data:{ /* username, password */ },
})
}
and the server-side just takes username and password from post or and runs relogin.
Try acquiring tokens with the offline_access permission.
I presume, guess this is not possible,FB architecture would not allow it. And why is offline_access such a problem!!!!!!...anyway offline_access is the best optimal solution I guess....
Unfortunately I believe this is impossible by design (if you mean for it to happen without user intervention). If the user is still logged in to Facebook you can redirect the top-level page to Facebook and it will bounce you right back with a new code (as it sounds like you are doing already), but that is only possible because of the Facebook cookie that it can check. If you try to do anything from your server, it will be rejected because that cookie will not accompany the request. Same goes for trying to make a call to facebook from javascript -- since your code is running in a different domain, the cookie will not accompany the call and Facebook will reject it. The only way that Facebook can even know who the user is, and that they are still logged in, is to see that cookie. And the only way that can happen is if the browser itself is redirected to the facebook.com domain.
It's worth mentioning also that Facebook has blocked the only logical workaround, i.e. loading the oauth url in an iframe. If you try it you will see that they detect the page is being loaded in an iframe and output a page with a link on it which does a top-level redirect to break out of the frame. So not only does this approach not work, it's clear that Facebook has specifically made it impossible as part of their architecture.
Edit: If what you mean to do is not avoid the refresh altogether but just have it happen automatically when a new token is needed, you can do something like this:
$status=0;
$data=#file_get_contents("https://graph.facebook.com/me?access_token=$token");
foreach ($http_response_header as $rh) if (substr($rh, 0, 4)=='HTTP') list(,$status,)=explode(' ', $rh, 3);
if ($status==200)
{
//token is good, proceed
}
else
{
//token is expired, get new one
$fburl="http://www.facebook.com/dialog/oauth?client_id=APP_ID&redirect_uri=".urlencode('http://apps.facebook.com/yourapp/thispage.php');
echo "<html>\n<body>\n<script>top.location='$fburl';</script>\n</body>\n</html>\n";
exit;
}
This is assuming you have something before this code that will process a signed_request parameter if it is present and assign a value to $token (either explicit code of your own or the appropriate SDK entries). The shown code can then be used anywhere you need to check if $token is still valid before proceeding.
If you get the access_token without specifying any expiry to them they will not expire ..
atleast not till the time user either changes his Fb credentials or de registers your application ..
I presume you are using the iframe signed_request parameter to get your access token. One method of achieving what you require is to use the oAuth 2.0 method of aquiring an access token. This is more prolonged in the first instance; your server and Facebook's have to exchange credentials which can be slow, but it means that you will be given a code that can be exchanged for an access token regularly, meaning your server can maintain the session periodically (probably from an ajax call from the client). You would then pass this new access_token to the client, and use it in your dialog call for your requests (gifts).
Hope that helps.
Spabby
Have a look at https://developers.facebook.com/docs/offline-access-deprecation/#extend_token
basically you extend the token with
https://graph.facebook.com/oauth/access_token?
client_id=APP_ID&
client_secret=APP_SECRET&
grant_type=fb_exchange_token&
fb_exchange_token=EXISTING_ACCESS_TOKEN
that will give you new token with new expiry time (it should be 60d but I'm noticing similar bug like described here https://developers.facebook.com/bugs/347831145255847/?browse=search_4f5b6e51b18170786854060 )

Facebook access_token invalid?

I'm attempting to use the new Graph API Facebook recently released, but I can't seem to get it to work correctly.
I've gone through the steps, and after the /authorize call, I receive an access_token:
access_token=109002049121898|nhKwSTJVPbUZ5JYyIH3opCBQMf8.
When I attempt to use that token I get:
{
"error": {
"type": "QueryParseException",
"message": "An active access token must be used to query information about the current user."
}
}
I'm stumped as too why...
-AC
When using your Facebook Application's token
If you're using the me alias as in https://graph.facebook.com/me/ but your token is acquired for a Facebook Application, then "me" isn't you anymore - it's the app or maybe nothing. Anyway, that's not your intention for the app to interact with itself.
In this case you will want to interact with your personal user account from an app. What you need to do (after giving the app the permissions it requests in the UI when it asks) is find your facebook userid # and put it in place of "me" to access your own info. e.g. Mark Zuckerberg's facebook userid is 4 so he is https://graph.facebook.com/4/
The alias me only works if you're you! Sometimes it's hard to remember who the current user is when programming facebook (i.e. you, the Page, the App, etc) because we're accustomed to using the facebook UI as ourselves most of the time. From a programming standpoint it depends on what the acquired token represents.
A great blog post that always helps correct me is Ben Biddington | Facebook Graph API — getting access tokens.
same thing here. I followed Ben Biddington's blog to get the access token. Same error when trying to use it. Facebook's OAuth implementation doesn't follow the spec completely, i am fine with it as long as the doc is clear, which obviously is not the case here. Aslo, it would be nice if the userid and username are returned with the access token.
Just to clarify -- after you call
https://graph.facebook.com/oauth/authorize?
you should receive a CODE which, in conjunction with your CLIENT_ID and CLIENT_SECRET (assuming you have registered your application) can be exchanged for an access_token at
https://graph.facebook.com/oauth/access_token?
If this is indeed how you came by your ACCESS_TOKEN, you should then be able to request
https://graph.facebook.com/me/
Adding type parameter returns the auth_token for the application level, so it is better to OMIT it. What worked for me, after countless attempts and combinations, is using the same redirect_url parameter in the call to /oath/access_token as was used in the call to /oath/authorize.
So the full sequence to authorize your app on someone's behalf is:
1. call or redirect to:
"https://graph.facebook.com/oauth/authorize?client_id=" + my_clientId + "&scope=publish_stream,offline_access,manage_pages" + "&redirect_uri=" + "http://my_redirect_url?blah"
2. in the page located at the return_url above, issue a request or what ever else to this url:
"https://graph.facebook.com/oauth/access_token?client_id=" + client_id + "&client_secret=" + secret + "&code=" + Request.QueryString["code"] + "&redirect_uri=" + "http://my_redirect_url?blah"
I've been having the exact same problem. A couple of things I've done to resolve it:
Try it all out in the browser first to make sure the urls are correct at each stage
Ensure the redirect url is identical, not just equivalent. Parameters in the same order, encoding the same
Don't use the type=client_cred, or anything else for that matter
Encode any ampersands in the redirect_url (but not the rest of the url) e.g. http://example.com/fb?foo=234%26bar=567. This one caused me the most issues. When the callback page was run, only the url before the first ampersand was included, as the ampersand was assumed to be part of the url for graph.facebook.com, not part of the redirect_url. I was then getting the values from the querystring to put in the redirect_url for the second call, but they weren't there. Once I encoded the ampersands they appeared correctly.
Don't have any empty values in you encoded querystring parameters (e.g. ?foo=%26bar=123)
I want to point out what has sort of been said on Ben Biddington's blog, and what I noticed from looking at the "malformed" access_token in the initial question. Others have said similar things in this thread, but I want to be explicit.
The token is not actually malformed, but rather a token that allows you to do actions on behalf of the APP, not the user. This is the token you'd use if you wanted to get all of the users of the app, or view insights for your app, etc, with the requests typically coming from your server, not the client. This type of token is gained by using the type=client_cred parameter. If you want to do things on behalf of the user, do not specify type=client_cred, and make sure you specify the following parameters in your call to http://graph.facebook.com/oauth/access_token:
'client_id' => APP_ID
'redirect_uri' => REDIRECT_URI
'client_secret' => APP_SECRET
'code' => $_GET['code']
I've written this as key-value pairs of a PHP array, but I think you get the point. The code GET value is gained after making the initial call to http://graph.facebook.com/oauth/authorize with the following parameters:
'client_id' => APP_ID
'redirect_uri' => "http://your.connect.url/some/endpoint"
I hope this helps! What the Facebook docs say, but don't say well, is that getting an access_token is a two-request process.
I actually noticed that if your return uri doesn't have a slash on the end you have issues. I'm currently testing in the browser and return_uri=https://mydomain.com doesn't work but return_uri=https://mydomain.com/ does work. If I use the first I get "Error validating verification code."
This seems a bit odd, but I prolly just missed a word in the spec/instructions some where. Did lose two hours of my life to it though.
I had the same problem, but getting rid of type=client_cred and making sure that the redirect_uri parameter is the same when making the authorize and the access_token call fixed the issue.
I had the same issue in IE8 only.
The solution for me was sending the access_token in the API request.
Something like this:
FB.api('/me/friends?access_token=<YOUR TOKEN>
I obtained my token through PHP like this:
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => '<API_ID>',
'secret' => '<SECRET>',
'cookie' => false,
));
$session = $facebook->getSession();
$token = $session['access_token'];