使用PHP和JS facebook SDK实现Oauth

时间:2015-07-13 09:09:31

标签: codeigniter oauth facebook-javascript-sdk facebook-php-sdk

Hai Fellow Developers,

我正在使用codeigniter(电子商务类平台)实现A facebook登录我的Web应用程序。

所以,基于它我在我的网站上有很多过滤器我正在尝试获取数据并请求服务。所以用户必须登录才能请求服务,所以最后我强迫用户登录继续(比如买东西)。

出现问题,我使用Javascript SDK实现了Facebook登录并尝试获取accessstoken。并在codeigniter中创建了一个FACEBOOK库,它使用FacebookJavaScriptLoginHelper获取用户的数据。现在我应该更新所有会话中的用户详细信息,并将用户名动态地附加到codeigniter中的当前视图。

你可以看看我现在尝试过的东西:

Facebook Libabry:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( session_status() == PHP_SESSION_NONE ) {
  session_start();
}

// Autoload the required files
require_once( APPPATH . 'libraries/facebook/autoload.php' );

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\FacebookJavaScriptLoginHelper;
use Facebook\GraphObject;
use Facebook\GraphUser;

class Facebook {
  var $ci;
  var $helper;
  var $session;
  var $permissions;

  public function __construct() {
    $this->ci =& get_instance();
    $this->permissions = $this->ci->config->item('permissions', 'facebook');

    // Initialize the SDK
    FacebookSession::setDefaultApplication( $this->ci->config->item('api_id', 'facebook'), $this->ci->config->item('app_secret', 'facebook') );

      $this->helper = new FacebookJavaScriptLoginHelper();
            // No session exists
      try {
          $this->session = $this->helper->getSession(); 
      } catch( FacebookRequestException $ex ) {

      } catch( Exception $ex ) {
        // When validation fails or other local issues

      }
  }

  /**
   * Returns the login URL.
   */
  public function login_url() {
    return $this->helper->getLoginUrl( $this->permissions );
  }

  /**
   * Returns the current user's info as an array.
   */
  public function get_user() {

    if ( $this->session) {

      $request = ( new FacebookRequest( $this->session, 'GET', '/me' ) )->execute();

      // Get response as an array
      $user = $request->getGraphObject()->asArray();

      return $user;
    }
    return false;
  }

  public function logout(){
    session_start();
    session_destroy();
  }

}

在我的控制器中,我有像这样的索引函数

public function index(){
    $fb_data = $this->facebook->get_user();
    $profile_data=array(
        'name'=>$fb_data['name'],
        'id' =>$fb_data['id'],
        'image'=>'http://graph.facebook.com/'.$fb_data['id'].'/picture?width=300',
        'email'=>$fb_data['email'],
        'oauthProvider'=>'facebook',
        );
    $this->session->set_userdata('user_name', $fb_data['name']);
    echo json_encode($profile_data);
}

我的标题视图:

<?php if($this->session->userdata('user_name')): ?>

            <li id="userName" class="dropdown">
              <a href="#" id="userNameAnchor" class="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Welcome <span class="user_name"><?php echo $this->session->userdata('user_name')?></span><span class="caret"></span></a>
              <ul class="dropdown-menu">
                <li><a href="#">Account settings</a></li>
                <li><a href="<?php echo base_url('redirectoauth/FbLogout')?>">Logout</a></li>
              </ul>
            </li>
<?php else: ?>
<li id="login"><a href="#socialLogin" data-toggle="modal">Login</a></li>

<?php endif; ?>

Ajax调用

    $.ajax({ 
url:"<?php echo base_url('redirectoauth');?>", 
success:function(data){ 
var data=$.parseJSON(data); 
$('.user_name').html(data.name); 
$('#userName').css('display','block') 
$('#login').css('display','none'); 
$('#socialLogin').modal('hide'); 
} 
});

有关架构的任何参考或评论,建议以克服此问题。

1 个答案:

答案 0 :(得分:0)

这将解决您的问题

ajax call

$.ajax({ 
url:"<?php echo base_url('redirectoauth');?>", 
    success:function(data){ 
    var data=$.parseJSON(data); 
    $('.user_name').html(data.name); 
    $('#logined').css('display','block') 
    $('#sociallogined').css('display','none'); 
    $('#socialLogin').modal('hide'); 
} 
});

查看

<ul id="logined" <?php echo $this->session->userdata('user_name') ? 'style="display:none"' :''; ?>>
    <li id="userName" class="dropdown">
              <a href="#" id="userNameAnchor" class="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Welcome <span class="user_name"><?php echo $this->session->userdata('user_name')?></span><span class="caret"></span></a>
              <ul class="dropdown-menu">
                <li><a href="#">Account settings</a></li>
                <li><a href="<?php echo base_url('redirectoauth/FbLogout')?>">Logout</a></li>
              </ul>
            </li>
</ul>
<ul id="sociallogined">
    <li id="login"><a href="#socialLogin" data-toggle="modal">Login</a></li>
</ul>