开发者

authenticating facebook canvas application returns ?code=

i have a problem with my facebook canvas app that is currently on development i'm working on http://localhost:8080

my canvas url is http://localhost:8080/fbcanvas/

on facebook the url is set to http://apps.facebook.com/app_name/

the problem is i'm getting a code as an $_GET['code'] variable after a user approves my app. in facebook documentation it doesnt say anything about getting a $_GET['code'] it just says getting signed_request

this is the code i'm using from facebook examples.

    require_once($_SERVER['DOCUMENT_ROOT'] . '/classes/Page.php');
require($_SERVER['DOCUMENT_ROOT'] . '/core/config.fb.php');

$canvas_page = 'http://apps.facebook.com/khawamusic/';
$auth_url = 'https://www.facebook.com/dialog/oauth?client_id=' . $app_id . '&redirect_uri=' . urlencode($canvas_page);
$signed_request = $_REQUEST['signed_request'];

list($encoded_sig, $payload) = explode('.', $signed_request, 2);

$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);

if(empty($data['user_id'])) {
    echo('<script> top.location.href="' . $auth_url .'";</script>');
} else {

    $page = new Page;

    $styles = array('reset.css', 'fbcanvas.css');
    $scripts = array(
        'https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js', 
        'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js',
        'http://connect.facebook.net/en_US/all.js#xfbml=1',
        '/sources/js/fbcanvas.js'
    );


    $page->set_title('Khawa');
    $page->set_styles($styles);
    $page->set_scripts($scripts);
    $page->start_page();
    require($_开发者_运维技巧SERVER['DOCUMENT_ROOT'] . '/fbcanvas/fb.tpl');
    $page->end_page();

}

so what happens is a user approves my app then he gets redirected to http://apps.facebook.com/khawamusic/?code=blabla

i'm cnfused because in the documentation it doesn't say i'm suppose to get a $_GET['code']


If the user presses Allow, your app is authorized. The OAuth Dialog will redirect (via HTTP 302) the user's browser to the URL you passed in the redirect_uri parameter with an authorization code:

http://YOUR_URL?code=A_CODE_GENERATED_BY_SERVER

With this code in hand, you can proceed to the next step, app authentication, to gain the access token you need to make API calls.

Refer: https://developers.facebook.com/docs/authentication/

EDIT: Here's a sample of the authentication, this won't show ?code=Blabla.. First download the latest Facebook PHP SDK from here: https://github.com/facebook/php-sdk/tree/master/src

Make sure you save all 3 files, facebook.php, base_facebook.php and fb_ca_chain_bundle.crt Now replace the text "YOUR_APP_ID" and ""YOUR_APP_API_SECRET" with your Application ID and App Secret from facebook, I've added sample wall posting using graph api, if you don't want, you can remove it, if you go through my codes and comments, you'll understand what it does and you don't want to do anything to get access token, just use $access_token variable and it'll give you the access_token of the current user and if you want the user's ID then use $user variable, if you want user's basic information, use $userInfo variable and it'll fetch user's data using graph api and returns all information in an array, you'll get the current user's info like id,name,first_name,last_name,link,hometown,location,bio,work,education,gender,timezone.etc.

