As a good start we also recommend to read "Social Media Authentication and Authorization Using PHP", an extremely well written tutorial by Larry E. Ullman.


HybridAuth can be easly integrated on you existing website. All you have to do is to include hybridauth main file and to add a couple of lines to your login page like it's shown in the sample bellow.

The snippet will try to directly connect the user with Twitter then grab his complete profile and also access the twitter social api:

<?php
  // start a new session (required for Hybridauth)
  session_start();

  // change the following paths if necessary
  $config   = dirname(__FILE__) . '/library/config.php';
  require_once( "library/Hybrid/Auth.php" );

  try{
  	// create an instance for Hybridauth with the configuration file path as parameter
  	$hybridauth = new Hybrid_Auth( $config );

  	// try to authenticate the user with twitter,
  	// user will be redirected to Twitter for authentication,
  	// if he already did, then Hybridauth will ignore this step and return an instance of the adapter
  	$twitter = $hybridauth->authenticate( "Twitter" );

  	// get the user profile
  	$twitter_user_profile = $twitter->getUserProfile();

  	echo "Ohai there! U are connected with: <b>{$twitter->id}</b><br />";
  	echo "As: <b>{$twitter_user_profile->displayName}</b><br />";
  	echo "And your provider user identifier is: <b>{$twitter_user_profile->identifier}</b><br />";

  	// debug the user profile
  	print_r( $twitter_user_profile );

  	// exp of using the twitter social api: Returns settings for the authenticating user.
  	$account_settings = $twitter->api()->get( 'account/settings.json' );

  	// print recived settings
  	echo "Your account settings on Twitter: " . print_r( $account_settings, true );

  	// disconnect the user ONLY form twitter
  	// this will not disconnect the user from others providers if any used nor from your application
  	echo "Logging out..";
  	$twitter->logout();
  }
  catch( Exception $e ){
  	// Display the recived error,
  	// to know more please refer to Exceptions handling section on the userguide
  	switch( $e->getCode() ){
  	  case 0 : echo "Unspecified error."; break;
  	  case 1 : echo "Hybriauth configuration error."; break;
  	  case 2 : echo "Provider not properly configured."; break;
  	  case 3 : echo "Unknown or disabled provider."; break;
  	  case 4 : echo "Missing provider application credentials."; break;
  	  case 5 : echo "Authentification failed. "
  	              . "The user has canceled the authentication or the provider refused the connection.";
  	           break;
  	  case 6 : echo "User profile request failed. Most likely the user is not connected "
  	              . "to the provider and he should authenticate again.";
  	           $twitter->logout();
  	           break;
  	  case 7 : echo "User not connected to the provider.";
  	           $twitter->logout();
  	           break;
  	  case 8 : echo "Provider does not support this feature."; break;
  	}

  	// well, basically your should not display this to the end user, just give him a hint and move on..
  	echo "<br /><br /><b>Original error message:</b> " . $e->getMessage();
  }

After authentication, the sample will output something similar to:

Ohai there! U are connected with: Twitter
As: HybridAuth
And your provider user identifier is: 80359084 Hybrid_User_Profile Object ( [identifier] => 80359084 [webSiteURL] => http://hybridauth.sourceforge.net/ [profileURL] => http://twitter.com/HybridAuth [photoURL] => http://a0.twimg.com/profile_images/480547080/twi_normal.gif [displayName] => HybridAuth [description] => HybridAuth, An Open Source Social-Sign-On PHP Library. #PHP #API #REST #OpenID #OAuth #SSO [firstName] => Zachy [lastName] => [gender] => [language] => [age] => [birthDay] => [birthMonth] => [birthYear] => [email] => [phone] => [address] => [country] => [region] => [city] => [zip] => ) Your account settings on Twitter: stdClass Object ( [protected] => [use_cookie_personalization] => 1 [geo_enabled] => [always_use_https] => 1 [sleep_time] => stdClass Object ( [start_time] => [end_time] => [enabled] => ) [screen_name] => Zachy [discoverable_by_email] => 1 [language] => en ) Logging out..

How it work the short story

                          +------------+
                          |            |   1    +--------------+   2    +------------+
                          |   Your     |=======>|              |=======>|            |
                          |            |        |  HybridAuth  |   3    |  Twitter   |
                          |   Login    |        |              |<=======|            |
                          |            |   5    |   Endpoint   |   4    |    API     |
                          |   Page     |<=======|              |<======>|            |
                          |            |        +--------------+        +------------+
                          +------------+

1) If not connected yet, Hybrid_Auth::authenticate() will redirect the user to the HybridAuth endpoint
2) HybridAuth endpoint will redirect the user to twitter for authentication
3) IF the user grant access to your site, then Twitter will call back HybridAuth endpoint
4) HybridAuth endpoint will ask twitter for a temporary authorization in order for your application to access the twitter api and the user private resources (eg. profile, contact lists, photos)
5) Finally, we redirect the user a one last time to the original page where he come from

To authentificate a user with Twitter all what we have to do here is the first step, and HybridAuth will take care of the rest of it (steps 2, 3, 4 and 5).

Note:
Basically, when a user is connected to your application via a given provider using hybridauth, then he should be considered as if he have 3 different sessions:

  • the first one is on the provider side
  • a session within hybridauth
  • and another one within your application

If the first session is interrupted for some reason (if the user revoke the access given for your application while he still have a session with hybridauth, the authorization has expired, user disconnect form the provider, etc.) then hybridauth will no longer be able to communicate with the provider api ( Error Codes 6 or 7 ) and in this case we have to use Hybrid_Provider_Adapter::logout() to let hybridauth forget all about the user so we can try to authenticate the user again or to move on to something else.