I'm trying to work with Facebook's default PHP website integration and authentication.
When a user logs in, I'm able to request permissions to get various information from the user.
This question is kind of old. Please take note of harkirat1892's comment.
"If someone using Facebook SDK v4.4 is stumbling across this question, the answer by Dhiraj won't >work in that case as there is a small change. You don't have to include redirect_uri in the array >passed to getLoginUrl.
As per v4.4, getLoginUrl should work like:
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email,user_checkins, user_birthday'
)
);
The various scopes can be found here: Facebook permissions."
It was really easy to figure out how to do it with the JavaScript one, but I'm confused where to specify the scope in the PHP example.
Basically, I just want to request for permission to access their email & location and maybe some other information.
Here is the code I'm working with:
(It's modified slightly, but it is almost an exact match to what they had.)
<?php
define('YOUR_APP_ID', '---------');
define('YOUR_APP_SECRET', '------------');
//Uses the PHP SDK. Download from https://github.com/facebook/php-sdk
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$FBUID = $facebook->getUser();
?>
<?php if ($FBUID) {
$userInfo = $facebook->api('/' + $FBUID); ?>
<?php $FBName = $userInfo['name'];?>
<!--
Welcome <? // = $userInfo['name'] ?> -->
<?php } else { ?>
<div id="fb-root"></div>
<fb:login-button></fb:login-button>
<?php } ?>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '---------------',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
This is how you typically specify scope in PHP (check the documentation):
$facebook = new Facebook(array(
'appId' => AppInfo::appID(),
'secret' => AppInfo::appSecret(),
));
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'read_stream,publish_stream,publish_actions,manage_pages,email,user_checkins',
'redirect_uri' => $redirectURI
)
);
I hope this helps.
The answer above is great but, Facebook just loves to change things up. The best answer checked off on this forum is for a version of Facebook SDK, which is out of date. Similar to the example above, here is how you would request permissions or a scope for version 5.0.
session_start();
$F = new \Facebook\Facebook([
'app_id' => 'app-id',
'app_secret' => 'app-secret',
'default_graph_version' => 'v2.8'
]);
$helper = $F->getRedirectLoginHelper();
$callBackUrl = "http://website.com/callBack.php";
$scope = array("email","user_likes");
$loginUrl = $helper->getLoginUrl($url,$scope);
Also, I noticed the answer above is a request for "user_checkins" which I believe is deprecated. The most current reference list of permissions is here.
If someone using Facebook SDK v4.4 is stumbling across this question, the answer by Dhiraj won't work in that case as there is a small change. You don't have to include redirect_uri in the array passed to getLoginUrl.
As per v4.4, getLoginUrl should work like:
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email, user_checkins, user_birthday'
)
);
The various scopes can be found here: Facebook permissions.
I am getting same issue and got below solution. Might it help you :
Open your app in facebook developer console and then select app reviews section on left side.
Submit Items for Approval. Some permissions need to take approval from facebook before using.
:)
Related
I'm new to web development, still a beginner.
I unsure on how to code for session calling the FaceBook if there any. However, I've added this at all pages which I want my facebook to be loaded. I believe it is the Facebook SDK. For example, I add this code in my register.php and login.php.
<body>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $config['appId']; ?>',
xfbml : true,
version : 'v2.4'
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
I also added this in my config.php which I believe it is Config for FB Login.
$config = array();
However, every time I tried to click on the Facebook button in my login.php, there will be error such that
Fatal error: Call to a member function getLoginUrl() on a non-object
in C:\wamp\www\sggrocer\loginFb.php on line 13
loginFB.php
<?php
session_start();
include('ajax-helper/config.php');
$_SESSION[$PROJECT_NAME . '-loginFb'] = true;
unset($_SESSION[$PROJECT_NAME . '-logout']);
$params = array(
'scope' => 'email, user_birthday',
'redirect_uri' => $base_url . "http://localhost/sggrocer/",
);
$loginUrl = $facebook->getLoginUrl($params);
header('Location:' . $loginUrl);
?>
This is my login.php:
https://jsfiddle.net/Snurainiyakob/V4u5X/872/
And the UI as follows:
enter image description here
You miss to initialize your $facebook-object.
Please take a look at the official documentation here. It offers nice examples to get started.
$fb = new Facebook\Facebook([
'app_id' => '1475470649428121',
'app_secret' => '{your-app-secret}',
'default_graph_version' => 'v2.4',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('https://example.com/fb-callback.php', $permissions);
echo 'Log in with Facebook!';
I am using facebook SDK to get facebook friends list. If I Invoke API with Javascript FB.init(); it works perfectly fine..
but if I use it directly like
facebook = new Facebook(array(
'appId' => $appid,
'secret' => $secret
));
$fbuser = $facebook->getUser();
try{
$user_profile = $facebook->api('/me');
print_r($user_profile);
} catch(Exception $e){
echo $e->getMessage();
}
(User is logged in with facebook in the same browser)
It always gives me an error : An active access token must be used to query information about the current user.
Please help me how to use it without FB.init() or redirect anywhere..
Use this
facebook = new Facebook(array(
'appId' => $appid,
'secret' => $secret,
'cookie' => true
));
$fbuser = $facebook->getUser();
if($fbuser){
$access_token = $facebook->getAccessToken();
$facebook->setAccessToken($access_token);
try{
$user_profile = $facebook->api('/me');
print_r($user_profile);
} catch(Exception $e){
echo $e->getMessage();
}
}else{
// User not logged in generate the login button or link here
}
Make sure in the above script when user login ffor the first time it reloads the page in other words you need to provide the redirect_uri
https://developers.facebook.com/docs/reference/php/facebook-getLoginUrl/
Also you can use the following api to get the user details
$user_profile = $facebook->api('/'. $fbuser,'GET');
Then add the following below the page. This will check if the user is already logged in it will re-direct to the same page, in other words it will not ask user to login again
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function()
{
FB.init
({
appId : 'your fb app id',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true
});
FB.Event.subscribe('auth.login', function()
{
window.location.reload();
});
};
(function()
{
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
I wasn't sure how to ask it, but I am trying to teach myself how to create a program that uses the graph api. Most of the tutorials I have seen are older, and I don't know how relevant they are now. Essentially, I am trying to get the "thing" where someons clicks my app, it says, this app wants your username, etc. and then Allow or Don't Allow.
I want it to take the information and then I can insert it into a database. I am using php and have a domain.
I can insert the data no problem, if I can get the data. I don't understand how to do it.
I'm sorry for a vague question, and I have searched. Not asking you to write my code for me, just point me in the right direction, maybe to a modern tutorial doing what I am asking. Thanks.
1) Create a Facebook application from here:
http://developers.facebook.com/apps
And configure it with your domain.
This step is really easy, put any namespace you want that will be your application name, then check that your application will be used as an "application and login page" (not a fan page or something related) and finally specify the URLs where you will use Facebook API (leave Canvas URL blank).
Just a heads up, I believe Facebook API requires HTTPS URLs but I don't know why is still allowing HTTP, so don't worry by now.
Login config:
Set the URL: http://yourdomain.com/
Application config:
http://yourdomain.com/myfacebookapp/
So, when a user goes to:
http://apps.facebook.com/yourappName
Means that a user is really browsing the first link and in that page (let's say index.php) you will need to do everything from below.
Just FYI, at this point you can also set a logo for your application, manage administrators and get your application ID and secret that you will use in your PHP file later.
(If you get confused in this step you can do a Google search, this configuration is easy to find)
2) I always use these files to link my PHP enviroment with Facebook API, here's the link from my Dropbox: https://www.dropbox.com/s/itw4pav1f7a9vez/files.rar
3) Put those files in a folder called fb.
4) I will show you the way to get data and picture from a user but first the user has to allow your application to get this info when getting logged in your application.
So, for this example I will use a simple button for the login:
(Don't forget to replace your application ID and secret, notice the 'xxx' and 'yyy')
<?php
require 'fb/facebook.php';
$facebook = new Facebook(array(
'appId' => 'xxx',
'secret' => 'yyy',
));
// Check if user is already logged
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Get login or logout URL
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
?>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>Facebook PHP SDK</title>
</head>
<body>
<h1>Facebook PHP SDK</h1>
<?php if ($user): ?>
Logout
<?php else: ?>
<div>
Login with Facebook
</div>
<?php endif ?>
<h3>PHP Session</h3>
<pre><?php print_r($_SESSION); ?></pre>
<?php if ($user): ?>
<h3>Your picture</h3>
<img src="https://graph.facebook.com/<?php echo $user; ?>/picture">
<h3>Your info (/me)</h3>
<pre><?php print_r($user_profile); ?></pre>
<?php else: ?>
<strong><em>You are not connected.</em></strong>
<?php endif ?>
</html>
5) Above example uses Facebook PHP SDK without JavaScript. So, if user wants to login and authorize your application to get the info then the whole page will be redirected to the Facebook permissions page of your application and after it will go back to the main page of your Facebook application (specified in the configurations from your application).
6) Below code will do the same as above but using JavaScript and custom Facebook login button that allows you to put special permissions as you wrote in your question. Another difference is that a popup will appear instead of redirecting the whole page.
(Don't forget to replace your application ID and secret, notice the 'xxx' and 'yyy')
<?php
require 'fb/facebook.php';
$facebook = new Facebook(array(
'appId' => 'xxx',
'secret' => 'yyy',
));
// Check if user is already logged
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
$logoutUrl = $facebook->getLogoutUrl();
} catch (FacebookApiException $e) {
$user = null;
}
} else {
$loginUrl = $facebook->getLoginUrl();
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Facebook PHP SDK</title>
</head>
<body>
<fb:login-button size="small" onlogin="after_login_button()" scope="email, user_about_me, user_birthday, user_status, publish_stream, user_photos, read_stream, friends_likes">Login with facebook</fb:login-button>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '<?php echo $facebook->getAppID() ?>',
cookie: true,
xfbml: true,
oauth: true
});
// This is used by Facebook login button
FB.Event.subscribe('auth.login', function(response) {
if (response.authResponse) {
// Specify the login page where Facebook login button is located
window.location = 'main.php';
}
});
FB.Event.subscribe('auth.logout', function(response) {
window.location = 'logout.php';
});
};
(function() {
var e = document.createElement('script');
e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
function after_login_button(){
FB.getLoginStatus(function(response) {
if (response.status == 'connected') {
// If user is connected, redirect to below page
window.location = 'main.php';
}
}, true);
}
</script>
</body>
</html>
7) As you can see, the scope attribute in the Facebook login button determines which special permissions and info your application will need from a user like the email for example (which is always private unless authorized).
8) To add something, you can get only public information from someone by using the following:
// For example: Your Facebook friend's profile is http://www.facebook.com/foobar
$myFriend = $facebook->api('/foobar');
// For example: Your Facebook friend's profile is http://www.facebook.com/users/1002020300010
$myFriend = $facebook->api('/1002020300010');
// Print the name
echo $myFriend['name'];
// Print all data
print_r($myFriend);
And, in order to get your Facebook friend's picture just do this:
<img src="https://graph.facebook.com/foobar/picture">
Or:
<img src="https://graph.facebook.com/1002020300010/picture">
Finally, supposing that you have all user info that was needed then now you can save it all into DB without problems or restrictions.
Hope this helps as reference.
It seems that you are looking to creating an authentication (login) using Facebook.
You may wish to check out Opauth, it handles all of that for you and returns you the user info in an array, of which you can then insert into database easily.
See http://opauth.org for a quick demo and download the library which contains sample code.
Considering that you are using the PHP SDK Classes provided by Facebook here
You can do something like this
$fb = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET'
));
$userData = $fb->api('/me','GET');
$userData = serialize($userData);
//now userdata is a string, so, insert into the database.
Remembering, in your app configurantion, you must specify the kind of information you want from user.
You can use the php API and the query language that facebook provides (FQL). Here is a link that contains sample query's and tutorials http://developers.facebook.com/docs/reference/fql/
This question already has an answer here:
Codeigniter, Facebook javascript SDK, PHP SDK Redirect after facebook login doesn't getUser() until refresh
(1 answer)
Closed 5 years ago.
I am implementing Facebook login using the PHP SDK with Codeigniter. I get the Facebook login popup, hit login, but I am unable to retrieve the user's id - it always returns 0.
I have put the facebook.php and base_facebook.php files in my libraries file and included it as a library in Codeigniter following a tutorial here.
Can anyone tell me what they think is going on? I am using the following code -
View - Facebook login button
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $this->config->item('facebook_app_id'); ?>',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
FB.Event.subscribe('auth.login', function() {
window.location='<?php echo base_url(); ?>auth_other/fb_signin/';
});
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<div class="fb-login-button">Login with Facebook</div>
Controller - auth_other/fb_signin
function fb_signin()
{
$fb_user = null;
$fb_config = array(
'appId' => $this->config->item('facebook_app_id'),
'secret' => $this->config->item('facebook_app_secret')
);
$this->load->library('facebook',$fb_config);
$fb_user = $this->facebook->getUser();
echo $fb_user;
I was stuck up with similar issue, here is the solution that may help you.
$facebook = new Facebook(array(
'appId' => 'xxxx',
'secret' => 'xxxxx',
"redirect_uri" => "set the uri to point to the same page"
));
$user = $facebook->getUser();
if($user)
{
//your task
} else {
header('location:'. $facebook->getLoginUrl());
}
$user = $facebook->getUser();
if($user)
{
//your task
} else {
header('location:'. $facebook->getLoginUrl());
}
Came across a situation where getUser() was returning 0 when it really shouldn't be, the application was still sandboxed. Turns out the user hadn't accept the request to be developer of the application.
I've encountered a similar problem. I used an example project, and couldn't figure out why it keeps returning 0. tried nearly all related links here but none solved it.
The solution was to update Facebook's SDK files in the example project.
Simple and easily missed,
I had same issue, After long time of trying to figure out what the issue is,
I found that you need access token to get user ID.
To get access token form the signed_request, user must authorize (to get permissions) you app firstly.
I hope this will help
If App domain is real domain but site url is localhost, getUser function return 0
I created a facebook application and send request to a user through below code.Now when a user allow my application then i need his id and email address into my canvas url.But on that below code user don't go to my canvas URL.So,Please help me to solve ,how a user go to my canvas url when he allow my application and i get the user id of that user?My code is below:
require_once 'facebook.php';
$facebook = new Facebook(array(
'appId' => '#######',
'secret' => '###################',
'cookie' => true, ));
$req_perms = "publish_stream,offline_access,user_status,email,read_stream";
$session = $facebook->getSession();
$loginUrl = $facebook->getLoginUrl(array('canvas'=>1,'fbconnect' => 0,'req_perms'=>$req_perms));
$me = null;
if (!$session)
{ echo "top.location.href= '$loginUrl';";exit;}
else{
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
}
catch (FacebookApiException $e)
{ echo "<script type='text/javascript'>top.location.href= '$loginUrl';</script>"; exit;}
}
So,please help me to get the user id.
Thanks in advance
riad
The Facebook ID & email for the current user can be accessed through:
$me['id'];
$me['email'];
Is that what you're after?
First of all, your code is "badly" written. The catch block in your code "when executed" does not mean that the user is not logged in. It means that something went wrong in your try block (a.k.a bad Facebook Call).
Now for your question, you just need to place this in your try block:
$data = $facebook->api('/me?fields=id,email');
IMPORTANT NOTE:
You may not get the user real email, the user may choose to not share it with you and this way Facebook will create a "mirror" email to share with your App.
I am not familiar with php to comment on the code above. However in general it would be better to use javascript sdk for login alone (faced the same issue in asp.net). That way post user login, the control comes back to the same page where it was initiated. For example:
<div id="fb-root"></div>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
FB.init({
appId: <app_id>, cookie: true, status: true, xfbml: true
});
function fblogin() {
FB.login(function (response) {
//Control comes back here
if (response.session) {
alert(response.session.access_token);
var url = '/me?fields=name,email';
FB.api(url, function (response) {
//You are now in the same page with the data you wanted. If necessary redirect.
alert(response.name);
alert(response.email);
});
}
else {
alert("User did not login successfully");
}
}, { perms: 'email' });
}
</script>
<img src="../Images/social_facebook.png" />
At last i solve my problem and now i can easily get the facebook user id and email address and other related information.Using this code i can hit to facebook for particular user's authentication and when user accept my application then i can get his/her facebook user id, email and other information into $user_info array.Hope it will help you.
Just see my code below:
<?php
require_once 'facebook.php';
$facebook = new Facebook(array(
'appId' => '########',
'secret' => '##########################',
'cookie' => true,
));
$req_perms = "publish_stream,offline_access,user_status,email,read_stream";
$session = $facebook->getSession();
$loginUrl = $facebook->getLoginUrl(array('canvas'=> 1,'fbconnect' => 0,'req_perms' => $req_perms));
$user_info = null;
if (!$session)
{ echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";exit;}
else{
try { $user_info = $facebook->api('/me'); }
catch (FacebookApiException $e)
{ echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>"; exit;}
}
?>
<!doctype html>
<html>
<head>
</head>
<body>
<?php
$user_name=$user_info['name'];
echo "Hi $user_name ! Your Facebook ID is: ".$user_info['id']."<br/>";
echo "Hi $user_name ! Your E-mail Address is: ".$user_info['email']."<br/>";
echo "Thanks for accepting our application.";
//print_r($user_info);
?>
</body>
</html>