我正在尝试检索用户的脸谱资料。我正在使用Laravel 4框架。 Bur我得到"无效的访问令牌"每次。
我的代码如下。
<?php
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
class FacebookController extends BaseController{
public function __construct(){
session_start();
FacebookSession::setDefaultApplication('xx','yy');
}
//when the user clicks on the login button he comes to this function
public function getLogin(){
$helper = new FacebookRedirectLoginHelper(url('facebook/user'));
return Redirect::to($helper->getLoginUrl());
}
//when the user logs in, he comes to this function
public function getUser(){
try{
$session = new FacebookSession(Session::get('_token'));//I believe here lies the problem
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$graphObject = $response->getGraphObject()->asArray();
dd($graphObject);
} catch(Exception $e){
dd($e);
}
}
}
答案 0 :(得分:2)
您不需要session_start()
,laravel将为您处理所有会话管理。
它似乎不是特定于laravel的问题,而是代码中的一个简单错误:
facebook的文档页面上的示例使用FacebookRedirectLoginHelper::getSessionFromRedirect()
来检索用于处理请求的会话。
$helper = new FacebookRedirectLoginHelper();
try {
$session = $helper->getSessionFromRedirect();
// your old code
}
答案 1 :(得分:1)
请查看我们在http://valoresdovale.com/login/fb测试的工作代码:
<?php
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookAuthorizationException;
use Facebook\FacebookRequestException;
session_start(); //this can be moved to app/public/index.php
Route::get('/', function()
{
return View::make('hello');
});
Route::get('login/fb', function() {
FacebookSession::setDefaultApplication('YOUR_ID', 'YOUR_SECRET');
$helper = new FacebookRedirectLoginHelper('http://yoururl/login/fb/callback');
$loginUrl = $helper->getLoginUrl();
return "<a href='$loginUrl'>facebook</a>";
});
Route::get('login/fb/callback', function() {
// A FacebookResponse is returned from an executed FacebookRequest
$helper = new FacebookRedirectLoginHelper('http://yoururl/login/fb/callback');
$session = $helper->getSessionFromRedirect();
$request = new FacebookRequest($session, 'GET', '/me');
try {
$response = $request->execute();
$me = $response->getGraphObject();
} catch (FacebookRequestException $ex) {
echo $ex->getMessage();
} catch (\Exception $ex) {
echo $ex->getMessage();
}
print_r($me);//->getProperty("id"));
$user = new Giftee;
$user->name = $me->getProperty('first_name') . ' ' . $me->getProperty('last_name');
$user->email = $me->getProperty('email') . "@facebook.com.br";
$user->photo = 'https://graph.facebook.com/' . $me->getProperty('id') . '/picture?type=large';
$user->save();
});
这是基于http://maxoffsky.com/code-blog/integrating-facebook-login-into-laravel-application/并通过Denisson Leal更新到新的Facebook SDK。