Facebook PHP API: getUser returns 0 - php

Using Codeigniter framework with Facebook's PHP SDK and Javascript SDK.
Here is my code.
public function __construct(){
parent::__construct();
$this->load->library('session');
$this->config->load('facebook');
$this->load->library('Facebook',array('appId'=>$this->config->item('appID'),'secret'=>$this->config->item('appSecret')));
}
function fblogin(){
$base_url=$this->config->item('base_url');
$user = $this->facebook->getUser();
log_message('info','>>>>>>>>>>>>User id is::'.$this->config->item('appID').'::'.$this->config->item('appSecret').' For session '.session_id());
if($user == 0){
$loginUrl = $this->facebook->getLoginUrl(array("scope"=>"user_about_me"));
redirect("$loginUrl","location");
}
if($user){
try{
$user_profile = $facebook->api('/me');
$params = array('next' => $base_url.'fbci/logout');
$ses_user=array('User'=>$user_profile,
'logout' =>$facebook->getLogoutUrl($params)
);
$this->session->set_userdata($ses_user);
redirect('/','refresh');
header('Location: '.$base_url);
}catch(FacebookApiException $e){
log_message('error',error_log($e));
$user = NULL;
}
}
Javascript
FB.login(function(response) {
console.log('fb respone'+response.serialize());
if(response.authResponse) {
parent.location ="<?php echo site_url('fbci/fblogin');?>";
}
},{scope: 'email,read_stream,publish_stream,user_birthday,user_location,user_work_history,user_hometown,user_photos'});
});
Added Facebook.php and base_facebook.php in libraries folder. This code looks straight forward but not getting what is wrong with it.

Related

facebook login with codeigniter error URL blocked

I have a code from a tutorial to login with facebook. Now when i go to the login with facebook, it says error with
URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs.
I already configure my appsettings with the settings in this screenshot:
setup from Oauth:
i am using codeigniter with these codes :
<?php
include(APPPATH.'libraries/facebook/src/facebook.php');
class Connect extends Facebook {
public $user = null;
public $user_id = null;
public $fb = false;
public $fbSession = false;
public $appkey = 0;
public function Connect() {
$ci =& get_instance();
$ci->config->load('facebook',TRUE);
$config = $ci->config->item('facebook');
// echo $config['appId'];
parent::__construct($config);
$this->user_id = $this->getUser();
$me = null;
if($this->user_id){
try {
$me = $this->api('/me');
$this->user = $me;
} catch (FacebookApiException $e) {
error_log($e);
}
}
}
}
and with this in my controller:
public function facebook_request(){
$data = array (
'redirect_uri' => base_url('authentication/handle_facebook_login'),
'scope' => 'email'
);
var_dump($data);
$this->load->library('connect');
redirect($this->connect->getLoginUrl($data));
}
public function handle_facebook_login() {
$this->load->library('connect');
if($this->connect->user) {
print_r($this->connect->user);
} else {
}
}

Facebook Login/Registration with Codeigniter - user data

I have a problem with the user data - the only data that I recieve after Facebook Login is 'name' and 'id', which is the facebook id of the user. I also need to recieve 'firstname', 'lastname' and 'email.
I'm testing the website at localhost and I've created app in developers.facebook.com
Maybe the problem is that the app is in developing mode and that's why it's not giving me the full data?
Here is my code of taking the user data:
<?php
include(APPPATH.'libraries/facebook/facebook.php');
class Fbconnect extends Facebook {
public $user = null;
public $user_id = null;
public $fb = false;
public $fbSession = false;
public $appKey = 0;
public function Fbconnect() {
$ci =& get_instance();
$ci->config->load('facebook', TRUE);
$config = $ci->config->item('facebook');
parent::__construct($config);
$this->user_id = $this->getUser();
$me = null;
if($this->user_id) {
try{
$me = $this->api('/me');
$this->user = $me;
} catch(FacebookApiException $e) {
error_log($e);
}
}
}
}
$my_profile_info = (new FacebookRequest($session, 'GET', '/me/?fields=id,first_name,last_name,email,picture,gender,location,address,email,hometown'))->execute()->getGraphObject()->asArray();
Hope this help too in answering your question.
Facebook Official Documentation
You could login using the same Facebook ID that you used for APP which will show these data, or you could use Facebook tools such as https://developers.facebook.com/tools/explorer/ to query facebook database.

