Facebook API: Logging in, but still not working - php

I'm using the Facebook API connected script written in PHP (provided by Facebook). Everything works, it generates the login URL and redirects me back to the website when I'm logged in.
However, the $user variable seems to be undefined.
Have anyone experienced a similar problem? In the Facebook Apps statistics page I can see that the app has been used.
Update - The code:
<?php
$app_id = "xxxxxxxxxxxxxx";
$app_secret = "xxxxxxxxxxxxx";
$site_url = "http://xxx";
try{
include_once "src/facebook.php";
}catch(Exception $e){
error_log($e);
}
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret
));
if($user = $facebook->getUser())
{
echo 'ok';
}
else
{
}
if($user){
//==================== Single query method ======================================
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;
}
//==================== Single query method ends =================================
}
if($user){
// Get logout URL
$logoutUrl = $facebook->getLogoutUrl();
}else{
// Get login URL
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email,user_birthday,user_about_me',
'redirect_uri' => $site_url . '/auth_complete.php',
));
}
if($user){
// Proceed knowing you have a logged in user who has a valid session.
//========= Batch requests over the Facebook Graph API using the PHP-SDK ========
// Save your method calls into an array
$queries = array(
array('method' => 'GET', 'relative_url' => '/'.$user),
array('method' => 'GET', 'relative_url' => '/'.$user.'/home?limit=50'),
array('method' => 'GET', 'relative_url' => '/'.$user.'/friends'),
array('method' => 'GET', 'relative_url' => '/'.$user.'/photos?limit=6'),
);
// POST your queries to the batch endpoint on the graph.
try{
$batchResponse = $facebook->api('?batch='.json_encode($queries), 'POST');
}catch(Exception $o){
error_log($o);
}
//Return values are indexed in order of the original array, content is in ['body'] as a JSON
//string. Decode for use as a PHP array.
$user_info = json_decode($batchResponse[0]['body'], TRUE);
$feed = json_decode($batchResponse[1]['body'], TRUE);
$friends_list = json_decode($batchResponse[2]['body'], TRUE);
$photos = json_decode($batchResponse[3]['body'], TRUE);
//========= Batch requests over the Facebook Graph API using the PHP-SDK ends =====
}
?>

I'm not entirely sure why it worked, but I redirected the user to a page where the Javascript SDK is included (http://developers.facebook.com/docs/reference/javascript/), and now it's working!

The user have not authorized the app yet. Try something like this-
$user_id = $facebook->getUser();
echo $uid;
if($user_id){
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user_id = null;
}
}else{
$login_url = $facebook->getLoginUrl();
echo("<br>login url=".$login_url);
};

An FB app of ours that previously worked for months is now experiencing the issue you speak of. $fb_user is now being returned undefined. =(

Update your SDK, sounds like you are hitting a certificate issue from a few weeks back.
You can find the latest version at https://github.com/facebook/facebook-php-sdk/

Related

Facebook: PHP SDK issues

I have some facebook php code that worked flawlessly before the 4/30/15 upgrade. I upgraded my code, it seems to work on certain computers but not on others. On computers that it doesn't work on I've tried multiple browsers with the same result. I am able to log into Facebook using the SDK, but it won't post anything to my page's wall. Same code, different computer, and everything works fine. Here's the code:
<?php
$facebook = new Facebook(array(
'appId' => '##########',
'secret' => '##########',
'fileUpload' => true
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
}
catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl(array(
'next' => ($user['baseurl'] . 'logout.php')
));
} else {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'publish_pages , manage_pages'
));
}
$access_token = $facebook->getAccessToken();
$params = array(
'access_token' => $access_token
);
#The id of the fanpage
$fanpage = '############';
#The id of the album
$album_id = '############';
if ($user) {
$accounts = $facebook->api('/me/accounts', 'GET', $params);
foreach ($accounts['data'] as $account) {
if ($account['id'] == $fanpage || $account['name'] == $fanpage) {
$fanpage_token = $account['access_token'];
}
}
$message = 'Post this to the wall.';
$img = 'path to image.jpg';
$args = array(
'message' => $message,
'image' => '#' . $img,
'aid' => $album_id,
'no_story' => 0,
'access_token' => $fanpage_token
);
$photo = $facebook->api($album_id . '/photos', 'post', $args);
}
?>
Most permissions need to get approved by Facebook before they can be used for any user, else they only work for users with a role in the App. Check out the docs about Login Review.
You can only use publish_pages and manage_pages as App Admin/Developer/Tester without review.
If you only test with those users and it still does not work, debug the Access Token in the Debugger and see if those permissions are really authorized: https://developers.facebook.com/tools/debug/
Edit: After reading your comment, i believe you are trying to use a User Token. Use /me/accounts to get a Page Token and try again with that one. If you debug the Token, make sure the Page shows up too.

