donglanche9257
donglanche9257
2017-05-01 10:07

如何使用Facebook php-sdk从facebook登录获取用户数据

  • facebook
  • php

I m trying to get User info from facebook login api of php sdk. here is my config script. I tried to used this fb guidelines but still i m not getting it properly.

try {
  // Returns a `Facebook\FacebookResponse` object
  $response = $fb->get('/me?fields=id,name', '{access-token}');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

$user = $response->getGraphUser();

echo 'Name: ' . $user['name'];

I m unable to get the data of user. Please help me where I am making mistake.

<?php
if(!session_id()){
    session_start();
}

// Include the autoloader provided in the SDK
require_once __DIR__ . '/facebook-php-sdk/src/Facebook/autoload.php';

// Include required libraries
use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;

/*
 * Configuration and setup Facebook SDK
 */
$appId         = '1698023223833500'; //Facebook App ID
$appSecret     = 'e4113b39035af477669c40c9c87bc17b'; //Facebook App Secret
$redirectURL   = 'http://localhost/'; //Callback URL
$fbPermissions = array('email');  //Optional permissions

$fb = new Facebook(array(
    'app_id' => $appId,
    'app_secret' => $appSecret,
    'default_graph_version' => 'v2.2',
));

// Get redirect login helper
$helper = $fb->getRedirectLoginHelper();

// Try to get access token
try {
    if(isset($_SESSION['facebook_access_token'])){
        $accessToken = $_SESSION['facebook_access_token'];

    }else{
          $accessToken = $helper->getAccessToken();
          echo $accessToken;
    }
} catch(FacebookResponseException $e) {
     echo 'Graph returned an error: ' . $e->getMessage();
      exit;
} catch(FacebookSDKException $e) {
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
      exit;
}

  ?>
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答

为你推荐

换一换