getLogoutUrl is not working with facebook graphp api using php codeigniter

My facebook php sdk getLogoutUrl is not working when i click on my logout url.
it takes me back to my given redirect url but it does not destroy my facebook session i can still see my var_dump($fb_data) array on my page and logout url.
Here is my code i am using codeigniter
My lib_login library function facebook code
public function facebook()
{
$facebook_default_scope = explode(',', $this->ci->config->item("facebook_default_scope"));
$facebook_app_id = $this->ci->config->item("facebook_app_id");
$facebook_api_secret = $this->ci->config->item("facebook_api_secret");
// init app with app id and secret
FacebookSession::setDefaultApplication($facebook_app_id, $facebook_api_secret);
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper(site_url('login/facebook'));
// see if a existing session exists
if (isset($_SESSION) && isset($_SESSION['fb_token'])) {
// create new session from saved access_token
$session = new FacebookSession($_SESSION['fb_token']);
// validate the access_token to make sure it's still valid
try {
if (!$session->validate()) {
$session = null;
}
} catch (Exception $e) {
// catch any exceptions
$session = null;
}
}
if (!isset($session) || $session === null) {
// no session exists
try {
$session = $helper->getSessionFromRedirect();
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
// handle this better in production code
print_r($ex);
} catch(Exception $ex) {
// When validation fails or other local issues
// handle this better in production code
print_r($ex);
}
}
// see if we have a session
if (isset($session)) {
// save the session
$_SESSION['fb_token'] = $session->getToken();
// create a session using saved token or the new one we generated at login
$session = new FacebookSession($session->getToken());
// graph api request for user data
$request = new FacebookRequest($session, 'GET', '/me?fields=id,name,accounts{access_token,category,name,id,perms},permissions');
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject()->asArray();
$logoutUrl = site_url('login');
$fb_data = array(
'me' => $graphObject,
'loginUrl' => $helper->getLoginUrl($facebook_default_scope),
'logoutUrl' => $helper->getLogoutUrl($session,$logoutUrl),
);
$this->ci->session->set_userdata('fb_data', $fb_data);
} else {
$fb_data = array(
'me' => null,
'loginUrl' => $helper->getLoginUrl($facebook_default_scope),
'logoutUrl' => $helper->getLogoutUrl($session,$logoutUrl),
);
$this->ci->session->set_userdata('fb_data', $fb_data);
}
return $fb_data;
}
Here is my function of my controller
public function facebook()
{
$fb_data = $this->lib_login->facebook();
if (isset($fb_data['me'])) {
echo "<pre>";
var_dump($fb_data);
echo "</pre>";
echo 'logout';
} else {
echo 'Login';
}
}
When ever i login to my account using this code then the logout url and $fb_data array appears on my page but when i logout and refresh my page it is still their.Can some one tell what i am doing wrong here.
Try something like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library(array('session', 'lib_login'));
$this->fb_data = $this->lib_login->facebook();
}
/**
* facebook login
*
* #return void
* #author appleboy
**/
public function facebook()
{
// check login data
if (isset($this->fb_data['me'])) {
var_dump($this->fb_data);
} else {
echo 'Login';
}
}
public function logout()
{
if ( isset($this->fb_data['me']) ) {
$this->session->unset_userdata('fb_data');
}
redirect('login/facebook', 'refresh');
}
}
/* End of file login.php */
/* Location: ./application/controllers/login.php */

I found No way to build facebook integration with my website