Fceabook PHP SDK valid access token

I have search over and over again and I can't seem to find an answer. What am I doing wrong?
My error is FacebookApiException [ 0 ]: An active access token must be used to query information about the current user.
EDIT Just to add. This worked once or twice, but never in succession.
require_once('media/fb/facebook.php');
$app_id = '123456';
$app_secret = '123456';
$my_url = 'mysiteurl';
$config = array(
'appId' => $app_id,
'secret' => $app_secret,
'fileUload' => 'false');
$facebook = new Facebook($config);
$user = $facebook->getUser();
if($user) {
try {
$user_profile = $facebook->api('/me','GET');
} catch(FacebookApiException $e) {
error_log($e->getType());
error_log($e->getMessage());
}
} else {
$login_url = $facebook->getLoginUrl(array('redirect_uri' => $my_url));
header("Location:" . $login_url);
$user_profile = $facebook->api('/me','GET');
}
Your help is greatly appreciated.
Does your error come from this line: $user_profile = $facebook->api('/me','GET'); at the bottom?
The header function will re-direct the user to Facebook login page which will cause the browser to refresh. You won't get the user's access token immediately after that. You need to wait until the user is redirected back to your website to get the access token. You need to set $my_url to point to the same page of the codes you wrote here.

$facebook->api('/me') not giving the user data

require_once($_SERVER['DOCUMENT_ROOT'] . '/facebook-php-sdk/facebook.php');
$facebook = new Facebook(array(
'appId' => FB_MAIN_APP_API_ID,
'secret' => FB_MAIN_APP_SECRET
));
// Get User ID
$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) {
error_log($e);
$user = null;
}
}
Above is the code I'm using to get the Facebook details for my application. In my localhost this is working fine and it gives my Facebook email, user id. After I upload this in to live server this function is not working and it's not giving my Facebook details. I checked on the Facebook app id and it is the correct one.
I cannot figure out why it's not working in live site since it is working in my localhost. Please help me with this. Thank you.
I think problem is in your app which your are using on server. So try the same app which you are using for your localhost and in login and logout url instead of localhost use $_SERVER['HTTP_HOST'].
Example :
$session->fb_logout = $facebook->getLogoutUrl(array('next' => "http://" . $_SERVER['HTTP_HOST'] . "/path/to/logout"));
First check that what $user_profile = $facebook->api('/me'); showing. Just print_r the variable $user_profile.
Ex :
$user_profile = $facebook->api('/me');
print_r($user_profile);
exit;
if it showing blank then surely it will go in catch block. Then write following in catch block.
print_r($e);
exit;
For geting the user id, user need to grant permission
$user_id = $facebook->getUser();
echo $uid;
if($user_id){
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user_id = null;
}
}else{
$login_url = $facebook->getLoginUrl();
echo("<br>login url=".$login_url);
};
After the user grant permission check the login_url, you may access user id.
Try this
Have you checked you have the correct URL in the configuration of your app in Facebook?
I have this piece of code to my FB apps and work properly, could you try it?
$session = $this->facebook->getUser();
if ($session) {
$logoutUrl = $this->facebook->getLogoutUrl();
try {
$data['uid'] = $this->facebook->getUser();
$me = $this->facebook->api($session);
$data['me'] = $me;
} catch (FacebookApiException $e) {
error_log($e);
}
} else {
$loginUrl = $this->facebook->getLoginUrl(
array(
'scope' => 'publish_stream, user_about_me, email',
'redirect_uri' => 'YOUR URL',
'canvas' => 1,
'fbconnect' => 0,
'display' => 'page',
));
}
if (!$session) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
$this->load->view('MY VIEW', $data);

Facebook API OAuth Excpetion #200 with '&scope=publish_steam'

