Wednesday, March 16, 2016

Login with Facebook using PHP with v5 SDK

It has been a long time since my last post about Facebook. Many things have changed since. This time I want to talk about the new version of Login PHP SDK for Facebook.

The latest version of SDK can be found here.

I think I can skip to codes directly as all the steps to install the SDK and obtain the app_id and app_secret can be easily found in the internet. But I need to point out the errors you may see if something goes wrong. If you see the following error:

Parse error: syntax error, unexpected '[', expecting ')' in ...

You need a PHP 5.4 or higher version to avoid this error.

Instead, if you see this:

Cross-site request forgery validation failed. The "state" param from the URL and session do not match.

It means your app_id and app_secret are not registered to run in the current domain.

Facebook required us to run the login authorization process in two parts: the login link page and the call-back page. The login page will produce a link with new access token to comply with OAuth 2.0 flow. The next page is to process the call-back from Facebook with valid access token so as to do anything with the verified login such as accessing the ID or email address.

As my philosophy is always to make things short and simple as programmers will not like anything too windy, I combined the two parts into one PHP script. Here is the hybrid script:

<?php

session_start();

require_once __DIR__ . '/facebookV5/autoload.php'; // Please point to your facebook SDK autoload.php

$fb = new Facebook\Facebook([
  'app_id' => 'Your App ID',
  'app_secret' => 'Your App Secret',
  'default_graph_version' => 'v2.5',
]);



if (!isset($_GET['code'])) { // If it is a callback, you will get 'code' as query string.

  $helper = $fb->getRedirectLoginHelper();

  $myURL = '{Your Login URL}'; // The URL to this very script such as http://yourdomainname.com/this_hybrid_login_script.php
  $permissions = ['email']; // Optional permissions
  $loginUrl = $helper->getLoginUrl($myURL, $permissions);

  //header( 'Location: ' . htmlspecialchars($loginUrl) ); PLEASE DO USE REDIRECT WITH PHP HEADER! Somehow it doesn't work well with Facebook OAuth 2.0 flow
  echo("<meta http-equiv='refresh' content=\"0;URL='". htmlspecialchars($loginUrl) ."'\" />");
  exit;
}
else { // This is the call-back section:

  $helper = $fb->getRedirectLoginHelper();
  try {
    $accessToken = $helper->getAccessToken();
  } catch( Facebook\Exceptions\FacebookSDKException $e ) {
    echo $e->getMessage();
    exit;
  }

  if (isset($accessToken)) {
    $_SESSION['facebook_access_token'] = ( string ) $accessToken;

    $fb->setDefaultAccessToken($accessToken);

    try {
      $response = $fb->get('/me?fields=email');
      $userNode = $response->getGraphUser();
    } catch(Facebook\Exceptions\FacebookResponseException $e) {
      echo 'Graph returned an error: ' . $e->getMessage();
      exit;
    } catch(Facebook\Exceptions\FacebookSDKException $e) {
      echo 'Facebook SDK returned an error: ' . $e->getMessage();
      exit;
    }

    $me = $response->getGraphUser();
    echo "Your Facebook Email: ".$me->getProperty('email');

    // You now can use the email for the rest of the login process

    exit;
  }
  else if ( $helper->getError() ) {

    // Facebook Login Error

    echo( $helper->getError()."<br>" );
    echo( $helper->getErrorCode()."<br>" );
    echo( $helper->getErrorReason()."<br>" );
    echo( $helper->getErrorDescription()."<br>" );
    exit;
  }

  echo("Access Token cannot be obtained.");
  // You need to debug if you see this as it shouldn't reach here.
  exit;
}

?>


This is a 2-in-1 script. I use the query string 'code' as a signal to decide where it is a call-back from Facebook or it is the first-run before linking to Facebook. If everything goes well and your browser has not run this PHP code before, you will encounter a page where Facebook will ask for your permission to run this PHP app. Here is an example of how it looks like:



After continuing this authorization process, you will not see this page again unless you change the app_id and app_secret. Enjoy logging in with Facebook!

No comments:

Post a Comment