This piece of code used to work as expected, but now it seems i can't retrieve the user name the same way:
$uid = $facebook->getUser(); // returns the facebook id of the user
$me = $facebook->api('/me'); // returns empty. why?
Due some facebook api updates i had to change the getSession from:
$session = $facebook->getUser();
to
$session = $facebook->getUser()>0;
So how to retrieve the user name in facebook?
So how to retrieve the user name in facebook?
What about this :
$pageContent = file_get_contents('http://graph.facebook.com/USERID');
$parsedJson = json_decode($pageContent);
echo $parsedJson->name;
Facebook use CURL for send request to server, maybe curl on your server not work or curl_exec is disabled
Related
I getting this error message suddendly and i don't know why because my fb app ran perfectly. My hosting guy said the he moved my site to another server, but he kept the same configuration.
this is my facebook app code:
include 'config.php';
$user = $facebook->getUser();
echo $user;
$loginUrl = $facebook->getLoginUrl(array (
'scope' => 'publish_actions,public_profile,user_friends',
'redirect_uri' => 'http://attila-naghi.com/fb/mytest/test.php'
));
echo 'Login Here ';
and this is the test.php file:
$user = $facebook->getUser(); // here it crashed for some god know reason
if ($user) {
try{
$user_profile = $facebook->api('/me');
$fbid = $user_profile['id']; // To Get Facebook ID
$fbfullname = $user_profile['name']; // To Get Facebook full name
$femail = $user_profile['email']; // To Get Facebook email ID
//FACEBOOK POST
}catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
........
I created a new facebook application, but still the same. I moved in another folder the but still the same. I'm out of idea why I'm still getting this. Can you give some idea ? thx
Just a shot in the dark, but do you have php CURL installed on your new server? Usually request such as these require some back and forth which usually comes in the form of a CURL request, but there are other ways :)
I know there are tons of topics
on this question, but every single one that I've seen, seems to have no solution at all!
I'm getting the infamous "Oauth Exception - An active access token must be used to query information about the current user" and I don't know what to do.
My facebook connect was working perfectly fine until yesterday, now, it stopped working all of a sudden today.
Can anyone please help me with this?
I'm using php sdk to connect the user to facebook in a pop-up window, then I make him autorize my app and redirect the window to a php called facebookReturn.php.
In this file, I'm supposed to get the user info, save it on Session, then close the window and refresh the main page behind.
Here are my codes.
index.php:
require_once 'phps/facebook.php';
$config = array();
$config[appId] = 'xxxx';
$config[secret] = 'xxxx';
$config[fileUpload] = false;
$facebook = new Facebook ($config);
$facebookId = $facebook->getUser();
echo "<br>facebook id: $facebookId";
if ($facebookId) {
$userProfile = $facebook->api('/me');
$logoutUrl = $facebook->getLogoutUrl();
}
else {
$params = array ();
$params[scope] = 'publish_stream, user_birthday, email, user_activities';
$params[redirect_uri] = 'http://www.mydomain.com.br/phps/facebookReturn.php';
$params[display] = 'popup';
$loginUrl = $facebook->getLoginUrl($params);
}
facebookReturn.php:
require_once 'facebook.php';
$config = array();
$config[appId] = 'xxxx';
$config[secret] = 'xxxx';
$config[fileUpload] = false;
$facebook = new Facebook ($config);
$user = $facebook->getUser();
$userProfile = $facebook->api('/me');
Thank you in advance.
Remomber: Facebook token expires in 60 days.
I'm trying to get the UID of the connected user with Facebook SDK for PHP, but it doesn't work, and all other things work properly; it means that the problem is not in the connection to the application.
I tried this code but it is always returning 0 while I'm connected to Facebook; I even tried with other accounts but no solution.
$uid = $facebook->getUser();
$facebook = facebook_get();
$uid = $facebook->getUser();
echo $uid;
and here's facebook_get()
function facebook_get()
{
include('lib/fbapi/facebook.php');
$config = array();
$config['appId'] = '...';
$config['secret'] = '...';
$facebook = new Facebook($config);
return $facebook;
}
Can you post your authentication code you've coded or you're using?
If you post, we can look into your code and give you the answer to why it's returning 0, it could be your authentication code which is not coded properly or it could be config error.etc.
Is it possible to check if a user already likes my facebook fanpage from my website with Javascript or PHP?
EDIT: I need a solution, so the user doesn't need to authenticate / allow some persmissions first
<?php
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'APP_ID',
'secret' => 'APP_SECRET',
));
$user = $facebook->getUser();
$page_id = "123456789";
$page_name = $facebook->api("/".$page_id)['name'];
$page_link = $facebook->api("/".$page_id)['link'];
if ($user) {
try {
$likes = $facebook->api("/me/likes/".$page_id);
if( !empty($likes['data']) )
echo "I like!";
else
echo "not a fan!";
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'user_likes'
));
}
// rest of code here
?>
The simplest way would be to call the Graph API to get the /me/likes connections (note you have to require the user_likes permission). Then go through each and compare id with the ID of your page.
Assuming you're using the official Facebook PHP SDK, and have an instance of the Facebook object set up (see Usage section in the aforementioned page), the following code can be used to find out if the user is fan of Daft Punk:
$our_page_id = '22476490672'; // This should be string
$user_is_fan = false;
$likes = $facebook->api( '/me/likes?fields=id' );
foreach( $likes['data'] as $page ) {
if( $page['id'] === $our_page_id ) {
$user_is_fan = true;
break;
}
}
Now, you can further work with the $user_is_fan variable.
In JavaScript, the code would be very similar. Using the official JavaScript SDK's method FB.api (again, assuming you have taken of the authentication):
FB.api('/me/likes?fields=id', function(response) {
var our_page_id = '22476490672';
var user_is_fan = false;
var likes_count = response.data.length;
for(i = 0; i < likes_count; i++) {
if(response.data[i].id === our_page_id) {
user_is_fan = true;
break;
}
}
});
Note that here we're using an asynchronous request and callback, so the code using the user_is_fan variable must be inside the function.
In case you are OK with user giving the permissions, for a PHP based website it can be done this way easily:
1- Create a new Facebook app here.
2 - Download Facebook PHP SDK from here. Extract the files and place it in the same folder with the file in which you will paste the code given below!
3 - Get your Facebook Page ID using this tool.
4 - Generate Facebook like box code for your page from here.
After 1, 2, 3 and 4 steps are complete, you can check if user has liked a page or not with the following code:
<?php
require('facebook.php');
$config = array(
'appId' => 'your facebook app id',
'secret' => 'your facebook app secret code',
'allowSignedRequest' => false
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if (isset($user_id)) {
try {
$likes = $facebook->api('/me/likes/your_facebook_page_id_here', 'GET');
if (!empty($likes['data'])) // if user has liked the page then $likes['data'] wont be empty otherwise it will be empty
{
echo 'Thank you for liking our fan page!';
}
else {
echo 'You have not liked our fan page! Like it now:';
?>
<iframe src="//www.facebook.com/plugins/likebox.php?href=https%3A%2F%2Fwww.facebook.com%2Fchillopedia&width&height=290&colorscheme=light&show_faces=true&header=true&stream=false&show_border=true&appId=1392604484339363" scrolling="no" frameborder="0" style="border:none; overflow:hidden; height:290px;" allowTransparency="true"></iframe> //replace this with your own Facebook like box code
<?php
}
} catch (FacebookApiException $e) {
$login_url = $facebook->getLoginUrl();
echo 'Please click here to login into your Facebook account.';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
$login_url = $facebook->getLoginUrl();
echo 'Please lick here to login into your Facebook account';
}
?>
The user will click on the "Please click here to login into your Facebook account." text which will redirect it to Facebook app permissions page, once user allows the permission to your app the code will fetch user's data and will display the likebox if user hasn't liked your fan page.
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : 'YOUR_APP_ID_WITHIN_QUOTES', //Change this to your app id
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
</script>
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
$has_liked = $data["page"]["liked"];
now check the $has_liked param to see if user likes ur page or not!
seems like "/me/likes/[page_id]" doesn't always return the record even there is one.
recently I request by "/me/likes/[page_id]", it will return 0,
but if I request without page_id, but grab a bunch of record by "/me/likes/", and you will see the page_id is actually there, can't figure why.
when checking with graph.facebook.com/[page_id], only suspicious thing is its "can_post" is false, and others which "/me/likes/[page_id]" do works, is true.
but looping is not good in this situation, especially some crazy people has millions of likes.
is there any kinda privacy setting related to the page_id owner account would cause the problem?
i have a problem with my facebook canvas app that is currently on development i'm working on http://localhost:8080
my canvas url is http://localhost:8080/fbcanvas/
on facebook the url is set to http://apps.facebook.com/app_name/
the problem is i'm getting a code as an $_GET['code'] variable after a user approves my app.
in facebook documentation it doesnt say anything about getting a $_GET['code'] it just says getting signed_request
this is the code i'm using from facebook examples.
require_once($_SERVER['DOCUMENT_ROOT'] . '/classes/Page.php');
require($_SERVER['DOCUMENT_ROOT'] . '/core/config.fb.php');
$canvas_page = 'http://apps.facebook.com/khawamusic/';
$auth_url = 'https://www.facebook.com/dialog/oauth?client_id=' . $app_id . '&redirect_uri=' . urlencode($canvas_page);
$signed_request = $_REQUEST['signed_request'];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if(empty($data['user_id'])) {
echo('<script> top.location.href="' . $auth_url .'";</script>');
} else {
$page = new Page;
$styles = array('reset.css', 'fbcanvas.css');
$scripts = array(
'https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js',
'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js',
'http://connect.facebook.net/en_US/all.js#xfbml=1',
'/sources/js/fbcanvas.js'
);
$page->set_title('Khawa');
$page->set_styles($styles);
$page->set_scripts($scripts);
$page->start_page();
require($_SERVER['DOCUMENT_ROOT'] . '/fbcanvas/fb.tpl');
$page->end_page();
}
so what happens is a user approves my app then he gets redirected to http://apps.facebook.com/khawamusic/?code=blabla
i'm cnfused because in the documentation it doesn't say i'm suppose to get a $_GET['code']
If the user presses Allow, your app is authorized. The OAuth Dialog will redirect (via HTTP 302) the user's browser to the URL you passed in the redirect_uri parameter with an authorization code:
http://YOUR_URL?code=A_CODE_GENERATED_BY_SERVER
With this code in hand, you can proceed to the next step, app authentication, to gain the access token you need to make API calls.
Refer: https://developers.facebook.com/docs/authentication/
EDIT:
Here's a sample of the authentication, this won't show ?code=Blabla..
First download the latest Facebook PHP SDK from here: https://github.com/facebook/php-sdk/tree/master/src
Make sure you save all 3 files, facebook.php, base_facebook.php and fb_ca_chain_bundle.crt
Now replace the text "YOUR_APP_ID" and ""YOUR_APP_API_SECRET" with your Application ID and App Secret from facebook, I've added sample wall posting using graph api, if you don't want, you can remove it, if you go through my codes and comments, you'll understand what it does and you don't want to do anything to get access token, just use $access_token variable and it'll give you the access_token of the current user and if you want the user's ID then use $user variable, if you want user's basic information, use $userInfo variable and it'll fetch user's data using graph api and returns all information in an array, you'll get the current user's info like id,name,first_name,last_name,link,hometown,location,bio,work,education,gender,timezone.etc.
Change $RedirectUrl with your landing page URL or your canvas page url
<?php
require 'facebook.php';
define('FACEBOOK_APP_ID', "YOUR_APP_ID"); // Your App ID
define('FACEBOOK_SECRET', "YOUR_APP_API_SECRET"); // Your App API Secret
$RedirectUrl = "http://apps.facebook.com/myapp/"; // Your Landing Page URL, User's will be redirect to this URL after they allow your app.
function d($d){
echo "<pre>";
print_r($d);
echo "</pre>";
}
$user = null;
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
'cookie' => true,
));
$user = $facebook->getUser(); // Get the UID of the connected user, or 0 if the Facebook user is not connected.
if(isset($_GET['code'])){
header("Location: $RedirectUrl");
}
if($user == 0) {
// If User is not connected to your app, then redirect User to Authentication Page.
/**
* Get a Login URL for use with redirects. By default, full page redirect is
* assumed. If you are using the generated URL with a window.open() call in
* JavaScript, you can pass in display=popup as part of the $params.
*
* The parameters:
* - redirect_uri: the url to go to after a successful login
* - scope: comma separated list of requested extended perms
*/
$login_url = $facebook->getLoginUrl($params = array('scope' => "publish_stream", 'redirect_uri' => $RedirectUrl));
echo("<script> top.location.href='" . $login_url . "'</script>");
} else {
// If User is connected to your app, then do something.
$signed_request = $facebook->getSignedRequest(); // Get the data from a signed_request token.
$access_token = $facebook->getAccessToken(); // Determines the access token that should be used for API calls.
$userInfo = $facebook->api("/me"); // Get's User Info
try {
// Posts to user's wall after the user allows your app.
$wallpost = array(
'message' => "I like this",
'link' => 'http://google.com',
'picture' => 'http://i.imgur.com/8iz6L.png',
'name' => 'This is cool',
'description'=> 'Checkout this cool app'
);
$publishStream = $facebook->api("/$user/feed", "post", $wallpost); // WallPost to User's Wall using Graph API
echo "Your post was successfully posted to UID: $user";
}
catch (FacebookApiException $e) {
d($e);
}
}
?>
i'm not yet sure but i think i have the answer to the process of authorizing / authenticating a facebook app...
step 1 : the first time a user access your app facebook sends you a signed request and you need to parse it validate it and check if the $data['user_id'] is set.
the code:
$data = $canvas->parse_signed_request($signed_request);
$auth_url = 'http://www.facebook.com/dialog/oauth?client_id=' . $app_id . '&redirect_uri=' . urlencode($canvas_page);
if(empty($data['user_id'])) {
echo '<script>top.location.href="' . $auth_url . '"</script>';
}
so if the $data['user_id'] is empty go authenticate.
step 2: the user authorizes your app facebook sends you a signed request and a code
if(isset($_REQUEST['code'])) {
$access_token = $canvas->get_access_token($_REQUEST['code']);
$user = $canvas->getUser($access_token);
$user_info = array(
'user_id' => $user->id,
'user_username' => $user->username,
'user_name' => $user->name
);
// install the application for the new user.
$user_obj = new User($user_info);
// registered or allready exists.
if($user_obj) {
echo '<script>top.location.href="' . $canvas->canvas_page . '";</script>';
}
exit();
}
so from what i understood facebook sends you $_REQUEST['code'] just one time: when the user approves your canvas application.
that's it the user is installed so now every time a user re enters your application you will get a signed_request
but this time because the user already approves the application the signed request will include an user_id and oauth_token with it u can get stuff from the graph api.
IF THE SIGNED_REQUEST HAVE A USER_ID THIS IS WHAT U DO.
if(isset($data['user_id'])) {
$user = false;
if(!$user) {
$user = $canvas->getUser($data['oauth_token']);
}
if(!ob_start('ob_gzhandler')) ob_start();
$styles = array(
'reset.css', 'jplayer.fbcanvas.css', 'fbcanvas.css'
);
$scripts = array(
'http://connect.facebook.net/en_US/all.js#xfbml=1',
'http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js',
'/sources/js/jplayer/jquery.transform.js',
'/sources/js/jplayer/jquery.grab.js',
'/sources/js/jplayer/jquery.jplayer.js',
'/sources/js/jplayer/mod.csstransforms.min.js',
'/sources/js/jplayer/circle.player.js',
'/sources/js/fbcanvas.js'
);
$results = $canvas->getLatestSongs();
// the canvas.
$page->set_title('Khawa');
$page->set_styles($styles);
$page->set_scripts($scripts);
$page->start_page();
require($_SERVER['DOCUMENT_ROOT'] . '/fbcanvas/fb.tpl');
$page->end_page();
ob_end_flush();
}
again i'm not sure but i think this is the process of authentication for FACEBOOK CANVAS APPS.