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

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.".

Related

Facebook Graph API (#190) This method must be called with a Page Access Token

I get data from the Facebook insights via Facebook Graph API more than year. And recently started all my requests (like {id}/insights) to return with an error: (#190) This method must be called with a Page Access Token.
But the Access token contains scopes manage_pages,read_insights.
Any ideas?
manage_pages,read_insights
This will give a user access_token , that u can use to manage pages & check insights,
But a page token became required for any /insights endpoint since 5th feb 2018
Use your manage_pages scope & user_token to get a Page access token
Send a get request to this endpoint
GET /{page-id}?fields=access_token
Output
{
"access_token": "{your-page-access-token}",
"id": "{page-id}"
}
You can use the returned access token to call /insights endpoint now.
As I cant add comment I'll write it here.
Field name is access_token which you can check here with your page id.
https://developers.facebook.com/tools/explorer/?method=GET&path=page-id%3Ffields%3Daccess_token&version=v2.12
For PHP
If you had your script in PHP, using Facebook SDK for PHP and now it brokes, you just need to retrieve token and pass it instead of access/refresh token you were using.
//Retrieve new 'page access token'.
$token = $fbApiClient -> get( "/{$pageId}?fields=access_token") -> getGraphNode()-> asArray();
//$q is your insights query which was working until now :(
//But with page acces token it will work again.
$response = $fbApiClient -> get( $q, $token['access_token']) -> getGraphEdge();
//(...) rest of script.
I think its easily adaptable to other languages too. Also you can (and propably should) store page access token and use it wherever you need, instead of retrieving it each time.

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

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.

Facebook PHP SDK: getting "long-lived" access token now that "offline_access" is deprecated

BASIC PROBLEM: I want my app to be able to make calls to the Facebook graph api about authorized users even while the user is away.
For example, I want the user (A) to authorize the app, then later I want user (B) to be able to use the app to view info about user (A)'s friends. Specifically: the "work" field. Yes, I am requesting those extended permissions (user_work_history, friends_work_history, etc). Currently my app has access to the logged-in user's friends work history, but not to any of the friends' work history of other users of the app.
Here's what I know already:
Adding offline_access to the scope parameter is the old way and it
no longer works.
The new way is with "long-lived" access tokens,
described here. These last for 60 days.
I need to exchange a normal access token to get the new extended token. The FB documentation says:
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
Here's what I don't know (and I'm hoping you can tell me):
How do I get the extended (aka "long-lived") access token using the Facebook PHP SDK? Currently, my code looks like this:
$facebook->getAccessToken();
Is there such a thing as this?:
$facebook->getExtendedAccessToken();
If not, is this what I should be doing?
$accessToken = $facebook->getAccessToken();
$extendedAccessToken = file_get_contents("https://graph.facebook.com/oauth/access_token?
client_id={$appId}&
client_secret={$secret}&
grant_type=fb_exchange_token&
fb_exchange_token={$accessToken}"
);
I've tried it and it doesn't work. I get this error:
Warning: file_get_contents(https://graph.facebook.com/oauth/access_token? client_id=#######& client_secret=#########& grant_type=fb_exchange_token& fb_exchange_token=##########) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in /...
Does it work any differently if I switch to FQL instead of the graph api? I've read through the Facebook documentation many times, but the PHP sdk is not thoroughly documented and I can't find any examples of how this should work.
I finally figured this out on my own. The answer is pretty anti-climactic. It appears that newly created apps get 60 day access tokens automatically. I'm not sure if this is dependent on enabling the "depricate offline_access" setting in the Migrations section of the app settings. Leave it on to be safe.
So at the time of writing this, you can use the PHP SDK as follows: $facebook->getAccessToken();
(The reason my app wasn't working as expected was unrelated to the expiration of the access token.)
Just one more thing, to get long-lived access token using PHP SDK you should call $facebook->setExtendedAccessToken(); before $facebook->getAccessToken();
In the last Facebook PHP SDK 3.2.0 you have a new function setExtendedAccessToken()
that you have to call before getAccessToken();
Like this:
$user = $facebook->getUser();
$facebook->setExtendedAccessToken(); //long-live access_token 60 days
$access_token = $facebook->getAccessToken();
Actually newly created apps only get a 60 day access token automatically if you are using a server side call. If you are using the client-side endpoint as shown above in the question, even new apps will still receive a short-term token initially. see: https://developers.facebook.com/docs/roadmap/completed-changes/offline-access-removal/
I had the same HTTP/1.1 400 Bad Request error that you had when using the New Endpoint and the problem was if you copy the code Facebook gives you exactly and paste it into your app, there are actually spaces in between the params, meaning there's unnecessary spaces in the url and it won't get called correctly when passed into file_get_contents() even though it works okay when pasted in the browser. This took me way too long to figure out. Hope this helps somebody! Here is my complete working code to get the extended access token out of the new endpoint (replace x's with your values):
$extend_url = "https://graph.facebook.com/oauth/access_token?client_id=xxxxxxxxxxxx&client_secret=xxxxxxxxxxxxxxxxxxxxxx&grant_type=fb_exchange_token&fb_exchange_token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$resp = file_get_contents($extend_url);
parse_str($resp,$output);
$extended_token = $output['access_token'];
echo $extended_token;
The selected answer is now outdated. Here are Facebook's instructions to swap a short-term token (provided in front-end) for a long-term token (server only):
https://developers.facebook.com/docs/facebook-login/access-tokens/refreshing/
Generate a Long-lived User or Page Access Token
You will need the following:
A valid User or Page Access Token
Your App ID
Your App Secret
Query the GET oath/access_token endpoint.
curl -i -X GET "https://graph.facebook.com/{graph-api-version}/oauth/access_token?
grant_type=fb_exchange_token
client_id={app-id}&
client_secret={app-secret}&
fb_exchange_token={your-access-token}"
Sample Response
{
"access_token":"{long-lived-access-token}",
"token_type": "bearer",
"expires_in": 5183944 //The number of seconds until the token expires
}

How to subscribe to real-time updates for a Facebook page's wall

Facebook's real-time updates docs now say that you can get the feed for a page:
You can subscribe to the page's feed in the same way you subscribe to
a user's feed - the subscription topic should be 'user' and the
subscription field should be 'feed'
My understanding of this is that I need to post to the graph API to subscribe as such:
curl -d \
"object=user&fields=feed&callback_url=$CALLBACKURL&verify_token=$SECRET" \
"https://graph.facebook.com/$PAGEID/subscriptions?access_token=$OAUTHTOKEN"
(This is a bash script.) Here $CALLBACKURL is set up correctly following their example code. (At least I think it's correct -- I can successfully add subscriptions with it.)
The $OAUTHTOKEN is the one for my Facebook App.
And the $PAGEID is the facebook object id of the page I'd like to get realtime updates for.
When I do this, the call appears to work -- no error message. My callback gets called. But I certainly don't get notified when something happens on the page's feed.
So what's missing? Does the page need to install the app whose oauth token I'm using? Or do I somehow need to get an oauth token for the page itself by logging in as the page?
I do not know if this can help you but I'll tell you where I am for real-time update page feed:
(permissions : manage_page,offline_access,read_stream)
your application must be linked to the page (then install the application but not required to have a tab ex. create tab https://graph.facebook.com/PAGE_ID/tabs?app_id=APP_ID&method=POST&access_token=PAGE_ACCESS_TOKEN and delete tab
TAB_ID=PAGE_ID.'/tabs/app_'.APP_ID;
https://graph.facebook.com/TAB_ID?method=DELETE&access_token=PAGE_ACCESS_TOKEN)
function page_access_token($page_id,$access_token){
$page_token_url="https://graph.facebook.com/" .
$page_id . "?fields=access_token&" . $access_token;
$response = file_get_contents($page_token_url);
$resp_obj = json_decode($response,true);
$page_access_token = $resp_obj['access_token'];
return $page_access_token;
}
function page_tabs_create($page_id,$app_id,$page_access_token){
$page_settings_url = "https://graph.facebook.com/" .
$page_id . "/tabs?app_id=".$app_id."&method=POST&access_token=" . $page_access_token;
$response = file_get_contents($page_settings_url);
$resp_obj = json_decode($response,true);
return $resp_obj;
}
function page_tabs_delete($tab_id,$page_access_token){
$page_settings_url = "https://graph.facebook.com/".$tab_id."?method=DELETE&access_token=" . $page_access_token;
$response = file_get_contents($page_settings_url);
$resp_obj = json_decode($response,true);
return $resp_obj;
}
Subscription: to subscribe must be like a "user" and therefore object = user fields = feed but you have to add new fields because otherwise it receives the comments and likes the wall so you must add "status" in order to receive the articles posted (my problem is to get other content such as links I have managed to add "link" as fields but I am not receiving notifications when a link is posted)
$param = array ('access_token' => $ access_token,
'object' => 'user',
'fields' => 'feed, status, link'
'callback_url' => 'http:// ******** fbcallback.php'
'verify_token' =>'***********',
'include_values' => 'true');
POST
https://graph.facebook.com/APP_ID/subscriptions
my English is not very good but I hope it will help you, on my side I'm still looking for really all updates to the wall (links, video ...)
I have been researching on this and i am getting the pushes for pages too.
while subscribing make sure that object = user and fields = feed, status is present.
Make sure that application is added to your page, then only you will receive the update.
Response received from facebook is as below :-
{"entry":[{"id":"*******","uid":"*****","time":1332940650,"changed_fields":["status"]}],"object":"user"}
where **** is my pageId.
The above push is received on adding a new post , as you can see the changed_feild is status , but when we post on wall the changed_fields comes as feed. Below link helped me in receiving pushes for the page.
http://bugs.developers.facebook.net/show_bug.cgi?id=18048
Firstly, subscription to real-time update for page/feed doesn't work.
See: http://bugs.developers.facebook.net/show_bug.cgi?id=18048
Does the page need to install the app whose oauth token I'm using?
Yes
Or do I somehow need to get an oauth token for the page itself by logging in as the page?
If i correctly understand you, you need only app access_token
https://graph.facebook.com/oauth/access_token?client_id=your_app_id&client_secret=your_secret&grant_type=client_credentials
I first started reading the docs about real-time updates thinking that it could delivery the actual data. But, as I realized, that's not the purpose.
Real-time updates are just to tell you that something has changed, and once it happens, you can call the api with the conventional method.
Also, seems like there's an error on this part the subscription topic should be 'user' and the subscription field should be 'feed'. The subscription topic, actually, should be 'page'. (Have you thought the same?)
And by subscribe on page feed as the same as user feed, means that you can get update notifications, not the data itself.
Not sure if this is a common mistake, but I'm posting it just in case.
--
Currently I'm working on a data mining tool that will need real-time updates. But first, I'm focused on the data itself, so I can't post any examples yet. (I'll edit this answer when implementing this part)
What I can say about your issue is:
1) Look that your $PAGEID isn't correct. Actually it's your APPID instead.
2) After subscribing, have your subscription appeared on the list when calling https://graph.facebook.com/<app-id>/subscriptions?access_token=... ?
3) With user subscription, does it work? Or is it just with pages?
For this you need to set up an endpoint URL that receives both HTTP GET (for subscription verification) and POST (for actual change data) requests from Facebook.
Then you should make a POST to the graph API url https://graph.facebook.com/<app-id>/subscriptions?access_token=<access_token> to subscribe, and be ready to handle the verification request.
Then to list subscriptions, just perform a GET request on the same url, https://graph.facebook.com/<app-id>/subscriptions?access_token=<access_token>, which returns a JSON-encoded content that lists your subscriptions, up to one per object type.
Before you start waiting for the notifications you should check if the URL is actually being hit or not by FB
Check The Output of Following:
"https://graph.facebook.com/".FACEBOOK_APP_ID."/subscriptions?".$appToken."&client_secret=".FACEBOOK_SECRET;
This shall return the callback_url if set correctly !

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