Parse.com PHP Facebook Login with JavaScript

There is little documentation out there showing how to successfully create a new Parse user using PHP – Facebook login method. Here is the steps that worked for me:

  • Add  Facebook PHP-SDK in your web app
  • Add Facebook SDK for JavaScript. Include the Facebook login button.
  • Initialize a Facebook session. (Facebook App ID and App Secret). In your php code it should look like this:

$fb = new Facebook([
'app_id' =>'YOUr APP ID',
'app_secret' =>'YOUR APP SECRET',
'default_graph_version' => 'v2.5',
]);

  • Authenticate user with Facebook (clicking the javascript login button). Follow the facebook Javascript login button guide here:

Once the users authenticates via the login button. We will use the php javascript helper to retrieve the values to php.


$helper = $fb->getJavaScriptHelper();
 $oAuth2Client = $fb->getOAuth2Client();
 try {
 $accessToken = $helper->getAccessToken(); //getting short lived token
 $token = $accessToken;

 } 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();
 
 }

  • Get the user’s Facebook ID.

Once we have the token. We can get the long lived token and use that to retrieve the users Facebook values:


<strong></strong>

$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($token);
$longToken = $longLivedAccessToken->getValue();

$fb->setDefaultAccessToken($longLivedAccessToken);
 
 $response = $fb->get('/me?fields=id, email'); //retrieving users id and email

$user = $response->getGraphUser();
 $id = $user['id'];
 $email = $user['email'];

  • Authenticate the user with Parse with ID and access code.

ParseUser::logInWithFacebook($id, $longToken);

 

 

Here is the full php and js code. You’ll have to refresh the page a few times to show the user is created and logged in.


<?php 
use Facebook\Facebook as Facebook;
use Parse\ParseUser;
use Parse\ParseClient;
?>
<!DOCTYPE html>
<html>
    <head>
        <title>TEST PHP</title>

        <link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css">

        <style>
            html, body {
                height: 100%;
            }

            body {
                margin: 0;
                padding: 0;
                width: 100%;
                display: table;
                font-weight: 100;
                font-family: 'Lato';
            }

            .container {
                text-align: center;
                display: table-cell;
                vertical-align: middle;
            }

            .content {
                text-align: center;
                display: inline-block;
            }

            .title {
                font-size: 96px;
            }
        </style>
    </head>
    <body>
	
	<div id="fb-root"></div>
<div id="fb-root"></div>
<script>


function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
      // Logged into your app and Facebook.
      testAPI();
    } else if (response.status === 'not_authorized') {
      // The person is logged into Facebook, but not your app.
      document.getElementById('status').innerHTML = 'Please log ' +
        'into this app.';
    } else {
      // The person is not logged into Facebook, so we're not sure if
      // they are logged into this app or not.
      document.getElementById('status').innerHTML = 'Please log ' +
        'into Facebook.';
    }
  }

  // This function is called when someone finishes with the Login
  // Button.  See the onlogin handler attached to it in the sample
  // code below.
  function checkLoginState() {
    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  }

  window.fbAsyncInit = function() {
  FB.init({
    appId      : 'YOUR APP ID',
    cookie     : true,  // enable cookies to allow the server to access 
                        // the session
    xfbml      : true,  // parse social plugins on this page
    version    : 'v2.5' // use graph api version 2.5
  });

  // Now that we've initialized the JavaScript SDK, we call 
  // FB.getLoginStatus().  This function gets the state of the
  // person visiting this page and can return one of three states to
  // the callback you provide.  They can be:
  //
  // 1. Logged into your app ('connected')
  // 2. Logged into Facebook, but not your app ('not_authorized')
  // 3. Not logged into Facebook and can't tell if they are logged into
  //    your app or not.
  //
  // These three cases are handled in the callback function.

  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  });

  };


	(function(d, s, id) {
	  var js, fjs = d.getElementsByTagName(s)[0];
	  if (d.getElementById(id)) return;
	  js = d.createElement(s); js.id = id;
	  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.6&appId=YOURAPPID";
	  fjs.parentNode.insertBefore(js, fjs);
	}
(document, 'script', 'facebook-jssdk'));



</script>
	
	
        <div class="container">
            <div class="content">
                <div class="title">TESTING</div>
				<?php 
				
				//testing login
								$fb = new Facebook([
			  'app_id' => 'YOUR APP ID',
			  'app_secret' => 'YOUR APP SECRET',
			  'default_graph_version' => 'v2.5',
			]);
			
			//first check parse
			$currentUser = ParseUser::getCurrentUser();
			
			if($currentUser){
				echo 'user is logged in, logging out';
				//ParseUser::logOut();
			}
			else{
				
			
				
				
				$helper = $fb->getJavaScriptHelper();
				$oAuth2Client = $fb->getOAuth2Client();
				try {
				  $accessToken = $helper->getAccessToken(); //getting short lived token
				  $token = $accessToken;

				  
				  
				  
				  
				} 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();
			
				}
		
				if (! isset($accessToken)) {
  echo 'No cookie set or no OAuth data could be obtained from cookie.';

}else{

// Logged in
echo '<h3>Access Token</h3>';



$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($token);
$longToken = $longLivedAccessToken->getValue();  

				$fb->setDefaultAccessToken($longLivedAccessToken);
				
				$response = $fb->get('/me?fields=id, email');

				   $user = $response->getGraphUser();
				   $id = $user['id'];
				   $email = $user['email'];
				   
				   ParseUser::logInWithFacebook($id, $longToken); //works
			




}
			}
				?>
				<fb:login-button scope="public_profile,email" onlogin="checkLoginState();"></fb:login-button>
				<div id="status"> <?php //dispayis please login to facebook message if not logged in ?>
            </div>
        </div>
    </body>
</html>


Parse.com PHP GeoPoint- Laravel

I recently had a project that required an app to collect coordinates and display the location via an online dashboard.

I decided to use Parse.com as the backend for the app and the site. For the front end web part I went with the Laravel framework.

I came across the following issues when trying to echo out the coordinates from my parse table.

Object of class Parse\ParseGeoPoint could not be converted to string

Cannot use object of type Parse\ParseGeoPoint as array

The issue appeared to be related to a json conversion in Laravel as discussed here.

The fix was to encode the coordinate values to return array data if there is any.

Error:


$query2 = new ParseQuery("table");
$query2->select("coordinates");
$query2->select("username");
$query2->select("comments");
$query2->descending("createdAt");
$query2->limit(5);
$results2 = $query2->find();
if ($results2) {
//Display coordinates limit to 5
foreach($results2 as $row2){

echo $row2->username;
echo $row2->coordinates;
echo $row2->comments;
echo date_format($row2->getCreatedAt(), 'Y-m-d');

}
}

Encoding fix:

$query2 = new ParseQuery("table");
$query2->select("coordinates");
$query2->select("username");
$query2->select("comments");
$query2->descending("createdAt");
$query2->limit(5);
$results2 = $query2->find();
if ($results2) {
//Display coordinates limit to 5 
foreach($results2 as $row2){
 //encoding the coordinate values to return array data if there is data
 $values = $row2->coordinates->_encode();
 echo $row2->username;
 echo $values['latitude'] . ',' . $values['longitude']; 
 echo $row2->comments;
 echo date_format($row2->getCreatedAt(), 'Y-m-d');

}
}