I tried in many ways.. i used php-sdk and in many other ways... but i am not able to connect my website with facebook... actually.. i am doing my project in codeigniter. Can anybody plz suggest me to connect to facebook login and share using codeigniter.
<?php
include "libs/facebook.php";
$facebook = new Facebook(array(
'appId' => '376406812408828',
'sec`enter code here`ret' => 'ca1eb65bde82a4009c31b4a5adb047b5',
'cookie' => true
));
print_r($facebook);
$session = $facebook->getUser();
echo $session;
$me=null;
if($session)
{
try
{
$me = $facebook->api('/me');
echo $me;
$facebook->api('/me/feed','post',array('message' => 'Hello World!'));
}
catch(FacebookApiException $e)
{
echo $e->getMessage();
}
}
if($me)
{
$logoutUrl = $facebook ->getLogoutUrl();
echo "Logout";
}
else
{
$loginUrl = $facebook ->getLoginUrl(array(
'req_perms' => 'publish_stream,read_friendlists'
));
echo "Login";
}
?>
Danny Tran has provided A Simple & Easy Facebook Library for CodeIgniter.
CI_Facebook is a Facebook Library for CodeIgniter.
Simply copy/merge all the files into the corresponding locations and
setup config/facebook.php.
There are unit tests written for each function/class. You will need
PHPUnit to execute them.
Accessing the Facebook object is easy since the hook is auto-loading
it.
e.g. $user_data = $this->facebook->fb->api_client->fql_query("select name from user where uid = TARGETUSERID");
Link to library on Github: https://github.com/dannybtran/CI_Facebook
Hope this helps.
A couple of weeks I had to do the same, and after and I came up with this. I needed it for an ajax login, but it mostly suits everyone needs.
This is the first step, it prompts the facebook login (if you are not already logged) and then redirect to your previously set uri.
$this->load->library('facebook_handler');
$this->facebook_handler->loginBegin($this->config->item('endpointfacebook'));
Facebook_handler in libraries folder
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Facebook_handler extends ML_index
{
var $scope = "email, user_about_me, user_birthday, user_hometown, user_website,read_stream, publish_stream, read_friendlists";
function __construct()
{ parent::__construct();
$this->CI =& get_instance();
$this->CI->config->load('mlogin_config'); //Config where I have the keys
if ( ! $this->CI->config->item('facebook_api_key') || ! $this->CI->config->item('facebook_api_key_secret') )
{
throw new Exception( "Your application id and secret are required in order to connect to {$this->providerId}.", 4 );
}
include_once(APPPATH.'libraries/Facebook/base_facebook.php'); //Place where I've situated the facebook libraries
include_once(APPPATH.'libraries/Facebook/facebook.php');
$this->fb = new Facebook( ARRAY( 'appId' => $this->CI->config->item('facebook_api_key'),'cookie'=>true, 'secret' => $this->CI->config->item('facebook_api_key_secret') ) );
$this->user = $this->fb->getUser();
}
/*The login process starts here, endpoint is the redirect_url for facebook*/
function loginBegin($endpoint)
{
$scope=$this->CI->config->item('facebook_scope');
if( isset( $scope ) && ! empty( $scope ) )
{
$this->scope = $scope;
}
$this->logout();
$url = $this->fb->getLoginUrl( array( 'domain'=>base_url(),'scope' => $this->scope, 'redirect_uri' => $endpoint,'display' => 'popup' ) );
redirect($url);
}
/*Function to get user data*/
function getUser(){
if ($this->user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $this->fb->api('/me');
return $user_profile;
} catch (FacebookApiException $e) {
error_log($e);
return false;
}
}else{
$this->output->set_output('no logueado');
}
}
/*Facebook logout, it destroys facebook sessions. I dont really use this*/
function logout(){
$this->fb->destroySession();
}
}
?>
The function to redirect to
function closewindowfacebook(){
$this->load->library('facebook_handler');
$userprofile=$this->facebook_handler->getUser();
if ($userprofile!=false){
$fb_uid = $this->facebook_handler->fb->getUser();
$fb_email=$userprofile['email'];
$fb_name=$userprofile['name'];
/*My function to connect to the website, that you'd do it yourself*/
//$this->auth->try_fb_login($fb_uid,$fb_email,$fb_name);
/*I use this to close the popup window*/
die('<script type="text/javascript">
window.opener.everythingready();
window.close();
</script>');
} else{
echo 'error ';
}
}
Ask if you have any further question

Facebook login script not prompting facebook login window

Im having problems trying to implement a Facebook login script into my Zend website.
What I basically do here is
create My_Action_Helper_FBInitializer (extending Zend_Controller_Action_Helper_Abstract).This initializes facebook connection.
invoke My_Action_Helper_FBInitializer in the bootstrap (so to have it available to all my controllers)
Set my facebook app "Site URL" to : http://localhost/test/public/ ("Site domain" field left blank)
expecting to have a working login/logout button in my layout.phtml
ISSUE: the problem is that i'm never prompted with the facebook authentication window, and whenever I click on the Login button I see loaded the same page (my localhost/test/public//index/index) with 'facebook session parameters' appended to the url:
http://localhost/test/public/index/index/?session=%7B%22session_key ... [..]
here my files:
My action helper FBInitializer
class My_Action_Helper_FBInitializer extends Zend_Controller_Action_Helper_Abstract
{
public function init()
{
$controller=$this->getActionController();
$config=Zend_registry::get('config');
$controller->config=$config;
//initialize facebook
require_once('Fb/facebook.php');
$apiKey=$config->fb->apikey;
$appId=$config->fb->appid;
$secret=$config->fb->appid;
$facebook = new Facebook(array('appId' => $appId,'secret' => $secret,'cookie' => true));
$controller->session = $facebook->getSession();
$controller->fbme = NULL;
$controller->facebook=$facebook;
if (!empty($controller->session))
{
$controller->uid = $facebook->getUser();
$controller->fbme = $facebook->api('/me');
}
//
}
}
My Index controller
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
//login
$this->view->fbme=$this->fbme;
$this->view->fb=$this->facebook;
}
}
My layout extract
[..]
if($this->fbme!==NULL)
{
echo"<img align='middle' src='https://graph.facebook.com/{$this->fbme['id']}/picture'/>";
echo "Welcome ".$this->fbme['name'].'! ';
$logoutUrl = $this->fb->getLogoutUrl(array('next'=>'/index/logout'));
echo"<a href='{$logoutUrl}'>Logout</a>";
}
else
{
echo $this->fbme;
$loginUrl = $this->fb->getLoginUrl(array('req_perms' => 'email,read_stream,user_birthday,user_hometown,user_photos'));
echo "<a href='{$loginUrl}'>Login with Facebook!</a>";
}
[..]
I Dont know if Im wrong with either facebook app or Zend settings but I was testing a similar 100% WORKING script (but No zend!) that is:
$fbconfig['appid'] = "181****";
$fbconfig['api'] = "5c69*****";
$fbconfig['secret'] = "a2fc*****";
include_once "facebook.php";
// Create our Application instance.
$facebook = new Facebook(array('appId' => $fbconfig['appid'],'secret' => $fbconfig['secret'],'cookie' => true));
$session = $facebook->getSession();
$fbme = null;
// Session based graph API call.
if (!empty($session))
{
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
}
// login or logout url will be needed depending on current user state.
if ($fbme)
{
echo"<img src='https://graph.facebook.com/{$fbme['id']}/picture'/>";
echo $fbme['name'].' ';
$logoutUrl = $facebook->getLogoutUrl(array('next'=>'http://localhost/fb/logout.php'));
echo"<a href='{$logoutUrl}'>logout</a>";
}
else
{
$loginUrl = $facebook->getLoginUrl(array('req_perms' => 'email,read_stream,user_birthday,user_hometown,user_photos'));
echo"<a href='{$loginUrl}'>login</a>";
}
Thanks
Luca

Categories