简体   繁体   中英

Logging into Facebook App redirects to canvas URL

So I've started learning facebook application and got my first obstacle. Whenever i log into my simple hello user application, i'm redirected into canvas URL (App content opens on server directly, instead inside facebook iFrame).

Here's the code

<?php
require_once("php-sdk/facebook.php");

$config = array(
    'appId' => '',
    'secret' => ''
);

$facebook = new Facebook($config);

$user_id = $facebook->getUser();
$params = array(
    'scope' => 'read_stream, friends_likes',
    'redirect_uri' => 'https://apps.facebook.com/401822713222945/'
);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    </head>

    <body>
<?php
if ($user_id){
    try {
        $user_profile = $facebook->api('/me','GET');
        echo 'Welcome ' . $user_profile['name'] . '!';
    } catch(FacebookApiException $e) {
        $login_url = $facebook->getLoginUrl();
        echo 'Please <a href="' . $login_url . '" onclick="top.location.href = \'' . $login_url . '\'">log in.</a>';
        error_log($e->getType());
        error_log($e->getMessage());
    }
} else {
    $login_url = $facebook->getLoginUrl();
    echo 'Please <a href="' . $login_url . '" onclick="top.location.href = \'' . $login_url . '\'">log in.</a>';
}
?>
    </body>
</html>

Try the following right after the <body> tag.

<script type="text/javascript">
if(top === self){
    document.location = "<?php echo $params['redirect_uri'];?>";
}
</script>

It will check if the current window is the most top window, if you're accessing the page directly it will then redirect you to the iframed page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM