Facebook GRAPH API, php SDK problem - php

it's weird this morning all my facebook applications don't work anymore. And when I use the graph API using request like : "graph.facebook.com/me"
I got :
{
"error": {
"type": "OAuthException",
"message": "An active access token must be used to query information about the current user."
}
}
Any idea?

Facebook did a developer update the past couple days..
http://developers.facebook.com/blog/post/518/
We had problems with the API key on older versions of the sdk, check that.

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.

You need to create an app so that you can get an appId and secret. Then you can create a facebook object like so:
$fb = new Facebook(array(
'appId' => $appId,
'secret' => $secret,
'cookie' => $cookie
));
and get the access token with $fb->getAccessToken(); this can then be appended to your graph api call url, and it should work.

when you click on facebook button, after login one cookie is generated with fbs_(token_access). by which it understands that you are logged in. may be because you are going directly you dont have sufficient access to get json encoded data..
this can be the problem for you.. make sure when you are loggedd in,cookie is generated ..

As the message states, you need to provide a valid access token. If you aren't providing one, then it obviously is the problem, as you need to have one, even when accessing your own information. If you are providing one, and it gives that error, then the token is not valid, which may be because it has expired or been revoked.

Related

Restful API - Check if Facebook access token is valid and authorized to use APP

I am building a restful API (PHP) to serve iOS and Android applications and I would like to implement facebook login on both apps.
The flaw is like the following :
Clients ( ios or Android ) login with facebook and send an access_token to the restful api
verify if the access_token is authorized to use the application
If token is valid, get user data from graph.
Merge accounts and generate token for different queries.
For security purpose to avoid getting random tokens thatthey don't belong to my APP, I would like to make a test call to check if a token is authorized and valid or not ?
I know many similar questions might be already answered but none of them really give me the right answer and I don't really have experience with facebook graph.
I found this solution :
https://graph.facebook.com/oauth/access_token?client_id=APP_ID&client_secret=SECRET_APP_ID&grant_type=fb_exchange_token&fb_exchange_token=ACCESS_TOKEN
This works somehow .. it whether give me an error, or an access token (string format not JSON) and I am not sure if this is the best way to test or not.
Note: I am still in early stage of development, if you have any suggestion on my flow please let me know, I might be doing things the wrong way ?
What works for my application (code with explanation below)...
$fb = new Facebook\Facebook([
'app_id' => 'XXXXXXX',
'app_secret' => 'XXXXXXX',
'default_graph_version' => 'v2.5',
]);
// My app pulls users' access tokens & page ID from a database here and stores in $fb_access_token & $fb_page_id variables
$fb_access_token = 'YOU OR YOUR USERS ACCESS TOKEN GOES HERE';
$fb_page_id = 'ID OF FACEBOOK PAGE OR USER';
$fb->setDefaultAccessToken($fb_access_token);
// CHECK IF ACCESS TOKEN SITLL WORKS
try{
$page = $fb->get('/'.$fb_page_id.'?fields=id', $fb_access_token);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
$graphError = 'Yes';
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
$sdkError = 'Yes';
}
// IF ACCESS TOKEN STILL WORKS...CONTINUE WITH SCRIPT. THIS PREVENTS ACCESS TOKEN FAILURE FROM BREAKING SCRIPT.
if(!isset($graphError) && !isset($sdkError)){
// CONTINUE WITH SCRIPT
}
Explanation: you are taking the access token in question, and attempting to make a GET Request to the Facebook API. Only continue with the rest of your script IF there are NO ERRORS.
You could also add an ELSE statement at the end to maybe redirect the user to a page where they can re-authenticate their account/access token, depending on what your app is doing.
My app uses a couple of WHILE Loops to go through my database of users, and depending on certain column/cell values, it POSTS to their Facebook page for them...
Before this solution...when the Loop came across an invalid Access Token, it "broke" and did not execute the script for the rows following the "unauthenticated user" because it was making a failed request.
Hope this helps someone!
“Random” tokens would not work anyway. (Tokens issued by Facebook are encrypted, so the API can tell whether a token is genuine, or just "random". At most you'd need to worry about what a user possible could using a token for a different app, or one they themselves granted more permissions than you asked them for.)
Just request the user details using the access token you got - if it is not valid because someone tried to “fake” it, then the API response will tell you so.
The docs have a chapter about securing API requests, go check that out as well: https://developers.facebook.com/docs/graph-api/securing-requests

How do I get the App Access Token via the Facebook PHP SDK?

I'm trying to retrieve the app access token of my app in order to post notifications, but for some reason, it doesn't work. Here's the code:
$AppParams = array(
'client_id' => 'myclientid',
'&client_secret' => 'myclientsecret',
'&grant_type' =>'client_credentials'
);
$AppToken = $facebook->api('oauth/access_token?', 'GET', $AppParams);
I also replaced the first part with the full oauth/accesstoken link, but then it returns me general information about oauth and their facebook page, which I do not want.
I did nearly the same thing in C# and there it works.
You don't really have to request an application access token. You can simply assemble one yourself.
An application access token is formatted like this:
app_id|app_secret
That's the application's id, a pipe character | and the application secret.
Make sure that this app token is not accessible to your users! Only use and reference it on the serverside - never pass this to the client. For more info, check out the last few sentences in the relevant documentation.
With version 5 of the SDK you can get the access token with the accessToken() method of a FacebookApp instance. If you have a Facebook instance (as you normally would) you can get it like this:
$fb->getApp()->getAccessToken()
When I want to use my own app's access token I'm instantiating the API like this. I don't know if there's a cleaner way.
$fb = new \Facebook\Facebook([
'default_graph_version' => 'v2.8',
]);
$fb->setDefaultAccessToken($fb->getApp()->getAccessToken());
Replace -
'&client_secret' => 'client_secret'
'&grant_type' => 'grant_type'

I always get: "Invalid appsecret_proof provided"

I know that in the last update of Facebook API, there exists the possibility of provide a appsecret_proof that is the access token signed with the app_secret.
Now the problem is that, irregardless of the option that I set on my facebook app (enable\disable : Require AppSecret Proof for Server API calls) I always get:
Invalid appsecret_proof provided in the API argument
I discovered that last version of php-facebook-sdk always inserts between parameters appsecret_proof
...
if (isset($params['access_token'])) {
$params['appsecret_proof'] = $this->getAppSecretProof($params['access_token']);
}
...
protected function getAppSecretProof($access_token) {
return hash_hmac('sha256', $access_token, $this->getAppSecret());
}
...
If I disable the check on my app, and comment the line that inserts the parameter, everything works fine, otherwise I get the error.
Now, where am I wrong?
I triple checked $access_token, $this->getAppSecret() and the doc, all seem correct.
Any clues?
Put your mind to work from the easy to the complex solutions of a problem. In this specific case, what I would first do is double (triple) check my: App-ID, App-Secret, API-Version (all 3 provided in the App Dashboard) and Access token (Tools & Support > Graph API Explorer).
For me the missing part was the access token. Make sure that under Graph API Explorer, find the dropdown on the right and choose your registered application name, instead of the default value of "Graph API Explorer".
So after all your code should look like this (Graph v2.4):
$fb = new Facebook\Facebook([
'app_id' => $app_id,
'app_secret' => $app_secret,
'default_graph_version' => $api_version
]);
I was finally able to get rid of the error by just granting permissions to everything.

Facebook OAuthException: "user hasn't authorized the application to perform this action"

Using the Facebook PHP SDK, I'm getting the following error when I try to post a status update:
Fatal error: Uncaught OAuthException:
(#200) The user hasn't authorized the
application to perform this action
These are the steps I've taken:
Get code:
https://graph.facebook.com/oauth/authorize?client_id=FB_APP_ID&redirect_uri=REDIRECT_URI
Get access token:
https://graph.facebook.com/oauth/access_token?client_id=FB_APP_ID&code=CODE&client_secret= FB_SECRET&redirect_uri=REDIRECT_URI
Attempt the status update:
require_once(facebook.php);
$fb = new Facebook(array(
'appId' => FB_APP_ID,
'secret' => FB_SECRET
));
$post = $fb->api('me/feed', 'POST', array(
'access_token' => ACCESS_TOKEN,
'message' => 'hello world!'
));
I don't see any settings in my application that would authorize the application to do this, but maybe I'm missing something. Any suggestions?
Make sure you ask for extended publish_stream permission when you're requesting code (added as the third parameter):
https://graph.facebook.com/oauth/authorize?client_id=' . FB_APP_ID . '&redirect_uri=' . REDIRECT_URI . '&scope=publish_stream'
Hope this helps.
Cheers!
I had the same problem and this post really helped me out http://facebook.stackoverflow.com/a/8502709/965536
The only difference with my problem was that I was using the PHP SDK but essentially it works the same. I used the api call
$permissions = $facebook->api('/me/permissions');
You can then run your checks
if(isset($permissions['data'][0]['publish_stream']) && $permissions['data'][0]['publish_stream'])
This works for me but someone may have a better answer. Also you should wrap your publish post stream in a try catch
Hope this helps.
Thanks
I put here some more information:
Mark's replied above has lead me to the right direction. But it took me another 5 hours to figure out the solution.
I'm using omniauth-facebook for ruby on rails.
I need to set the scope for omniauth (Please refer to https://github.com/mkdynamic/omniauth-facebook)
I also ready this post from "Lu Chen" to set the right scope request
http://developers.facebook.com/blog/post/2012/04/25/streamlining-publish_stream-and-publish_actions-permissions/
So, here is the result for omniauth.rb:
provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET'],
:scope => 'email,user_birthday,publish_actions'
Have you taken the other steps required to connect the user with your app and get them to authorize your app to perform these actions? You need to register the users then call showPermissionDialog to let them log in and authorize your app. That's what this error is telling you.

Using Twitter OAuth for automatic status update

I want my website to automatically post status updates to a particular twitter account using OAuth in PHP.
I test this using a URL
www.mysite.com/update_status
but it asks me for "user name" and "password", which is fine when I am testing it. But my website will not be able to insert this user name and password before posting the status update.
So the question is how can a website which is in the server, automatically post a status update to an account without user filling out the user name and password.
Is there any way to bypass this? I tried saving oAuth tokens, but it's not working.
Thank you for your answer in advance!
My recommendation:
1) Use a PHP library like http://github.com/abraham/twitteroauth.
2) Select your app on http://dev.twitter.com/apps and click on "My Access Token".
3) Us that access token as described on http://dev.twitter.com/pages/oauth_single_token.
Just tried this and it WORKS! And its SO SIMPLE to use!!
http://ditio.net/2010/06/07/twitter-php-oauth-update-status/
Got it working in under 5mins.
xAuth is able to do that, but Twitter only allows it for desktop and mobile apps.
In case you wanna try it, read this article and the API docs.
Try it with zend framework. As of version 1.10.8 minimal code required to post on Twitter is:
$token = new Zend_Oauth_Token_Access;
$token->setParams(array(
'oauth_token' => 'REPLACE_WITH_TOKEN',
'oauth_token_secret' => 'REPLACE_WITH_TOKEN_SECRET'
));
$twitter = new Zend_Service_Twitter(array(
'consumerSecret' => 'REPLACE_WITH_CONSUMER_SECRET',
'accessToken' => $token
));
$response = $twitter->status->update('REPLACE WITH MESSAGE');
All tokens and secrets can be accessed after registering your application on http://dev.twitter.com

Categories