Logging In And Connecting

From Facebook Developer Wiki

Jump to: navigation, search

If a user is not logged-in to Facebook or has not connected with your site, you must have the user login and/or connect in order to make API calls on their behalf.

The preferred way to do this is to use the Facebook Connect login button using the fb:login-button XFBML tag:

<fb:login-button onlogin='window.location="/home.php";'></fb:login-button>

This displays the following login button on your site:

Image:Connect_light_medium_short.gif


When the user clicks the login button, Facebook displays a Connect dialog and allows the user to connect with your website. When the user successfully connects, the onlogin JavaScript argument gets invoked. There are many login buttons available via the fb:login-button tag. See Facebook Connect Login Buttons for a full list.

Contents

Creating Your Own Login Button

If you do not want to use XFBML to render the login button, you can also create a login button manually in one of two ways:

  • By choosing the appropriate image and manually wrapping it in an anchor tag with JavaScript.
  • By using PHP with JavaScript the login code.

Wrapping the Login Button within an Anchor Tag

<!-- You can invoke FB.Connect.requireSession() to require a session. If a session already exists, this call is a no-op. Otherwise, the user is prompted to connect their accounts. --> <a href="#" onclick="FB.Connect.requireSession(); return false;"> <img id="fb_login_image" src="http://static.ak.fbcdn.net/images/fbconnect/login-buttons/connect_light_medium_long.gif" alt="Connect" /> </a>

Because FB.Connect.requireSession takes a callback on state change, you can use it in a similar way to XFBML's onlogin:

FB.Connect.requireSession(function() { window.location='http://example.com'; });


Using PHP and JavaScript

<?php if (!$fb->get_loggedin_user()) { echo '<a href="#" onclick="FB.Connect.requireSession(); return false;"> <img id="fb_login_image" src="http://static.ak.fbcdn.net/images/fbconnect/login-buttons/connect_light_medium_long.gif" alt="Connect" /> </a>'; } else { // display content for logged in user } ?>

Displaying the Login Button

It's ideal if you display the login button only if the user is not connected with your site. If the user is already connected, clicking the login button will not prompt any user interface, although any registered callbacks will be called.

If this is a first-time user (that is, they're connecting with your site for the first time), we will also ping the Post-Authorize URL specified in your application's settings, if such an URL exists.

Caveats

The user's browser must be set to accept 3rd Party Cookies in order for it to stay connected between clicks.

See Also