Master Facebook's OAuth process in PHP


Here we'll show you how to go through the Facebook OAuth process, which lets any Facebook user log in to Facebook and grant your app access to their account. Our simple app simply logs users in and displays some info about their Facebook profile.

In order to follow this example, you'll need a web host running PHP 5 (or later). Unlike our other examples, this one cannot be run from inside your IDE or from the command line, as the OAuth process depends on your script having a valid URL.

Run our Facebook OAuth Example

1 Log in to Temboo. If you don't already have an account, you can register for free.

2 Make sure you've downloaded the Temboo PHP SDK and that you've added it to your development environment as described in our getting started tutorial.

3 Create a new Facebook app via the Facebook developer console using the Apps menu at the top of the page. Once you've created a new App, click the Settings tab on the left, select + Add Platform, and choose the Website option. Set up your Temboo callback URL by specifying the following URL as your Site URL:

https://{ACCOUNT_NAME}.temboolive.com/callback/

4 Create a new PHP script and copy in the code below, making sure to substitute in your Temboo account details, as well as your new Facebook app's App ID and App Secret. You may also want to set TEMBOO_EXAMPLE_URI to the location where you'll upload this script to your web host.

<?php

require 'php-sdk/src/temboo.php';

// Replace with your own Temboo Account Name, Application Name, and Application Key.
define('ACCOUNT_NAME', "ACCOUNT_NAME");
define('APP_NAME', "APP_NAME"); 
define('APP_KEY', "APP_KEY");

// Provide your Facebook App ID and App Secret.
define('APP_ID', "YOUR_FACEBOOK_APP_ID");
define('APP_SECRET', "YOUR_FACEBOOK_APP_SECRET");

