【发布时间】:2014-07-01 19:59:48
【问题描述】:
我目前正在尝试将最新的 Facebook php sdk 集成到 Phalcon 项目中,但我运气不佳。
我可以让 SDK 在独立项目中工作,但完全相同的代码在集成到 Phalcon 项目(作为服务或直接在控制器中)时会失败。
问题似乎是 facebook 重定向助手创建了一个“状态”属性,该属性附加到 loginUrl,然后存储在会话中。当用户在登录后被重定向回我的站点时,它会根据查询字符串值检查此属性。只有当您通过 redirectHelpers getLoginUrl() 方法显示登录 url 时,才会生成和存储 state 属性。不知何故,当我将它集成到 Phalcon 中时,会话变量和 $_GET 参数似乎永远不会匹配。有效的简单示例如下
// lots of requires
Facebook\FacebookSession::setDefaultApplication($appId,$secret);
$helper = new Facebook\FacebookRedirectLoginHelper('http://'.$_SERVER['HTTP_HOST'] .'/');
// see if a existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from saved access_token
$session = new FacebookSession( $_SESSION['fb_token'] );
// validate the access_token to make sure it's still valid
try {
if ( !$session->validate() ) {
$session = null;
}
} catch ( Exception $e ) {
// catch any exceptions
$session = null;
}
} // end if isset($_SESSION)
if ( !isset( $session ) || $session === null ) {
// no session exists
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
// handle this better in production code
print_r( $ex );
} catch( Exception $ex ) {
// When validation fails or other local issues
// handle this better in production code
print_r( $ex );
}
}
// see if we have a session
if ( isset( $session ) ) {
// save the session
$_SESSION['fb_token'] = $session->getToken();
// create a session using saved token or the new one we generated at login
$session = new FacebookSession( $session->getToken() );
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject()->asArray();
// print profile data
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
// print logout url using session and redirect_uri (logout.php page should destroy the session)
echo '<a href="' . $helper->getLogoutUrl( $session, 'http://yourwebsite.com/app/logout.php' ) . '">Logout</a>';
} else {
// show login url
echo '<a href="' . $helper->getLoginUrl( array( 'email', 'user_friends' ) ) . '">Login</a>'; // this line would generate a new state
}
当我尝试在 phalcon 项目的控制器中使用完全相同的代码时(或通过在 $di 中设置“$me”),即使我没有生成新的登录 URL,状态检查也总是失败。唯一的另一个区别是,在简单的项目中,我需要使用 require_once 的所有 facebook 文件,但在我使用的 Phalcon 项目中
$loader->registerNamespaces(
array(
"Facebook" => __DIR__ . '/../../vendor/facebook/php-sdk-v4/src/Facebook/'
)
);
但是用 requires 替换它似乎没有效果。
谁有线索?
【问题讨论】:
标签: facebook facebook-php-sdk phalcon