Change $RedirectUrl with your landing page URL or your canvas page url

 <?php
        require 'facebook.php';

        define('FACEBOOK_APP_ID', "YOUR_APP_ID"); // Your App ID
        define('FACEBOOK_SECRET', "YOUR_APP_API_SECRET"); // Your App API Secret

        $RedirectUrl = "http://apps.facebook.com/myapp/"; // Your Landing Page URL, User's will be redirect to this URL after they allow your app.

        function d($d){
                echo "<pre>";
                print_r($d);
                echo "</pre>";
        }

        $user  = null;

        $facebook = new Facebook(array(
                'appId'  => FACEBOOK_APP_ID,
                'secret' => FACEBOOK_SECRET,
                'cookie' => true,
        ));

        $user = $facebook->getUser(); // Get the UID of the connected user, or 0 if the Facebook user is not connected.  

        if(isset($_GET['code'])){
            header("Location: $RedirectUrl");
        }

        if($user == 0) {
            // If User is not connected to your app, then redirect User to Authentication Page.
         /**
          * Get a Login URL for use with redirects. By default, full page redirect is
          * assumed. If you are using the generated URL with a window.open() call in
          * JavaScript, you can pass in display=popup as part of the $params.
          * 
          * The parameters:
          * - redirect_uri: the url to go to after a successful login
          * - scope: comma separated list of requested extended perms
          */
          $login_url = $facebook->getLoginUrl($params = array('scope' => "publish_stream", 'redirect_uri' => $RedirectUrl));
          echo("<script> top.location.href='" . $login_url . "'</script>");
        } else {
            // If User is connected to your app, then do something.
            $signed_request = $facebook->getSignedRequest(); // Get the data from a signed_request token.

            $access_token = $facebook->getAccessToken(); // Determines the access token that should be used for API calls.

            $userInfo = $facebook->api("/me"); // Get's User Info

            try {
                // Posts to user's wall after the user allows your app.
                $wallpost = array(
                            'message' => "I like this",
                            'link'    => 'http://google.com',
                            'picture' => 'http://i.imgur.com/8iz6L.png',
                            'name'    => 'This is cool',
                            'description'=> 'Checkout this cool app'
                );
                $publishStream = $facebook->api("/$user/feed", "post", $wallpost); // WallPost to User's Wall using Graph API
echo "Your post was successfully posted to UID: $user";
            }
            catch (FacebookApiException $e) {
                d($e);
            } 

        }
        ?>


i'm not yet sure but i think i have the answer to the process of authorizing / authenticating a facebook app...

step 1 : the first time a user access your app facebook sends you a signed request and you need to parse it validate it and check if the $data['user_id'] is set.

the code:

    $data = $canvas->parse_signed_request($signed_request);

$auth_url = 'http://www.facebook.com/dialog/oauth?client_id=' . $app_id . '&redirect_uri=' . urlencode($canvas_page);

        if(empty($data['user_id'])) {
           echo '<script>top.location.href="' . $auth_url . '"</script>';
        }

so if the $data['user_id'] is empty go authenticate.

step 2: the user authorizes your app facebook sends you a signed request and a code

        if(isset($_REQUEST['code'])) {
        $access_token = $canvas->get_access_token($_REQUEST['code']);
        $user = $canvas->getUser($access_token);

        $user_info = array(
            'user_id' => $user->id,
            'user_username' => $user->username,
            'user_name' => $user->name
        );

        // install the application for the new user.

        $user_obj = new User($user_info);

            // registered or allready exists.
            if($user_obj) {
                echo '<script>top.location.href="' . $canvas->canvas_page . '";</script>';
            }

        exit();
    }

so from what i understood facebook sends you $_REQUEST['code'] just one time: when the user approves your canvas application.

that's it the user is installed so now every time a user re enters your application you will get a signed_request but this time because the user already approves the application the signed request will include an user_id and oauth_token with it u can get stuff from the graph api.

IF THE SIGNED_REQUEST HAVE A USER_ID THIS IS WHAT U DO.

        if(isset($data['user_id'])) {
        $user = false;
        if(!$user) {
            $user = $canvas->getUser($data['oauth_token']);
        }

        if(!ob_start('ob_gzhandler')) ob_start();

        $styles = array(
            'reset.css', 'jplayer.fbcanvas.css', 'fbcanvas.css'
        );

        $scripts = array(
            'http://connect.facebook.net/en_US/all.js#xfbml=1',
            'http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js',
            '/sources/js/jplayer/jquery.transform.js',
            '/sources/js/jplayer/jquery.grab.js',
            '/sources/js/jplayer/jquery.jplayer.js',
            '/sources/js/jplayer/mod.csstransforms.min.js',
            '/sources/js/jplayer/circle.player.js',
            '/sources/js/fbcanvas.js'
        );

        $results = $canvas->getLatestSongs();

        // the canvas.
        $page->set_title('Khawa');
        $page->set_styles($styles);
        $page->set_scripts($scripts);
        $page->start_page();
        require($_SERVER['DOCUMENT_ROOT'] . '/fbcanvas/fb.tpl');
        $page->end_page();

        ob_end_flush();     


    }

again i'm not sure but i think this is the process of authentication for FACEBOOK CANVAS APPS.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