如何让用户使用他们的Facebook帐户登录我的网站?

时间:2013-03-05 13:57:40

标签: php facebook login

我使用SDK php让用户使用他们的Facebook帐户登录我的网站。我正在关注SDK示例。当我尝试获取登录用户ID时,它返回0:

$id = $facebook->getUser();

你能告诉我是什么问题,以及如何使用php SDK工作

这是示例的代码:

<?php
$config = FacebookConfig::getConfig();
$facebook = new Facebook( $config );
$user = $facebook->getUser();
Facebook::$CURL_OPTS[ CURLOPT_SSL_VERIFYPEER ] = false;

if ( $user ) {
    try {
        $user_profile = $facebook->api( '/me' );
        $logoutUrl = $facebook->getLogoutUrl();
    }
    catch ( FacebookApiException $e ) {
        error_log( $e );
        $user = null;
    }
} else {
    try {

        $loginUrl = $facebook->getLoginUrl( array(
             "scope" => "email,user_education_history,user_work_history",
            "redirect_uri" => "http://localhost:8888/www/index.php" 
        ) );
        $user = $facebook->getUser();
        $user_profile = $facebook->api( '/me' );
        $userProf = $facebook->api( "/$user" );
        echo $user;
        echo $user_profile;
    }
    catch ( FacebookApiException $e ) {
        $user = null;
        echo "expetion in login";

    }
}
?>

1 个答案:

答案 0 :(得分:0)

您必须将用户重定向到$loginUrl!试试这个:

<?php
$config = FacebookConfig::getConfig();
$facebook = new Facebook( $config );
$user = $facebook->getUser();
Facebook::$CURL_OPTS[ CURLOPT_SSL_VERIFYPEER ] = false;

if ( $user ) {
    try {
        $user_profile = $facebook->api( '/me' );
        var_dump($user_profile);
        $logoutUrl = $facebook->getLogoutUrl();
    }
    catch ( FacebookApiException $e ) {
        error_log( $e );
        $user = null;
    }
} else {
    try {
        $loginUrl = $facebook->getLoginUrl( array(
             "scope" => "email,user_education_history,user_work_history",
            "redirect_uri" => "http://localhost/facebook/index.php" 
        ) );
        header('Location: '.$loginUrl);
    }
    catch ( FacebookApiException $e ) {
        $user = null;
        echo "exception in login";
    }
}