// The URL where you've installed this example. Defaults to best guess based on server environment.
define('TEMBOO_EXAMPLE_URI', (isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF']);

// Temboo session to execute choreos.
$session = new Temboo_Session(ACCOUNT_NAME, APP_NAME, APP_KEY);

// PHP session to store oauth access token and callback ID from Facebook.
session_start();

// Route requests based on "action" parameter in query string.
try {
    $action = isset($_GET['action']) ? (string) $_GET['action'] : false;
    switch($action) {
        case "oauth_init":
            oauthInit($session);
            break;
        case "oauth_final":
            oauthFinal($session);
            break;
        case "oauth_reset":
            oauthReset();
            break;
        default:
            getProfile($session);
    }
} catch(Temboo_Exception $e) {
    header('Content-type: text/plain');
    echo get_class($e) . ': ' . $e->getMessage() . "\n";
    echo "Debug info:\n\n";
    print_r($e->getDetails());
    exit;
} catch(Exception $e) {
    header('Content-type: text/plain');
    echo "Something else went wrong! " . $e->getMessage();
    exit;
}


// Generate an authorization URL and callback ID with Facebook, and forward the user to Facebook's sign in page.
function oauthInit(Temboo_Session $session) {
    // Instantiate choreo with previously instantiated temboo session
    $initializeOAuth = new Facebook_OAuth_InitializeOAuth($session);

    // Get an input object for the Choreo
    $initializeOAuthInputs = $initializeOAuth->newInputs();

    // Set inputs
    $initializeOAuthInputs->setAppId(APP_ID);
    $initializeOAuthInputs->setForwardingURL(TEMBOO_EXAMPLE_URI . '?action=oauth_final');

    // Execute Choreo and get results
    $initializeOAuthResults = $initializeOAuth->execute($initializeOAuthInputs)->getResults();

    // Store callback id for second part of authorization
    $_SESSION['facebook_callback_id'] = $initializeOAuthResults->getCallbackID();

    // Redirect to sign in URL supplied by Facebook
    header("Location: " . $initializeOAuthResults->getAuthorizationUrl());
    exit;
}


// Finalize authorization and retrieve access token after user is redirected back by Facebook.
function oauthFinal(Temboo_Session $session) {
    // Instantiate choreo with previously instantiated temboo session
    $finalizeOAuth = new Facebook_OAuth_FinalizeOAuth($session);

    // Get an input object for the Choreo
    $finalizeOAuthInputs = $finalizeOAuth->newInputs();

    // Set inputs
    $finalizeOAuthInputs->setAppId(APP_ID)->setAppSecret(APP_SECRET);
    $finalizeOAuthInputs->setCallbackID($_SESSION['facebook_callback_id']);
    $finalizeOAuthInputs->setLongLivedToken(1)->setTimeout(60);

    // Execute Choreo and get results
    $finalizeOAuthResults = $finalizeOAuth->execute($finalizeOAuthInputs)->getResults();

    $error = $finalizeOAuthResults->getErrorMessage();

    if($error) {
        throw new Exception('Facebook authorization failed: ' . $error);
    }

    // Store access token in PHP session
    $_SESSION['facebook_access_token'] = $finalizeOAuthResults->getAccessToken();

    // Callback ID no longer needed
    unset($_SESSION['facebook_callback_id']);

    // Redirect to base URL to fetch and display users's Likes.
    header("Location: " . TEMBOO_EXAMPLE_URI);
    exit;
}


// Fetch the Facebook user's profile.
function getProfile(Temboo_Session $session) {
    if(!isset($_SESSION['facebook_access_token'])) {
        return false; // OAuth not initiated yet, so nothing to be done.
    }

    // Instantiate choreo with previously instantiated temboo session
    $user = new Facebook_Reading_User($session);

    // Get an input object for the Choreo
    $userInputs = $user->newInputs();

    // Set inputs
    $userInputs->setAccessToken($_SESSION['facebook_access_token']);

    // Execute Choreo and get results
    $userResults = $user->execute($userInputs)->getResults();

    $_SESSION['facebook_profile'] = $userResults->getResponse();
}


// Erase PHP session variables, resetting example.
function oauthReset() {
    unset($_SESSION['facebook_access_token']);
    unset($_SESSION['facebook_profile']);
    header("Location: " . TEMBOO_EXAMPLE_URI);
    exit;
}

?>
<!DOCTYPE html>
<html lang="en-us">
<head>
    <meta charset="utf-8">
    <title>Temboo Facebook OAuth Example</title>
</head>
<body>
    <?php if(isset($_SESSION['facebook_profile'])): ?>

        <p class="example-facebook-success">Success! Here is your Facebook profile:</p>

        <pre style="white-space: pre-wrap">
            <?php echo htmlentities($_SESSION['facebook_profile'], ENT_NOQUOTES, 'UTF-8'); ?>
        </pre>

        <p><a href="<?php echo TEMBOO_EXAMPLE_URI ?>?action=oauth_reset">Reset</a></p>

    <?php else: ?>

        <p><a href="<?php echo TEMBOO_EXAMPLE_URI ?>?action=oauth_init">Log in with Facebook</a></p>

    <?php endif; ?>
</body>
</html>

5 Upload the entire project, including your newly created script and the php-sdk folder, to your web host.

6 Visit your script in a web browser. Click the Facebook Login link and go through the OAuth process.

7 Once you've been redirected to Facebook, you can log in and grant the application access. At this point in the example, you should be redirected back to your application where you'll see the user profile information in JSON format. That's it!

Taking a closer look at the code

This example includes a pair of OAuth helper functions for Facebook and a simple page template for initializing the OAuth flow and displaying user information.

First, we execute the InitializeOAuth Choreo. This is the point in the code where the user is redirected to Facebook in order to log in and grant the application access:

// Generate an authorization URL and callback ID with Facebook, and forward the user to Facebook's sign in page.
function oauthInit(Temboo_Session $session) {
    // Instantiate choreo with previously instantiated temboo session
    $initializeOAuth = new Facebook_OAuth_InitializeOAuth($session);

    // Get an input object for the Choreo
    $initializeOAuthInputs = $initializeOAuth->newInputs();

    // Set inputs
    $initializeOAuthInputs->setAppId(APP_ID);
    $initializeOAuthInputs->setForwardingURL(TEMBOO_EXAMPLE_URI . '?action=oauth_final');

    // Execute Choreo and get results
    $initializeOAuthResults = $initializeOAuth->execute($initializeOAuthInputs)->getResults();

    // Store callback id for second part of authorization
    $_SESSION['facebook_callback_id'] = $initializeOAuthResults->getCallbackID();

    // Redirect to sign in URL supplied by Facebook
    header("Location: " . $initializeOAuthResults->getAuthorizationUrl());
    exit;
}

Note that we pass the script's own address in the ForwardingURL. When the InitializeOAuth Choreo completes, we store the CallbackID it returns in a PHP session for later use, then redirect the user to the AuthorizationUrl returned by Facebook.

The last step is to run the FinalizeOAuth Choreo and store the returned AccessToken so the Facebook > Reading > User Choreo can use it to retrieve your user's profile information. The important thing to note here is that the CallBackID we saved to the PHP session in the previous step is now passed back to the FinalizeOAuth Choreo:

// Finalize authorization and retrieve access token after user is redirected back by Facebook.
function oauthFinal(Temboo_Session $session) {
    // Instantiate choreo with previously instantiated temboo session
    $finalizeOAuth = new Facebook_OAuth_FinalizeOAuth($session);

    // Get an input object for the Choreo
    $finalizeOAuthInputs = $finalizeOAuth->newInputs();

    // Set inputs
    $finalizeOAuthInputs->setAppId(APP_ID)->setAppSecret(APP_SECRET);
    $finalizeOAuthInputs->setCallbackID($_SESSION['facebook_callback_id']);
    $finalizeOAuthInputs->setLongLivedToken(1)->setTimeout(60);

    // Execute Choreo and get results
    $finalizeOAuthResults = $finalizeOAuth->execute($finalizeOAuthInputs)->getResults();

    $error = $finalizeOAuthResults->getErrorMessage();

    if($error) {
        throw new Exception('Facebook authorization failed: ' . $error);
    }

    // Store access token in PHP session
    $_SESSION['facebook_access_token'] = $finalizeOAuthResults->getAccessToken();

    // Callback ID no longer needed
    unset($_SESSION['facebook_callback_id']);

    // Redirect to base URL to fetch and display users's Likes.
    header("Location: " . TEMBOO_EXAMPLE_URI);
    exit;
}

What's Next?

We're all finished! This PHP application executes the OAuth flow, and retrieves information about your app's user. We also have OAuth support for many other APIs in our Choreo Library.

Once you've got your code up and running, you're ready to move on and do more. From monitoring your running applications, to moving your generated Temboo code to your preferred development environment and sharing it with colleagues, collaborators and friends - we've got you covered.

Get Live Updates About Your Application

Integrate Temboo with Slack to get up-to-the-second notifications and alerts about your deployed Temboo code.

Commit Code to GitHub

Commit Temboo-generated code directly to GitHub and share with the world. Learn more.

Need help?

We're always happy to help. Just email us at support@temboo.com, and we'll answer your questions.


Back