获取网址的Facebook访问令牌或在Facebook应用程序中打印出来

时间:2015-02-21 14:57:36

标签: php facebook facebook-graph-api facebook-access-token

我正在尝试创建一个Facebook应用程序,其中用户登录Facebook后,我的应用程序将打印出他的用户名和应用程序的访问令牌....就像thiis:

Hello Facebook用户,

访问令牌:CAAAAAIZAgwGsBAARk1sPr3PGY196qsdFc518GrC3ADMkilY4oFgAoTLTuPO8YkXaHqMOiKZAXoubyOLmABwa6ZA386iNZCqUP569ABJ5UMlO65rhIRnIu912lSdSTaxgzdUH2PvJM18ANZBEOqEIQ00C3ju0UcaW3TKIyhNGIJb0CXbZkdC6WYL1aD46wrc6KDuSB62g4SYmveFDjNvClhgZB6fV0PCaWHYg4e1csxMfIgZDZD

我对PHP有一点了解。请帮助我如何获取访问令牌并在我的应用程序中打印出来,以便用户可以在我的应用程序中看到他的访问令牌。请告诉我整个示例代码我该怎么做。

这是我的代码,但错了:

<?php
session_start();

require_once 'facebook-php-sdk/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;

$api_key = 'id';
$api_secret = 'secret';
$redirect_login_url = 'url';


// initialize your app using your key and secret
FacebookSession::setDefaultApplication($api_key, $api_secret);

// create a helper opject which is needed to create a login URL
// the $redirect_login_url is the page a visitor will come to after login
$helper = new FacebookRedirectLoginHelper( $redirect_login_url);


try {
  $session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
  // When Facebook returns an error
} catch( Exception $ex ) {
  // When validation fails or other local issues
}

// see if we have a session
if ( isset( $session ) ) {
    $code = $_GET['code'];
  function getaAccessToken($api_key, $api_secret, $redirect_login_url, $code) {
    $ch = curl_init();
          curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/v2.0/oauth/access_token?'. 'client_id=' . $api_key . '&redirect_uri=' . urlencode($redirect_login_url) . '&client_secret=' . $api_secret . '&code=' . $code);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $r  = curl_exec($ch);
    $r = strstr(str_replace('access_token=', '', $r), '&expires=', true);
    return $r;
}

 $access_token = getaAccessToken();

 echo $access_token;  
} else {
  // show login url
  echo '<a href="' . $helper->getLoginUrl() . '">Login</a>';
}

?>

0 个答案:

没有答案