I am a newbie to facebook opengraph and creating facebook applications. I have developed an app in facebook and going by the opengraph tutorial I have inserted the necessary meta tags. Testing the app privately, "publish_stream" permission have been granted. Is it necessary to obtain user access token even if publish_stream permission has been granted by the user? How can one obtain user token?
function Visit_Link()
{
$config = array();
$config['appId'] = 'APP ID';
$config['secret'] = 'APP SECRET';
$facebook = new Facebook($config);
$response = $facebook->api(
'me/namespace:action',
'POST',
array(
'website' => "WEBSITE",
)
);
print_r($response);
}
The error displayed is Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user. thrown in
P.S I am using fb php sdk
yes you do need the access token, a long lived one preferably (which last for 60 days). If you are testing your app with the graph api explorer token, you will always need a new one after 30 min or so, because it short-lived. Use this to login your user, because it will always return a long lived access token which you can store in the DB for offline-access (which facebook deprecated and introduced the long lived access tokens).
Related
I'm using the php-sdk to create a session upon login of my site thru fb. Upon login, the user will be redirected to a file called fb_redirect.php. On that page, there is the following:
$facebook = new Facebook(array('appId' => '123456789',
'secret' => '123456789',
'cookie' => true));
$access_token = $facebook->getAccessToken();
//$facebook->setAccessToken($access_token); // you do not need to set the token if there is one, so this should be conditional to if your switching tokens or setting a token from an external sdk.
When the
$access_token
is echoed here, it display the user token. But, on another page, I need to take advantage of the publish_actions permission that my app has requested and post a custom action to the user's timeline. For that to happen, I need the access token to be set to the user token. But, for some reason, on other pages the $access_token is always set to the access token and not the user token. How can I manually set it back to the user token?
If you use the server-side flow, then you have to save it somewhere (a cookie, or a server-side session, or a DB table), and load it back when the user comes back.
Quick and dirty method, this does not handle expiry.
if (!$_SESSION['fb_YourAppID_access_token']) {
$access_token = $facebook->getAccessToken();
if ($access_token) {
$_SESSION['your_token'] = $access_token;
}
}else{
$access_token = $_SESSION['fb_YourAppID_access_token'];
$_SESSION['your_token'] = $access_token;
}
this will look for existing token in browser, if not found it will ask the php sdk what the current token is, if there is a token in the sdk, it sets your session token to the current access token, if not it will save it blank.
Hi i have an application i got offline_access and manage_pages perms
i can upload photos by this code:
$phototoken='AAAAABya***sZAJ';
$photo_details = array(
'access_token' => $phototoken
);
$photo_details['image'] = '#' . realpath($img);
$upload_photo = $facebook->api('/me/photos', 'post', $photo_details);
}
but when i change my password my token will die and my app won't be able to access the to fan page am i right
http://smileychatcodes.com/facebook-smiley-chat-codes/
so how these sites access to fan pages as offline?
Changing your password will always invalidate the User Access Token, however as explained here you can get a long-lived User access token which will allow you to generate an infinite-life Page Access Token.
I am trying to work out how to post to a Facebook page wall, when using my app as a different Facebook User (who is not the Page Administrator).
I get a range of error messages while testing:
Exception: 200: The user hasn't authorized the application to perform this action
The page administrator has visited the app and accepted the following permissions: publish_stream, manage_pages, offline_access
Here is the code I plan to use:
// Insert Page Administrators ID here
// This user is not the same user that is currently logged in and using the app
// This user is the page administrator who has authorised:
// - manage_pages
// - offline_access
// - publish_stream
$user_id = '123456789';
// Insert Page ID here
$page_id = '123456789';
$accounts = $facebook->api('/'.$user_id.'/accounts');
foreach($accounts['data'] as $account)
{
if($account['id'] == $page_id)
{
$page_access_token = $account['access_token'];
echo "<p>Page Access Token: $page_access_token</p>";
}
}
// publish to the wall on your page
try
{
$result = $facebook->api(array( "uid" => $page_id,
"method" => "stream.publish",
"access_token" => $page_access_token,
"message" => $message, ));
}
catch (FacebookApiException $e)
{
error_log('FB Error: Could not post on Page Wall. Page ID: ' . $page_id);
error_log('FB Error Message: ' . $e);
}
Note: There may be PHP errors in the code above, as I just spliced it on the fly, but its not so much the PHP errors I need correcting, but more my logically understanding of how I am meant to go about this process.
PROBLEM:
I can't access the $user_id/accounts information without an active user access token for the Page Administrator.
The end result that I'm trying to achieve is:
1.) A normal FB user goes to the app and submits a form
2.) The app posts a message on a FB Page wall, which is not owned by the FB user, but has previously been authorized by the Page Administrator with the following permissions manage_pages, publish_stream and offline_access
Q1. Since the Page Administrator has accepted the appropriate permissions, why can't I just generate an active user access token, without the actual Page Administrator user logging into the website?
Q2. Is there a way I can get the equivalent of /$user_id/accounts for the Page Administrator user_id, when logged into Facebook as a different user (which is why I do not use /me/accounts)?
Q3. Please confirm that my understanding of needing the page access token to post to the page wall is correct (or do I need the user access_token for the Page Administrator - see Q1)?
Q4. Anyone have a handy resource on what each type of access_token can actually access?
If you need any more information, please let me know.
I've spent the last few days working on this and I'm stuck.
Thanks!
You can ask the page admin for manage_pages along with offline_access. I do this in my production app to be able to post scheduled postings onto the pages' walls.
Nope. Not possible. That's what asking permissions is all about. And why not everyone gets to administer everyone else's pages. Could you image if you could administer anyone's page without them granting you access?!?
To post to the page as the page, you need a page access token. To post to page's wall as a user, you need a user access token.
Yes, please see: https://developers.facebook.com/docs/reference/api/permissions and https://developers.facebook.com/docs/authentication/
If you have further questions about any one of these, please start a new question. It's not really fair to users of stackoverflow to be hit with 4 questions in one and then to be asked followup questions to each of those.
I have done in Django:
Step to get Page_access_token:
facebook_page_id=360729583957969
graph = GraphAPI(request.facebook.user.oauth_token.token)
page_access_token=graph.get(facebook_page_id+'?fields=access_token')
This way you can get Page access token.
You can check this thing on Fb GraphAPIexplorer:
http://developers.facebook.com/tools/explorer
GET URL: fb_page_id?fields=access_token
for example: 360729583957969?fields=access_token
that will give you page_access_token
I've got some trouble with Facebook authentication. Even when I'm logged, the function getUser() returns 0
Here's my code :
$fb_params = array(
'appId' => APP_ID,
'secret' => SECRET_ID
);
$fb = new Facebook($fb_params);
echo $fb->getUser(); // UID
Someone's got an idea?
PS : 'I can no long access to $fb->api('/me'), it says it requires an access_token, I think it's linked to the authentication issue...'
Thanks
You are currently not authenticating as a user, only as an application. As a result, the Facebook API can't show you the /me page or respond to a getUser() call since it doesn't know what user you are trying to access the API on behalf of (ie. "Who is /me?"). You will also only be able to access publically-accessible information.
You need to get a user to authenticate your application through Oauth2, store the access_token you are returned, and then include it in any future calls (eg. WIRQjCey1.3600.1309525200.0-509450630|eD6SAR">https://graph.facebook.com/me?access_token=2227470867|2.AQB-_WIRQjCey1.3600.1309525200.0-509450630|eD6SAR...).
To do this using the PHP SDK you can do
$loginUrl = $fb->getLoginUrl();
echo "<a href='$loginUrl'>Login with Facebook</a>";
Clicking that link and having the user authenticate will store the access_token to the $_SESSION, and when you hit refresh the "new Facebook( $fb_params );" constructor will pick out the access token from the $_SESSION and use it for all future calls, so then calls like $fb->getUser(); will return correctly.
There's a functioning example in the examples folder of the SDK, here:
https://github.com/facebook/php-sdk.
You can use it to try calls while authenticated as an application (public data access only), and then as a user.
When a user visits my site which contains a facebook app the first time, it requires him to allow it and he gets promted to do that, then I get the code which I can convert to an access_token. So far so good.
But how do I get the token once the user has already visited the site?
As long as this token form the first time is active everything is fine. But how do I get another token when the user had already allowed the app a week ago and is only visiting my page again?
Now that Facebook is migrating to Oauth2, the cookie created by the Javascript is different. I got it to work for me and added it to a fork of the FGraph plugin for Rails - https://github.com/imme5150/fgraph
One of the tricks is that when you request the access_token from the "code" parameter stored in the cookie, you have to pass in "redirect_uri", but you want it to be blank.
On the client-side flow, you can redirect the user to the OAuth dialog with the permissions in the scope parameter. If the user already accepted your App and permissions he will be redirected to your "redirect_uri" with the access_token in the URI fragment, otherwise the needed permissions will be prompt.
https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&scope=email,read_stream&response_type=token
On the server-side flow you should have the "code" so you can redeem it for an access_token on the OAuth endpoint:
https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&redirect_uri=YOUR_URLclient_secret=YOUR_APP_SECRET&code=THE_CODE_FROM_ABOVE
Documentation: https://developers.facebook.com/docs/authentication/
I use the cookie method to store the access_token on the user's computer.
FB.init({appId: 'your app id', status: true, cookie: true, xfbml: true});
In your facebook.php file you need to set cookieSupport to true then:
private $cookieSupport = true;
Or use the get_facebook_cookie function found here: Single sign-on with the JavaScript SDK
The access_token is then stored in a cookie called "fbs_APPID" (with expire). If you want the cookie to last more then a couple of hours you need to ask the extended permission 'offline_access':
Enables your application to perform authorized requests on behalf of the user at any time. By default, most access tokens expire after a short time period to ensure applications only make requests on behalf of the user when the are actively using the application. This permission makes the access token returned by our OAuth endpoint long-lived.
you can also use this:
$access_token = $facebook->getAccessToken();
https://developers.facebook.com/docs/reference/php/facebook-getAccessToken/
using php
session_start();
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_APP_SECRET,
'cookie' => true,
'domain' => 'example.com'
));
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
$_SESSION['me'] = $me;
$_SESSION['uid'] = $uid;
$_SESSION['session'] = $session;
} catch (FacebookApiException $e) {
error_log($e);
}
}
you can reference the access_token via $_SESSION['session']['access_token'] within your app,, for more theres tutorials over at fbdevtutorials.com