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
Related
I am trying the following:
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Welcome extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('facebook', $this->config->item('fb_config'));
}
public function index() {
$user_id = $this->facebook->getUser();
$data['user_id'] = $user_id;
if ($user_id) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$user_profile = $this->facebook->api('/me', 'GET');
echo "Name: " . $user_profile['name'];
} catch (FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $this->facebook->getLoginUrl();
echo 'Please login.';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, print a link for the user to login
$login_url = $this->facebook->getLoginUrl();
echo 'Please login.';
}
die;
}
}
but i am getting this error:
Invalid or no certificate authority found, using bundled information
OAuthException
Error validating access token: The user has not authorized application XXXXXXXXX.
What can i do to solve this? isn't this the correct way to ask the user to access his profile?
and how to add some scope like you do in the javascript
{scope: 'email, user_birthday'}
found the issue was in the $this->config->item('fb_config') array
it should be like this:
$config['fb_config'] = array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
'fileUpload' => false, // optional
'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
);
Im implementing facebook's PHP SDK for authentication here. I've searched over net and found lots of tutorial on that. like Using Facebook PHP SDK 3 with CodeIgniter
i've modified base_facebook.php to return www.skillpaper.com/auth/fb_register in
$this->facebook->getLoginUrl()
when i click "Connect with Facebook" in login modal and facebook auth popup appears its successfully redirect to my given url. i.e www.skillpaper.com/auth/fb_register
and my code is like in auth controller:
public function fb_register(){
$userId = $this->facebook->getUser();
if($userId != 0){
// Get user's data and print it
$user = $this->facebook->api('/me');
var_dump($user);
}else{ echo "No user";}
}
i'm getting "No user" every time!
What am i missing? I don't want to use any JS API for this. any suggestion?
Thanks in advance.
Please Download the Facebook PHP SDK From https://developers.facebook.com/docs/reference/php/
Now Put src folder into application/controller folder.
Call into controller any function like this :-
require 'src/facebook.php';
$appId = FBAPPID;
$secretkey = FBSECRETKEY;
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $secretkey,
));
$fb['facebook']=$facebook;
$facebook_user = $facebook->getUser();
$fb['facebook_user']=$facebook_user;
if ($facebook_user) {
try {
$user_profile = $facebook->api('/me');
//$fb['logoutUrl'] = $facebook->getLogoutUrl();
} catch (FacebookApiException $e) {
error_log($e);
$facebook_user = null;
$this->load->view('Your Page');
}
}else {
$data['loginUrl'] = $facebook->getLoginUrl(array(
'scope' => 'user_about_me,email,user_birthday,friends_birthday,publish_stream,manage_pages,offline_access'
));
$this->load->view('Your Page');
}
i tried to use the facebook login in my project. For this i use the PHP SDK in codeigniter..
all works and i can do the login and retrieve data to my page.
But i can´t understand why the logout doesn´t work, because when i click on the logout link nothing happend.
i have search a lot of things in the internet and tried too.
I don´t know what do now .. hope someone can help me with this.
here is my code:
model/Facebook_model
<?php
class Facebook_model extends CI_Model {
public function __construct()
{
parent::__construct();
$config = array(
'appId' => 'xxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxx',
'fileUpload' => true, // Indicates if the CURL based # syntax for file uploads is enabled.
);
$this->load->library('Facebook', $config);
$user = $this->facebook->getUser();
// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
$profile = null;
if($user)
{
try {
// Proceed knowing you have a logged in user who's authenticated.
$profile = $this->facebook->api('/me?fields=id,name,link,email');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
$fb_data = array(
'me' => $profile,
'uid' => $user,
'loginUrl' => $this->facebook->getLoginUrl(
array(
'scope' => 'email,user_birthday,publish_stream', // app permissions
//'redirect_uri' => site_url('home') // URL where you want to redirect your users after a successful login
'redirect_uri' => base_url()
)
),
'logoutUrl' => $this->facebook->getLogoutUrl(),
);
}
}
controller/mycontroller.php (i have a search function for other functionality)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Concertos extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('Facebook_model');
}
function topsecret()
{
$fb_data = $this->session->userdata('fb_data');
if((!$fb_data['uid']) or (!$fb_data['me']))
{
redirect('home');
}
else
{
$data = array(
'fb_data' => $fb_data,
);
$this->load->view('home', $data);
}
}
public function search($location)
{
$fb_data = $this->session->userdata('fb_data');
$data ['fb_data'] = $fb_data;
$this->load->view('home',$data);
}
view/home.php
<?php
if(!$fb_data['me']): ?>
Please login with your FB account: login
<!-- Or you can use XFBML -->
<div class="fb-login-button" data-show-faces="false" data-width="100" data-max-rows="1" data-scope="email,user_birthday,publish_stream"></div>
<?php else: ?>
<img src="https://graph.facebook.com/<?php echo $fb_data['uid']; ?>/picture" alt="" class="pic" />
<p>Hi <?php echo $fb_data['me']['name']; ?>,<br />
logout</p>
<?php endif;
?>
Since you are creating session, when you logout you need to destroy it in you logout function. Then you need to link to this function.
function logout()
{
$this->CI->session->sess_destroy();
// do more thing you want to do such as redirect
}
I don't think anything is wrong. Do you know that getLogoutUrl will logout the user from facebook.com. So if want to logout user from only app, I think it need some other native code.
I am trying to login with FB using codeigniter & the FB PHP SDK.
but it keeps giving me the same login with facebook link, it's not catching if the user is logged in, Am I missing anything like sessions or something?
And since we are at it how can I get the extended session & what data should I save to publish to pages while user is offline?
here is my controller:
function __construct () {
parent::__construct();
$this->load->helper('url_helper');
$this->load->add_package_path(APPPATH.'third_party/facebook/');
$this->config->load('facebook', TRUE);
$this->load->library('facebook', array( 'appId' => $this->config->item('appId', 'facebook'), 'secret' => $this->config->item('secret', 'facebook') ) );
}
public function index() {
$data['LoginURL'] = $this->facebook->getLoginUrl( array('scope' => 'manage_pages') );
$data['user'] = $this->facebook->getUser();
if ($data['user']) {
try {
$data['user_profile'] = $this->facebook->api('/me');
$data['AccessToken'] = $this->facebook->getAccessToken();
} catch (FacebookApiException $e) {
// The access token we have is not valid
$data['user'] = null;
}
}
$this->load->view('fb_welcome', $data);
}
And here is the view:
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<?php if ( $user ): ?>
User <em><?php echo $user ?></em> is Logged in, AccessToken is <?php echo $AccessToken; ?>
<?php print_r($user_profile); ?>
<?php else: ?>
<?php echo anchor($LoginURL, "Login with facebook"); ?>
<?php endif; ?>
</body>
</html>
I dont know code igniter, but hopefully this should prove a good starting point, just link to your fb sdk in the include, replace the vars with your own and it should give the user a popup when they are not logged in:
// include the FB SDK
require_once(APPLICATION_PATH . '/../library/facebook/facebook.php');
// create the application instance
$facebook = new Facebook(array(
'appId' => $this->facebookConfig->appid,
'secret' => $this->facebookConfig->appsecret
));
// get the user id
$user = $facebook->getUser();
if(!empty($user)) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
// do something
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$params = array(
'scope' => $this->permissions,
'redirect_uri' => $this->facebookConfig->applink
);
$loginUrl = $facebook->getLoginUrl($params);
// log errors
error_log($e->getType());
error_log($e->getMessage());
// redirect if not logged in or not enough permissions
//echo "<script>top.location=\"".$loginUrl."\";</script>";die;
}
// Give the user a logout link
//echo '<br />logout';
} else {
$params = array(
'scope' => $this->permissions,
'redirect_uri' => $this->facebookConfig->applink
);
$loginUrl = $facebook->getLoginUrl($params);
// log errors
error_log($e->getType());
error_log($e->getMessage());
// redirect if not logged in or not enough permissions
echo "<script>top.location=\"".$loginUrl."\";</script>";die;
}
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