Trying to post a status update using facebook php sdk. Code posted below. As I understand it, I need ask for extended persmission, which I do in the login URL with '&scope=publish_stream', but this still isn't working.
The resultant login URL looks like:
https://www.facebook.com/login.php?api_key=174954539217971&cancel_url=http%3A%2F%2Fexample.com%2facebook.post.php&display=page&fbconnect=1&next=http%3A%2F%2Fexample.com%2Ffacebook.post.php&return_session=1&session_version=3&v=1.0&scope=publish_stream
So you can see it is being set. While this is essentially the same question as: Facebook OAuthException: "user hasn't authorized the application to perform this action"
The suggested solution in that thread is not working here.
<?php
echo "Posting to facebook..<br/>";
require './fb_src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'appId',
'secret' => 'secret',
'cookie' => true,
));
$session = $facebook->getSession();
$me = null;
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
header('Location: ' . $facebook->getLoginUrl(array('scope' => 'publish_stream')));
error_log($e);
}
}
else {
header('Location: ' . $facebook->getLoginUrl(array('scope' => 'publish_stream')));
}
print_r($me);
try {
$feed = $facebook->api('/me/feed', 'post', array('message' => 'Hello world!', 'cb' => ''));
} catch (FacebookApiException $e) {
print($e);
}
print_r($feed);
?>
parameter is 'req_perms' not 'scope'. So hard to find good documentation...
Works fine now.

Facebook Iframe application authentication?

I have developed a Facebook application that runs inside an iframe in the Facebook canvas. For it to work properly I request extended permissions from the user. If the user hasn't authorized the application I send him/her to a login page with the getLoginUrl() method in the PHP SDK.
It works, but it's not pretty. The method sends the user to a landing page before the authentication page. It looks like this:
When I click "Go to Facebook.com" I see the actual page for permission requests (I also get right to the permissions page if I print the url, copy it and enter it into a new browser window). How do I make Facebook skip this step when I do the redirect from an Iframe?
My code looks like this (using CodeIgniter and Facebook PHP SDK):
$this->facebook = new Facebook(array(
'appId' => '{MY_APP_ID}',
'secret' => '{MY_SECRET}',
'cookie' => TRUE,
'domain' => $_SERVER['SERVER_NAME']
));
$this->facebook->getSession();
try {
$this->me = $this->facebook->api('/me');
}
catch (FacebookApiException $e) {
$this->me = NULL;
}
if ( is_null($this->me) ) {
redirect($this->facebook->getLoginUrl(array(
'req_perms' => 'offline_access,read_stream,publish_stream,user_photos,user_videos,read_friendlists',
'next' => $this->config->item('base_url').'fblogin.php?redirect_uri='.$this->uri->uri_string()
)));
}
I think you need to redirect the parent frame (i.e. _top) rather than the iFrame itself?
The way I do it is set up an INDEX.PHP file with the following
//if user is logged in and session is valid.
if ($fbme){
//fql query example using legacy method call and passing
parameter
try{
$fql = "select name, hometown_location, sex,
pic_square from user where uid=" .
$uid;
$param = array(
'method' => 'fql.query',
'query' => $fql,
'callback' => 'http://apps.facebook.com/yoursite/'
);
$fqlResult = $facebook->api($param);
}
catch(Exception $o){
d($o);
}
}
Then point your canvas url to http://yoursite.com/INDEX.php
The callback url in the above code which will be in INDEX.PHP sets where to look after permissions are granted.
FBMain.php looks like this
//set application urls here
$fbconfig['http://www.yoursite.com/iframeapp/YOURMAINPAGE.php/']
= "http://www.tyoursite.com/YOURMAINPAGE.php/";
$fbconfig['http://apps.facebook.com/CANVASBASEURL']
= "http://apps.facebook.com/CANVASBASEURL";
$uid = null; //facebook user id
try{
include_once "facebook.php";
}
catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['APPID'],
'secret' => $fbconfig['SECRET'],
'cookie' => true,
));
//Facebook Authentication part
$session = $facebook->getSession();
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms'=>'email,publish_stream,status_update,user_birthday,user_location'
)
);
$fbme = null;
if (!$session) {
echo "<script type='text/javascript'>top.location.href
= '$loginUrl';";
exit;
}
else {
try {
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo "<script type='text/javascript'>top.location.href
= '$loginUrl';";
exit;
}
}
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
} ?>
Hope its a little clearer. It took me a while to figure it out, but I got there, thought I would help.

Categories