TrinityTuts

Facebook integration PHP application

Facebook integration PHP application

Last updated on June 5th, 2018 at 08:07 pm

Note: This post is outdated

Facebook oAuth system is implemented on most of the web application nowadays. In this post, I am going to explain how we can implement Facebook in our own web application. Facebook integration is very easy to implement you can implement it in few minutes. Before start implementing oAuth system in your application first create new app in Facebook developer account.

Facebook integration PHP application

Step 1. Go to Facebook developer site and create new app select Website platform

Step 2. Name your app whatever you like

Step 3. Create an App Id for your app

Step 4. Now last step is to make your app available for all user.

 

 

Step 5. After your app is live you need to download PHP SDK from Facebook. You can download Facebook from  using GIT or you can download using Composer.

{
  "require" : {
    "facebook/php-sdk-v4" : "~5.0"
  }
}

Step 6. Now you need to include Facebook sdk in your application as shown below code.

<?php
	session_start();
	require_once '../lib/Facebook/autoload.php';
	$fb = new Facebook\Facebook([
	  'app_id' => '<YOUR_ID>',
	  'app_secret' => '<APP_SECRET>',
	  'default_graph_version' => 'v2.5',
	]);
	
	$helper = $fb->getRedirectLoginHelper();
	$permissions = ['email']; // optional
	$loginUrl = $helper->getLoginUrl('http://www.attireme.in/facebook/login-callback.php', $permissions);

	echo '<a href="' . $loginUrl . '">Log in with Facebook!</a>';

	$helper = $fb->getRedirectLoginHelper();
	try {
	  $accessToken = $helper->getAccessToken();
	} catch(Facebook\Exceptions\FacebookResponseException $e) {
	  // When Graph returns an error
	  echo 'Graph returned an error: ' . $e->getMessage();
	  exit;
	} catch(Facebook\Exceptions\FacebookSDKException $e) {
	  // When validation fails or other local issues
	  echo 'Facebook SDK returned an error: ' . $e->getMessage();
	  exit;
	}

	if (isset($accessToken)) {
	  // Logged in!
	  echo $_SESSION['facebook_access_token'] = (string) $accessToken;

	  // Now you can redirect to another page and use the
	  // access token from $_SESSION['facebook_access_token']
	}

Step 7. After this we need to create a callback file where Facebook redirect us.

<?php
	session_start();
	require_once '../lib/Facebook/autoload.php';
	$fb = new Facebook\Facebook([
	'app_id' => '<YOUR_ID>',
	'app_secret' => '<APP_SECRET>',
	'default_graph_version' => 'v2.5',
	]);
	
	$helper = $fb->getRedirectLoginHelper();
	
	try {
		$accessToken = $helper->getAccessToken();
		} catch(Facebook\Exceptions\FacebookResponseException $e) {
		// When Graph returns an error
		echo 'Graph returned an error: ' . $e->getMessage();
		} catch(Facebook\Exceptions\FacebookSDKException $e) {
		// When validation fails or other local issues
		echo 'Facebook SDK returned an error: ' . $e->getMessage();
		///header('location:/login');
	}
	
	if (! isset($accessToken)) {
		if ($helper->getError()) {
			header('HTTP/1.0 401 Unauthorized');
			echo "Error: " . $helper->getError() . "\n";
			echo "Error Code: " . $helper->getErrorCode() . "\n";
			echo "Error Reason: " . $helper->getErrorReason() . "\n";
			echo "Error Description: " . $helper->getErrorDescription() . "\n";
			} else {
			header('HTTP/1.0 400 Bad Request');
			echo 'Bad request';
		}
		//header('location:/login');
	}
	
	// The OAuth 2.0 client handler helps us manage access tokens
	$oAuth2Client = $fb->getOAuth2Client();
	
	// Get the access token metadata from /debug_token
	$tokenMetadata = $oAuth2Client->debugToken($accessToken);
	echo '<h3>Metadata</h3>';
	var_dump($tokenMetadata);
	
	// Validation (these will throw FacebookSDKException's when they fail)
	$tokenMetadata->validateAppId('442186309214489'); // Replace {app-id} with your app id
	// If you know the user ID this access token belongs to, you can validate it here
	//$tokenMetadata->validateUserId('123');
	$tokenMetadata->validateExpiration();
	
	if (! $accessToken->isLongLived()) {
		// Exchanges a short-lived access token for a long-lived one
		try {
			$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
			} catch (Facebook\Exceptions\FacebookSDKException $e) {
			echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n";
			//header('location:/login');
		}
		
		var_dump($accessToken->getValue());
	}
	
	$_SESSION['fb_access_token'] = (string) $accessToken;
	$fb->setDefaultAccessToken($accessToken);
	
	try {
		$response = $fb->get('/me?fields=id,name,first_name,last_name,email');
		$userNode = $response->getGraphUser();
		} catch(Facebook\Exceptions\FacebookResponseException $e) {
		// When Graph returns an error
		echo 'Graph returned an error: ' . $e->getMessage();
		
		} catch(Facebook\Exceptions\FacebookSDKException $e) {
		// When validation fails or other local issues
		echo 'Facebook SDK returned an error: ' . $e->getMessage();
	}
	
	//echo 'Logged in as ' . $userNode->getName();
	//echo "<pre>";
	if(!$userNode->getField('email')){
		header('location:/login');
	}else{
		// Create account or check if exsits login user
		// array("token" => $accessToken->getValue(), 'email' => $userNode->getField('email'), 'first_name' => $userNode->getField('first_name'), 'last_name' => $userNode->getField('last_name'), 'social_id' => $userNode->getField('id'))
		// Save user info
	}

Done!.