I'm using this code but I can't figure out how to get the email from the user. I know you must get special permission from the user but I don't know how.
I can get the public data from the user but that's not what I even need. The only thing I need is the email.
I guess it's something with this line:
$me = $facebook->api('/me');
I have read the documentation but I still don't know how I can get the email. How do I get the email from the user loggin in on my website with the facebook api?
You first need to request an extended permission "Email" from the user. You can do this using FB JS SDK by calling FB.login(), or PHP FB SDK by redirecting the browser by calling getLoginUrl().
FB JS SDK: FB.login method
FB.login(function(response) {
if (response.session) {
if (response.perms) {
// user is logged in and granted some permissions.
// perms is a comma separated list of granted permissions
} else {
// user is logged in, but did not grant any permissions
}
} else {
// user is not logged in
}
}, {perms:'email'});
FB PHP SDK method:
$login_url = $Facebook->getLoginUrl(array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'email'
));
echo '<script type="text/javascript">top.location.href = "'.$login_url.'";</script>';
exit();
Once you have the required permission, you can then call this in your PHP:
$me = $facebook->api('/me?fields=email');
Related
I need to read the posts on facebook. I had create the application and the program works if I log with my credential. But when I log with another credential ( like another profile that I have just created) the program doesn't work anymore. This is my login page:
$config = array(
'appId' => APPID,
'secret' => APPSECRET,
'allowSignedRequest' => false // optional but should be set to false for non-canvas apps
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if(!empty($_SESSION)) {
if($user_id) {
try {
$user_profile = $facebook->api('/me','GET');
$login_url = $facebook->getLoginUrl(array('scope' => 'user_posts'));
$access_token=$facebook->getAccessToken();
$facebook->setAccessToken($access_token);
} catch(FacebookApiException $e) {
error_log($e->getType());
error_log($e->getMessage());
}
}
} else {
$login_url = $facebook->getLoginUrl(array('scope' => 'user_posts'));
header("Location: ".$login_url);
}
when I login I obtain the access token and I call graph api:
https://graph.facebook.com/******/posts?access_token=**
This is operation work if I m who is logged in the application. If another login in the app this is not work.
Maybe it's a authentication problem. Maybe I forget some operation that I must do to authentica with another account. Anyone can help me?
You need to submit your App to Facebook then Facebook will check and pass you app then you can access you app other account. If you want to check App Functionality you can use Facebook App test user Id. Below I have Explained how to get test user
Goto App Page.
Click on Roles.
Click on to Right Corner Test users.
It will show your test user details.
Use this details and access you App.
You have to make your app public for all users from here: https://developers.facebook.com
have a look on it:
Use /me/feed instead of /me in your API call
see example below
Permissions
Your app needs user_posts permission from the person who created the post or the person tagged in the post. Then your app can read:
Timeline posts from the person who gave you the permission.
The posts that other people made on that person Timeline.
The posts that other people have tagged that person in.
If you attempt to read data from a feed that your app has not been authorized to access, the call will return an empty array.
please read this thread https://stackoverflow.com/questions/30719556/read-post-from-facebook-home/30732874#30732874
READING
/* PHP SDK v4.0.0 */
/* make the API call */
$request = new FacebookRequest(
$session,
'GET',
'/me/feed'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
/* handle the result */
I'm trying to activate cookies via the facebook login so it doesnt always depend on the session being there but whenever I set sharedSession to true I get a "The page isn't redirecting properly" error page.. Is this the way I'm suppose to make it so the facebook login uses cookies? I'm using the newest code on github for the facebook SDK (downloaded a freshy today) -> https://github.com/facebook/facebook-php-sdk
I'm not using the javascript SDK. and all of the coding below is fired before any headers are sent out. If I take the sharedSession out, it logs me in correctly, but it doesnt store a cookie with the info needed.
Heres the coding I'm using
$facebook = new Facebook(array(
'appId' => $Sets['facebook']['appId'],
'secret' => $Sets['facebook']['appSecret'],
'sharedSession' => true,
// 'trustForwarded' => true
));
$user = $facebook->getUser();
if($user){
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
// the user is logged into facebook
if($user){
// I register them on my website..
// and then send them to the index page
header('Location: /index.php');
} else {
// they are not registered through facebook
if(isset($_GET['error'])){
// this happens when an error is found
die($_GET['error'].' error');
// header("Location: /login/?error=".urlencode($_GET['error']));
exit;
} else {
// send to facebook to log them in.
$loginUrl = $facebook->getLoginUrl($Sets['facebook']['scope_array']);
// die('sending to '.$loginUrl);
header("Location: ".$loginUrl);
exit;
}
}
You can see I put the die() function before any redirection there, this was for debugging on my end to see if I can figure out where it was failing, but it seems to happen after the user is returned to the website.. I also tried the trustForward => true, but that didnt fix it..
all I'm after is to be able to have the user logged in for a longer period of time, without having to login through facebook everytime they visit the website.
Whats happening is the user is stuck in a loop trying to log into facebook being redirected between facebook and my website because the user is never verified. Again, this ONLY happens when I set 'sharedSession' => true
I'm trying to get the facebook sdk to store a cookie from my website onto the persons computer that tries to login but no cookie is being set.
I get confused by your question. what do you want to achieve:
1) If you want to set store your facebook user_id to cookie, you don't have to do anything. when the oauth process is completed facebook redirect to your "redirect_uri" url, the cookie is set by facebook to a cookie value: fbsr_xxxx (xxxx is your appId)
2) If you want to keep user logged in longer time, you need to set your own session value to determine if the user is logged in or not. in other word, after the facebook oauth flow, your user login status has nothing to do with your facebook session.
BTW: $Users->loginWithOauth, this function has no definition, what's this function for?
the reason is the required permission not granted so eventually it goes to facebook search for the token and comes back.
check for the permission you need.
I'm struggling to find a way to detect if users are not connected to my application, I want to send the activity 'View' an 'Item' which works perfectly fine, but they have to click a login link first, when just reloads the page and they are logged in.
How can I make this happen automatically? How can you check if the user is connected to the app?
I have tried the following code, but users who are not connected just get a blank page.
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
// Check if logged in
if($user_id) {
$params = array(
'ok_session' => 1, // Logged in and connected
'no_user' => 2, // Logged out of facebook
'no_session' => 3, // Logged in but not connected
);
$next_url = $facebook->getLoginStatusUrl($params);
if($next_url == 2 || $next_url == 3){
header('Location: '.$facebook->getLoginUrl(array('scope' => 'publish_stream')));
}
} else {
// Not logged in
header('Location: '.$facebook->getLoginUrl(array('scope' => 'publish_stream')));
}
There doesn't seem to be a function that checks if the user is connected so I made use of the getLoginUrl function.
$user_id is supplied by $user_id = $facebook->getUser();
If we are talking canvas/page tab app here, then the info you’re looking for is in the signed_requestparameter your app gets passed on initial load.
If not – “outside” of Facebook the PHP SDK has no way of knowing if there’s a user visiting your page that has used your app before if there aren’t any cookies set for your domain remaining that say so.
You can use FB.getLoginStatus out of the JS SDK – that will make a cross-domain request to Facebook to see if the user is logged in, and can set the appropriate cookies under your domain that’ll let the PHP SDK take notice on the next request to your server as well.
I am having trouble using permissions to upload to a specific Facebook album.
I am set to an admin to a specific Facebook page, however whenever I try to upload a photo I cannot seem to get access to do it.
The error I get is:
Fatal error: Uncaught OAuthException: (#120) Invalid album id thrown
If I explore using the Graph explorer, I can see this album without any access token required.
The URL I am using is https://graph.facebook.com/albumId/photos
The album I am trying to upload is an album within a Facebook page, which I created within Facebook.
The permissions I have set are:
user_photos
friends_photos
publish_actions
manage_pages
publish_stream
photo_upload
Any help appreciated.
First, check if the user is logged in:
function getLoginStatus() {
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
// the user is logged in and connected to your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
getPageAccess();
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
//but not connected to the app
logIn();
} else {
// the user isn't even logged in to Facebook.
logIn();
}
});
}
Then get the page access token associated to the user:
function getPageAccess() {
FB.api('/PAGE_ID?fields=access_token', function (resp) {
var pageAccessToken = resp.access_token;
});
}
This seems a common issue. If you want to impersonate Facebook Page (that is, act as page itself for uploading, posting and sharing) you have to first obtain an access token for that page:
Issue a GET Request to '/me/accounts' using user access token
Loop the result set and look for the page (pay attention to category property of each item, skip "application" as it's considered an account)
Store access token for that page.
Then (using PHP SDK):
$page = '432652662'; // Your page id
$album = '128949205'; // Your album id
$source = 'mypic.png';
$payload = array('source' => '#' . $source,
'access_token' => 'page access token');
// Upload photo for specific page and album
$sdk->api("/$page/$album/photos", 'POST', $payload);
Ok, I think I have found the solution.
If you go to https://graph.facebook.com/me/accounts
Each account will have its own access_token. When uploading an image to a Facebook page, you will need to pass that access_token as a parameter.
i want to authenticate my facebook profile with my website so i can pull infor from the page.
i was suggested to one time authenticate with the facebook api through a temp page. somewhat like:
<fb:login-button params="some permission" />
i am new to coding facebook apps. but this seems like fbml. how can i use it to authenticate my website with my own profile. i dont need users to log into my website. i just need to pull info from my page.
the facebook documentation is sparse and fragmented. all i got for the Login was this code fragment. I dont understand how i can authenticate a weblink through this method.
FB.login(function(response) {
if (response.session) {
// user successfully logged in
} else {
// user cancelled login
}
});
can anyone throw some light??
Let's start from the beggining:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml" xml:lang="en" lang="en">
It's required for fbml to work. Next:
<fb:login-button autologoutlink="true"></fb:login-button>
<div id="fb-root"></div>
These two lines create the "facebook login button", you should place them in your html where you want the button to appear.
Right before your closing body tag add:
<script type="text/javascript" src="https://connect.facebook.net/en_US/all.js"></script>
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'YOUR APP ID HERE', status: true, cookie: true, xfbml: true});
FB.Event.subscribe("auth.login", function(response) {
if(response.session) {
// this is where you handle facebook's response
}
});
};
</script>
What you are doing here is first initializing the connection to facebook, with your app id (you need to create an application), and register an "auth.login" event. The auth.login event is triggered every time you click the facebook login button and successfully login to facebook, or facebook auto logins you based on their cookie.
You can find an explanation of the auth.login and other events here, look at the sidebar at the left, all events are listed.
The response is JSON formatted and it contains your basic session information:
{
status: 'connected',
session: {
access_token: '...',
expires:'...',
secret:'...',
session_key:'...',
sig:'...',
uid:'...'
}
}
You can read more about it here. If your status is indeed "connected" the next most important bit of information is the uid, this is your unique facebook identifier, a public id with which you can send further requests to facebook. What you do with the response is up to you. An obvious choice would be to send it via ajax to a script that logs you in your application.
To get more info from facebook you need to download the php sdk. To use the sdk:
<?php
include_once "facebook-sdk-3.0.0/src/facebook.php";
$appID = "YOUR APP ID";
$appSecret = "YOUR APP SECRET";
$cookie = "fbs_{$appID}";
$cookie = isset($_COOKIE[$cookie]) ? trim($_COOKIE[$cookie], '"') : "";
if(empty($cookie)) {
echo "no facebook cookie";
die();
}
parse_str($cookie, $data);
$facebook = new Facebook(array(
"appId" => $appID,
"secret" => $appSecret,
"cookie" => true
));
$facebook->setAccessToken($data["access_token"]);
$user = $facebook->getUser();
$profile = $facebook->api("/me");
?>
So at first you parse facebook's cookie which is named "fbs_YOUR_APP_ID" and contains your session information (url encoded). What you actually need is the access_token (a unique identifier of the authenticated session), which was also returned to you in the JSON response object before. Then via the Facebook object you can do and api requests you want.
Now to have a full authentication mechanism you should create a similar connect script that instead of getting the session information from the cookie it should take them from the response object that is returned when auth.login occurs (possibly via ajax).
You should read the Authentication workflow document to better understand how facebook connect works.
A good and easy way to deal with Facebook authentication is to implement the server side flow with the Facebook PHP SDK (see on github). So you will have something like :
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$user = $facebook->getUser();
If the user is logged in, then $user is his Facebook ID. You then have to check if you have a valid access token by making an API call :
If it does not raise any exception, then you have a valid access token
If it does, then you have to re-authenticate the user.
Here :
if ($user) {
try {
$facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
You need then to display the login or logout link :
<?php if ($user): ?>
Logout of Facebook
<?php else: ?>
Login with Facebook
<?php endif ?>
When the user is logged in and you have a valid access token, you can make API calls to get data from Facebook :
$user_profile = $facebook->api('/me');
You may want to check the example page of the Facebook PHP SDK which is well documented.
Hope that helps.