【问题标题】:Facebook PHP + JavaScript - exception when navigating before page has loadedFacebook PHP + JavaScript - 在页面加载之前导航时出现异常
【发布时间】:2015-03-04 12:18:58
【问题描述】:

我已经使用 Facebook PHP 和 JS API 创建了一个页面。

首先,用户必须进行身份验证(login.php)。然后将用户重定向到 index.php。这很好用,但是如果用户导航到另一个页面或在页面加载之前重新加载页面,它将再次将用户返回到 login.php 进行身份验证。 (这是因为 $session 中的 if/else)。如果没有 $session 并记录异常,我关闭重定向以登录时,我收到此错误:

exception 'Facebook\FacebookAuthorizationException' with message 'This authorization code has been used.' in /Applications/XAMPP/xamppfiles/htdocs/ntsosial/fb/src/Facebook/FacebookRequestException.php:104 Stack trace: #0 /Applications/XAMPP/xamppfiles/htdocs/ntsosial/fb/src/Facebook/FacebookRequest.php(280): Facebook\FacebookRequestException::create('{"error":{"mess...', Object(stdClass), 400) #1 /Applications/XAMPP/xamppfiles/htdocs/ntsosial/fb/src/Facebook/Entities/AccessToken.php(328): Facebook\FacebookRequest->execute() #2 /Applications/XAMPP/xamppfiles/htdocs/ntsosial/fb/src/Facebook/Entities/AccessToken.php(242): Facebook\Entities\AccessToken::request('/oauth/access_t...', Array, NULL, NULL) #3 /Applications/XAMPP/xamppfiles/htdocs/ntsosial/fb/src/Facebook/Entities/AccessToken.php(187): Facebook\Entities\AccessToken::requestAccessToken(Array, NULL, NULL) #4 /Applications/XAMPP/xamppfiles/htdocs/ntsosial/fb/src/Facebook/FacebookSession.php(271): Facebook\Entities\AccessToken::getAccessTokenFromCode('AQCcnkOOMQ9l2Qk...') #5 /Applications/XAMPP/xamppfiles/htdocs/ntsosial/fb/src/Facebook/FacebookSession.php(252): Facebook\FacebookSession::newSessionAfterValidation(Object(Facebook\Entities\SignedRequest)) #6 /Applications/XAMPP/xamppfiles/htdocs/ntsosial/fb/src/Facebook/FacebookSignedRequestFromInputHelper.php(93): Facebook\FacebookSession::newSessionFromSignedRequest(Object(Facebook\Entities\SignedRequest)) #7 /Applications/XAMPP/xamppfiles/htdocs/ntsosial/db/FbAuth.php(19): Facebook\FacebookSignedRequestFromInputHelper->getSession() #8 /Applications/XAMPP/xamppfiles/htdocs/ntsosial/pages/index.php(3): require('/Applications/X...') #9 {main}
Notice: Undefined variable: session in /Applications/XAMPP/xamppfiles/htdocs/ntsosial/db/FbAuth.php on line 28

我的文件(已删除的 CSS 和内容):

index.php:

<?php
require '../db/FbAuth.php';
?>

<!DOCTYPE html>
<html lang="en">

<head>

    <script>
        // This is called with the results from from FB.getLoginStatus().
        function statusChangeCallback(response) {
        console.log('statusChangeCallback');
        console.log(response);
        // The response object is returned with a status field that lets the
        // app know the current login status of the person.
        // Full docs on the response object can be found in the documentation
        // for FB.getLoginStatus().
        if (response.status === 'connected') {
          // Logged into your app and Facebook.
        } else if (response.status === 'not_authorized') {
          // The person is logged into Facebook, but not your app.
          console.log("Not authorized. Redirecting ..");
            window.location = "login.php";
        } else {
          // The person is not logged into Facebook, so we're not sure if
          // they are logged into this app or not.
          console.log("Not logged in to FB. Redirecting..");
            window.location = "login.php";
        }
        }

        // This function is called when someone finishes with the Login
        // Button.  See the onlogin handler attached to it in the sample
        // code below.
        function checkLoginState() {
        FB.getLoginStatus(function(response) {
          statusChangeCallback(response);
        });
        }

        window.fbAsyncInit = function() {
        FB.init({
        appId      : 'removed',
        cookie     : true,  // enable cookies to allow the server to access 
                            // the session
        xfbml      : true,  // parse social plugins on this page
        version    : 'v2.1' // use version 2.1
        });

        // Now that we've initialized the JavaScript SDK, we call 
        // FB.getLoginStatus().  This function gets the state of the
        // person visiting this page and can return one of three states to
        // the callback you provide.  They can be:
        //
        // 1. Logged into your app ('connected')
        // 2. Logged into Facebook, but not your app ('not_authorized')
        // 3. Not logged into Facebook and can't tell if they are logged into
        //    your app or not.
        //
        // These three cases are handled in the callback function.

        FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
        });

        FB.Event.subscribe('auth.authResponseChange', function(response) {
            if (response.status !== 'connected') {
                window.top.location = 'login.php';
            }
        });

        };

        // Load the SDK asynchronously
        (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/nb_NO/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'));


        // Logging user out
        function logout() {
            console.log("Signing out");

            FB.logout(function(response) {
              // user is now logged out
                console.log("Signed out");
            });
        }
        </script>


</head>
<body>
</body>
</html>

db/FbAuth.php

<?php
require '../fb/autoload.php';

use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookJavaScriptLoginHelper;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;


// Initialize the Facebook SDK.
FacebookSession::setDefaultApplication('removed','removed');


$helper = new FacebookJavaScriptLoginHelper();
try {
    $session = $helper->getSession();
} catch(FacebookRequestException $ex) {
    // When Facebook returns an error
} catch(\Exception $ex) {
    // When validation fails or other local issues
}
if ($session) {
  try {
    $me = (new FacebookRequest(
    $session, 'GET', '/me'
    ))->execute()->getGraphObject(GraphUser::className());
    $userID = $me->getId();
  } catch (FacebookRequestException $e) {
    // The Graph API returned an error
  } catch (\Exception $e) {
    // Some other error occurred
}

}
else {                                
    header("Location: ../pages/login.php");
    die();
}

?>

我正在使用 FB PHP SDK v4 和 JS SDK v2.1。

这是因为 JavaScript 没有完成吗?我怎样才能避免这种情况?

【问题讨论】:

    标签: javascript php facebook facebook-graph-api


    【解决方案1】:

    有一些问题:

    1 - session_start() 丢失。

    2 - FacebookSession::setDefaultApplication(string $appId, string $appSecret),你输入了错误的参数

    3 - 在尝试/捕获之前启动 $session = null;

    示例:http://www.inmotionhosting.com/support/website/api/connecting-to-the-facebook-api-using-the-facebook-php-sdk

    【讨论】:

    • 感谢您的回答,但它对我不起作用。 1.增加了session_start(); FacebookSession::setDefaultApplication 之前 2. 我正在使用我的 appId 和 appSecret,但我在发布之前删除了它们 :) 3. 在 try/catch 之前添加。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多