Documentation says:
"redirect_uri - (optional) The URL to redirect the user to once the login/authorization process is complete. The user will be redirected to the URL on both login success and failure, so you must check the error parameters in the URL as described in the authentication documentation. If this property is not specified, the user will be redirected to the current URL (i.e. the URL of the page where this method was called, typically the current URL in the user's browser)."
So there is a method to catch if user refused autnentication/permissions, but link to corresponding documentation doesnt exist anymore (https://developers.facebook.com/docs/authentication/).
For the simplicity, redirect_uri is same address as a starting php file, and the php code is as simple as:
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => 'X',
'secret' => 'Y',
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if (!$user) {
$params = array(
'scope' => 'read_stream, friends_likes',
'redirect_uri' => 'http://myapp.com/app'
);
$loginUrl = $facebook->getLoginUrl($params);
}
Anybody knows how to catch that information?
You can do following to check the permissions:
$permissions = $facebook->api("/me/permissions");
if( array_key_exists('publish_stream', $permissions['data'][0]) ) {
// Permission is granted!
// Do the related task
$post_id = $facebook->api('/me/feed', 'post', array('message'=>'Hello World!'));
} else {
// We don't have the permission
// Alert the user or ask for the permission!
header( "Location: " . $facebook->getLoginUrl(array("scope" => "publish_stream")) );
}
It should be noted that in the newest PHP facebook SDK, there is no method ->api. There also seems to be an issue using this check (sometimes) to get permissions. When using the older SDK, sometimes (randomly by user it seemed) some users were getting "OAuthException: (#412) User has not installed the application" even though a check on the FB access token debugger showed proper permissions. After I updated to new SDK, and figured out the new way to get a simple data list of permissions, everything worked again.
It took me a lot of digging in the FB website to find this solution, so I paste it here to hopefully save somebody else a few hours. They real life saver was my discovery of the getDecodedBody method (a very hard to find trick in FB docs). My example just checks for publish_actions.
$fb = new Facebook\Facebook([
'app_id' => your_app_id,
'app_secret' => your_secret,
'default_graph_version' => 'v2.2',
]);
$badperms=true; //start by assume bad permissions
try {
$response = $fb->get('/me/permissions', $at);
$perms = $response->getDecodedBody();
if($badperms){
foreach($perms['data'] AS $perm){
if($perm['permission']=='publish_actions' && $perm['status']=='granted') $badperms=false;
}
}
} catch(Facebook\Exceptions\FacebookResponseException $e) {
log("MSG-received facebook Response exception!! ".$e->getMessage());
} catch(Facebook\Exceptions\FacebookSDKException $e) {
log("MSG-received facebook SDK exception!! ".$e->getMessage());
}
if($badperms) {
//do something like reflow auth
}
I just had the same issue, I didn't know how to treat the cancel action (both in facebook php api and google oauth2).
The solution is much easier than expected.
The response in case of permission not accepted (at all) comes with at least one parameter/variable: error in the URL.
In facebook that response looks like:
error=access_denied&error_code=200&error_description=Permissions+error&error_reason=user_denied
for google you only get the
error=access_denied
but it should be enough.
I'm just checking if error is set and if it's set I am redirecting the response to my login page.
I hope it will help someone because it's really not documented this step.
By the way:
version of facebook API: v5
version of google API oAuth2: 2.0 (i think - google doc is really a mess when it comes to finding the latest versions)
Related
When I run this code, and my cookies have been cleared and I am not logged into facebook. It directs me to facebook and I log in but when it brings me back to my page it is the same, where as it should be show me profile pic and so on...
I seem to have narrowed down the problem of the return statement of the $user because it returns a 0. I have stared at this code for a long time and I havent found what I am doing wrong.
What do i need to change to get it so that When i return from logging in from facebook it will show the profile pic and so on...
<?php
require_once 'libs/facebook.php';
require 'connections/connection.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxx',
));
// Get User ID
$user = $facebook->getUser();
echo $user;
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
echo $user;
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
//$logoutUrl = $facebook->getLogoutUrl();
$logoutUrl = $facebook->getLogoutUrl(array('next' => ($fbconfig['baseurl'] . 'logout.php')));
} else {
$statusUrl = $facebook->getLoginStatusUrl();
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'user_about_me',
'scope' => 'read_friendlists'
));
}
?>
Not to worry my friend, you are not doing anything wrong. I'm having same issue with my DEMO application which was running alright till yesterday.
I'm sure you are having issue with getting access token as well. I think issue is with PHP SDK only.So probably will be fixed in some time.
SOLUTION : This worked for me after trying for many solutions for this issue.
In base_facebook.php file, find the makeRequest() method and check for following Line.
$opts = self::$CURL_OPTS;
Immediately following it, add this line
$opts[CURLOPT_SSL_VERIFYPEER] = false;
More details can be found here - http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/
I have crawled around lots of various answers but am still a bit confused with how I should be dealing with facebook access tokens.
One of the main problems I'm having is due to what information is being stored in my browser. For example, I log onto the app, the token expires, I can't logon again unless I clear cookies/app settings in browser.
I stumbled across this thread: How to extend access token validity since offline_access deprecation
Which has shown me how to create an extended access token through php.
My questions are:
1. Do I need to store the access token anywhere?
2. What happens when the access token expires or becomes invalid? At the moment, my app simply stops working when the short term access ones expire.
3. Is there a way I should be handling them to check if they have expired?
I am using the php sdk and have basically used the standard if( $user )... Like this:
require 'sdk/src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'XXXXXXXXXXXXXXXXXXXXX',
'secret' => 'XXXXXXXXXXXXXXXXXXXXX',
));
$user = $facebook->getUser();
if( $user ){
try{
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if (!$user){
$params = array(
'scope' => 'email',
);
$loginUrl = $facebook->getLoginUrl( $params );
echo '<script type="text/javascript">
window.open("'. $loginUrl .'", "_self");
</script>';
exit;
}
if( $user ){
$access_token = $facebook->getExtendedAccessToken();
$get_user_json = "https://graph.facebook.com/me?access_token="
. $access_token;
// Rest of my code here...
}
Is there anything else I should be doing to handle tokens?
. Should I be passing the access token between pages or is it ok to just call it again at the top of each page like this:
$facebook = new Facebook(array(
'appId' => 'XXXXXXXXXXXX',
'secret' => 'XXXXXXXXXXXX',
'redirect_uri' => 'http://localhost:8000/',
));
$token = $facebook->getExtendedAccessToken();
Let's go through your questions:
Do I need to store the access token anywhere?
This depends on your application. First of all ask yourself, do you need to perform actions on behalf of the user while he is not present (not logged in to your app)?
If the answer is yes, then you need to extend the user token which can be done using the PHP-SDK by calling this method while you have a valid user session: setExtendedAccessToken().
Also you should refer to this document: Extending Access Tokens
What happens when the access token expires or becomes invalid? ...
Is there a way I should be handling them to check if they
have expired?
This is where the catch clause in your code comes in handy, while facebook example only logs the error (error_log($e);) you should be handling it!
Facebook already has a tutorial about this: How-To: Handle expired access tokens.
Also you should refer to the Errors table and adjust your code accordingly.
Is there anything else I should be doing to handle tokens?
See above.
Should I be passing the access token between pages or is it ok to just
call it again at the top of each page
You shouldn't need to do any of that, because the PHP-SDK will handle the token for you; have you noticed that you are calling: $user_profile = $facebook->api('/me'); without appending the user access_token?
The SDK is adding it from its end so you don't have to worry about it.
I just had the same issue, but i solve it with some of your help. I'm using the php-sdk to connect to the Facebook API, so i just made this.
$facebook = new Facebook(array(
'appId' => 'API_ID',
'secret' => 'SECRET',
));
// Get User
$user = $facebook->getUser();
// Verifing if user is logged in.
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Verify if user is logged in, if it is... Save the new token.
if($user){
// Request the access_token to the
$access_token = $facebook->getAccessToken()
// Saving the new token at DB.
$data = array('access_token' => $access_token);
$this->db->where('userid',$user);
$this->db->update('facebook', $data);
}
To post to facebook fan page, using a php script which is called by a cronjob, im using the following code, which worked yesterday while testing, it is no longer working.
include_once("../facebooksdk/src/facebook.php");
$facebook = new Facebook(array(
'appId' => 'XX',
'secret' => 'XX',
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
$page_id = 'XX';
$page_info = $facebook->api("/".$page_id."?fields=access_token");
if( !empty($page_info['access_token']) ) {
$args = array(
'access_token' => $page_info['access_token'],
'message' => "Welcome to TuneHub!"
);
$post_id = $facebook->api("/".$page_id."/feed","post",$args);
}
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
I cant figure out why it would work temporarily, then the following day when the code has been added to the live site, its no longer working (on the test or live site, it isnt working)
is there an API change that is killing the function?
or is there something I am doing wrong with the code that flagged Facebook to prevent it from posting?
(the code may have changed slightly from the script i had which was working, as ive been fiddling around with it to try and find the issue)
see
https://developers.facebook.com/docs/reference/api/page/#posts
Check your access token it may be expired, you need to have a valid access token with rights to post on wall, try getting the updated access token and try
I started playing around with the fb api a couple of days ago. I am using the fb php-sdk to authenticate users with facebook on my site. I use the following piece of code which works, but intermittently and I cant seem to figure out why.
<?php
session_start();
require './library/facebook.php';
include './library/fb_keys.php';
// Create app instance
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
// Get User ID
$user = $facebook->getUser();
//Check Access token
if ($user) {
try {
// Proceed with logged in user.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
//error_log($e);
$user = null;
}
}
// Login or logout based on user state
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(array('scope' => 'status_update, publish_stream', 'redirect_uri' => 'http://webaddress.com/web/'));
}
?>
This is really straightforward piece of code that I got from the https://github.com/facebook/php-sdk/.
I usually can't log in when I clear all my cookies and/or session is cleared. but once I log on to the facebook.com site all seems to work again. So it indicates that I am missing something with regard to setting the session or cookies.
Any help will be appreciated.
I guess by not working you mean that user isn't redirected to the login page?
You do get the loginUrl but you're not redirecting user there.
This can be easly done with adding the following code after $loginUrl line:
print '<script language="javascript" type="text/javascript"> top.location.href="'. $loginUrl .'"; </script>';
If I'm wrong please tell me exactly what you mean under "can't log in", what stops you etc.
I was making a facebook application in which i have to show news feeds of the user who is using it. I am using graph API to do this. The problem is that its not getting me feeds.
I used it to show friends like this:
$friends = $facebook->api('/me/friends');
and it is working fine.
For news feeds i use this:
$feeds = $facebook->api('/me/home');
it shows me an error:
Fatal error: Uncaught IDInvalidException: Invalid id: 0 thrown in
/home/content/58/6774358/html/test/src/facebook.php on line 560
when i try to get Profile feed (Wall) by using this:
$feeds = $facebook->api('/me/feed');
it shows me an empty array.
These API calls are showing me results in the graph API page but don't know why not working in my application.Can any one help me please..
My full code is as follows
require_once 'src/facebook.php';
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => 'xxxxx',
'secret' => 'xxxxx',
'cookie' => true,
));
$session = $facebook->getSession();
$fbme = null;
// Session based graph API call.
if (!empty($session)){
$fbme = $facebook->api('/me');
}
if ($fbme) {
$logoutUrl = $facebook->getLogoutUrl();
echo 'Logout';
}else{
$loginUrl = $facebook->getLoginUrl();
echo 'Logout';
}
$friends = $facebook->api('/me/friends?access_token='.$session["access_token"]);
$feeds = $facebook->api('/me/feed?access_token='.$session["access_token"]);
print('<pre>Herere:');print_r($feeds);die;
Did you ask for the read_stream permission during authentication?
What type of Authentication / "Allow" process did you go through?
JavaScript SDK? Facebook PHP SDK? XFBML Login Button?
EDIT- Here are helpful link that will get you started up:
Facebook PHP SDK
Authentication Process
Building Apps on Facebook.com
These are all official docs in Facebook and github.
EDIT: Follow this step by step:
From your original code, look for:
$loginUrl = $facebook->getLoginUrl();
Change it to:
$loginUrl = $facebook->getLoginUrl(array('req_perms'=>'read_stream'));
Uninstall your application first from your account:
http://www.facebook.com/settings/?tab=applications
Then try it again to show new Allow pop-up
EDIT:
It's also about the arrangement of code in the if statements. Use this code:
<?php
require_once 'src/facebook.php';
$session = $facebook->getSession();
$fbme = null;
if($session){
$fbme = $facebook->api('/me');
$friends = $facebook->api('/me/friends');
$feeds = $facebook->api('/me/feed');
$logoutUrl = $facebook->getLogoutUrl();
echo 'Logout';
echo "<pre>".print_r($feeds,TRUE)."</pre>";
}else{
$loginUrl = $facebook->getLoginUrl(array('req_perms'=>'read_stream','canvas'=>1,'fbconnect'=>0));
echo '<script> top.location.href="'.$loginUrl.'"; </script>>';
}
Uninstall your app again from
http://www.facebook.com/settings/?tab=applications
and re-open the application
The Facebook PHP SDK should handle your access token for you, you don't need to append it to your graph API endpoint in you Facebook::api() call.
As #dragonjet pointed out, you need to request the read_stream extended permission from your FB User in order to get access to their feed. Though, the exception you pasted doesn't really match that kind of problem, and your request to /me/home doesn't throw a similar exception (or one about not having access).
I still think this is a permissions issue, so start here for trying to fix it. Here's an example of how to request the appropriate permission.
$facebook = new Facebook(array(
'appId' => FB_APP_ID, //put your FB APP ID here
'secret' => FB_APP_SECRET, //put your FB APP SECRET KEY here
'cookie' => true
));
$session = $facebook->getSession();
if ($session)
{
//check to see if we have friends_birthday permission
$perms = $facebook->api('/me/permissions');
}
//we do this to see if the user is logged & installed
if (empty($session) || empty($perms['read_stream']))
{
//get url to oauth endpoint for install/login
$loginUrl = $facebook->getLoginUrl(array(
//put the URL to this page, relative to the FB canvas
//(apps.facebook.com) here vvv
'next' => 'http://apps.facebook.com/path_to_your_app/index.php',
'req_perms' => 'read_stream'
));
//use javascript to redirect. the oauth endpoint cant be loaded in an
//iframe, so we have to bust out of the iframe and load it in the browser
//and tell the oauth endpoint to come back to the fb canvas location
echo "<script>window.top.location='{$loginUrl}';</script>";
exit;
}
print_r($facebook->api('/me/home'));
print_r($facebook->api('/me/feed'));