Table Of Contents:

diagram-oauth-handshake

You want to access linkedIn API using OAuth Protocol handshake?

Here is a Screencast and a written tutorial showing you how to access linkedIn API in PHP using Zend_Oauth Zend module.

The LinkedIn API Access ScreenCast

http://blip.tv/file/get/Formatix-linkedInAPIPhpZendOauthEng748.mp4

The LinkedIn API Access Written Tutorial

Step 0. Get LinkedIn Consumer Keys

Step 1. Get the Zend Ressources

Get Zend FrameWork Library

svn checkout http://framework.zend.com/svn/framework/standard/trunk/library/

Get Zend FrameWork Incubator Library

svn checkout http://framework.zend.com/svn/framework/standard/incubator/library/

If you are under Windows you can Download Tortoise SVN to be able to extract the Zend Sources

Step 2.a Include the Zend_Oauth module

To do so we first need to add Zend Library and Zend Incubator Library to the Include Path:

set_include_path( '/home/mywebspace/libray/' . PATH_SEPARATOR .  '/home/mywebspace/incubator/libray/' . PATH_SEPARATOR . get_include_path()                                       );

Of Course /home/mywebspace/libray/ and /home/mywebspace/incubator/libray/ must be replaced with your own paths.

If you are under windows this Paths will look like C:/mylibrariesfolder/library’

Now we can include the Zend_Oauth Class definition we need that is to say Zend_Oauth_Consumer

require_once('Zend/Oauth/Consumer.php');

Step 2.b Correct Zend_Oauth module

At the time I am writing this tutorial there is a little issue that prevents us to use Zend_Oauth as it is to connect to LinkedIn using Oauth Protocol 0.1 Rev A

To Bypass this issue:

  • Open ./Zend/Oauth/Http/UserAuthorisation.php file
  • Goto function assembleParams
  • Remove or comment the following Lines
	public function assembleParams()
	{
		$params = array();
		$params['oauth_token'] = $this->_consumer->getLastRequestToken()->getToken();
		$callback = $this->_consumer->getCallbackUrl(); // callback correct? Not user auth uri?

		// if (!empty($callback)) {
			// $params['oauth_callback'] = $callback;
		// }
		if (!empty($this->_parameters)) {
			$params = array_merge($params, $this->_parameters);
		}
		return $params;
	}

Step 3. Create an Instance of Zend_Oauth_Consumer

You must tune the $options inputs such as localUrl, callbackUrl, and fill in the blanks for consumerKey and consumerSecret with the Keys you retreived at Step 0.

$options = array(
'version' => '1.0',
'localUrl' => 'http://localhost/Projets/API/oauth.php',
'callbackUrl' => 'http://localhost/Projets/API/oauth.php',
'requestTokenUrl' => 'https://api.linkedin.com/uas/oauth/requestToken',
'userAuthorisationUrl' => 'https://api.linkedin.com/uas/oauth/authorize',
'accessTokenUrl' => 'https://api.linkedin.com/uas/oauth/accessToken',
'consumerKey' => 'YOUR_CONSUMER_KEY',
'consumerSecret' => 'YOUR_SECRET_KEY'
);

$consumer = new Zend_Oauth_Consumer( $options );

Step 4. Undertake the Oauth authentication handshake

// Start Session to be able to store Request Token and Access Token
session_start ();

if ( !isset ( $_SESSION ['ACCESS_TOKEN'] )) {
	// We do not have any access token Yet
	if (! empty ( $_GET )) {
		// But We have some parameters passed throw the URL

		// Get the LinkedIn Access Token
		$token = $consumer->getAccessToken ( $_GET, unserialize ( $_SESSION ['REQUEST_TOKEN'] ) );

		// Store the LinkedIn Access Token
		$_SESSION ['ACCESS_TOKEN'] = serialize ( $token );
	} else {
		// We have Nothing

		// Start Requesting a LinkedIn Request Token
		$token = $consumer->getRequestToken ();

		// Store the LinkedIn Request Token
		$_SESSION ['REQUEST_TOKEN'] = serialize ( $token );

		// Redirect the Web User to LinkedIn Authentication  Page
		$consumer->redirect ();
	}
} else {
	// We've already Got a LinkedIn Access Token

	// Restore The LinkedIn Access Token
	$token = unserialize ( $_SESSION ['ACCESS_TOKEN'] );

}

Step 5. Get User’s Profile From LinkedIn

Now that authentication is done we can request data from LinkedIn

// Use HTTP Client with built-in OAuth request handling
$client = $token->getHttpClient($options);

// Set LinkedIn URI
$client->setUri('https://api.linkedin.com/v1/people/~');
// Set Method (GET, POST or PUT)
$client->setMethod(Zend_Http_Client::GET);
// Get Request Response
$response = $client->request();

// Get the XML containing User's Profile
$content =  $response->getBody();

XML content looks like this:

LinkedIn-API-Screencast-Get-Profile-XML

Step 6. Extract and Display Information from LinkedIn XML

// Use simplexml to transform XML to a PHP Object

$xml = simplexml_load_string($content);

echo 'First Name: ' . $xml->{'first-name'};
echo '<br/>';
echo 'Last Name: ' . $xml->{'last-name'};
echo '<br/>';
echo 'Headline: ' . $xml->{'headline'};

SimpleXml Object Structure looks like this:

Php-LinkedIn-API-Screencast-Simple-XML-Profile-Structure

Step 7. Overview of the All Script

You can create a file called oauth.php and paste the following php code in it

<?php

set_include_path( 'C:/Users/Formatix.Eu/Desktop/MesProjets/API/library' . PATH_SEPARATOR .  'C:/Users/Formatix.Eu/Desktop/MesProjets/API/incubator/library' . PATH_SEPARATOR . get_include_path()                                       );

require_once('Zend/Oauth/Consumer.php');

$options = array(
'version' => '1.0',
'localUrl' => 'http://localhost/Projets/API/oauth.php',
'callbackUrl' => 'http://localhost/Projets/API/oauth.php',
'requestTokenUrl' => 'https://api.linkedin.com/uas/oauth/requestToken',
'userAuthorisationUrl' => 'https://api.linkedin.com/uas/oauth/authorize',
'accessTokenUrl' => 'https://api.linkedin.com/uas/oauth/accessToken',
'consumerKey' => 'YOUR_CONSUMER_KEY',
'consumerSecret' => 'YOUR_CONSUMER_SECRET_KEY'
);

$consumer = new Zend_Oauth_Consumer( $options );

// Start Session to be able to store Request Token and Access Token
session_start ();

if ( !isset ( $_SESSION ['ACCESS_TOKEN'] )) {
	// We do not have any access tokem Yet
	if (! empty ( $_GET )) {
		// But We have some parameters passed throw the URL

		// Get the LinkedIn Access Token
		$token = $consumer->getAccessToken ( $_GET, unserialize ( $_SESSION ['REQUEST_TOKEN'] ) );

		// Store the LinkedIn Access Token
		$_SESSION ['ACCESS_TOKEN'] = serialize ( $token );
	} else {
		// We have Nothing

		// Start Requesting a LinkedIn Request Token
		$token = $consumer->getRequestToken ();

		// Store the LinkedIn Request Token
		$_SESSION ['REQUEST_TOKEN'] = serialize ( $token );

		// Redirect the Web User to LinkedIn Authentication  Page
		$consumer->redirect ();
	}
} else {
	// We've already Got a LinkedIn Access Token

	// Restore The LinkedIn Access Token
	$token = unserialize ( $_SESSION ['ACCESS_TOKEN'] );

}

// Use HTTP Client with built-in OAuth request handling
$client = $token->getHttpClient($options);

// Set LinkedIn URI
$client->setUri('https://api.linkedin.com/v1/people/~');
// Set Method (GET, POST or PUT)
$client->setMethod(Zend_Http_Client::GET);
// Get Request Response
$response = $client->request();

// Get the XML containing User's Profile
$content =  $response->getBody();

// Uncomment Following Line To display XML result
// header('Content-Type: ' . $response->getHeader('Content-Type'));
// echo $content;
// exit;

// Use simplexml to transform XML to a PHP Object
$xml = simplexml_load_string($content);

// Uncomment Following Line To display Simple XML Object Structure
// echo '<pre>';
// print_r($xml);
// echo'</pre>';

// Display Profile Information as you wish
echo 'First Name: ' . $xml->{'first-name'};
echo '<br/>';
echo 'Last Name: ' . $xml->{'last-name'};
echo '<br/>';
echo 'Headline: ' . $xml->{'headline'};

?>

Step 8. Transform this Raw code into a nice looking Php Class

<?php

/*
*
* @abstract: This Class can be used to Access LinkedIn API using Oauth Authentication Protocol
* @author: Christophe Fiat
* @version: 0.1 2009-11-30
* @copyright: FormatiX.EU
*
*/

class linkedIn
{

	private $options;
	private $consumer;
	private $client;
	private $token;

	public function __construct($params)
	{
		set_include_path( 'C:/Users/Formatix.Eu/Desktop/MesProjets/API/library' . PATH_SEPARATOR .  'C:/Users/Formatix.Eu/Desktop/MesProjets/API/incubator/library' . PATH_SEPARATOR . get_include_path()                                       );

		require_once('Zend/Oauth/Consumer.php');

		$this->options = array(
		'version' => '1.0',
		'localUrl' => 'http://localhost/Projets/API/oauth.php',
		'callbackUrl' => 'http://localhost/Projets/API/oauth.php',
		'requestTokenUrl' => 'https://api.linkedin.com/uas/oauth/requestToken',
		'userAuthorisationUrl' => 'https://api.linkedin.com/uas/oauth/authorize',
		'accessTokenUrl' => 'https://api.linkedin.com/uas/oauth/accessToken',
		'consumerKey' => $params['consumerKey'],
		'consumerSecret' => $params['consumerSecret']
		);

		$this->consumer = new Zend_Oauth_Consumer( $this->options );

	}

	public function connect()
	{
		// Start Session to be able to store Request Token and Access Token
		session_start ();

		if ( !isset ( $_SESSION ['ACCESS_TOKEN'] )) {
			// We do not have any Access token Yet
			if (! empty ( $_GET )) {
				// But We have some parameters passed throw the URL

				// Get the LinkedIn Access Token
				$this->token = $this->consumer->getAccessToken ( $_GET, unserialize ( $_SESSION ['REQUEST_TOKEN'] ) );

				// Store the LinkedIn Access Token
				$_SESSION ['ACCESS_TOKEN'] = serialize ( $this->token );
			} else {
				// We have Nothing

				// Start Requesting a LinkedIn Request Token
				$this->token = $this->consumer->getRequestToken ();

				// Store the LinkedIn Request Token
				$_SESSION ['REQUEST_TOKEN'] = serialize ( $this->token );

				// Redirect the Web User to LinkedIn Authentication  Page
				$this->consumer->redirect ();
			}
		} else {
			// We've already Got a LinkedIn Access Token

			// Restore The LinkedIn Access Token
			$this->token = unserialize ( $_SESSION ['ACCESS_TOKEN'] );

		}

		// Use HTTP Client with built-in OAuth request handling
		$this->client = $this->token->getHttpClient($this->options);

	}

	public function whoAmI()
	{

		// Set LinkedIn URI
		$this->client->setUri('https://api.linkedin.com/v1/people/~');
		// Set Method (GET, POST or PUT)
		$this->client->setMethod(Zend_Http_Client::GET);
		// Get Request Response
		$response = $this->client->request();

		// Get the XML containing User's Profile
		$content =  $response->getBody();

		// Uncomment Following Line To display XML result
		// header('Content-Type: ' . $response->getHeader('Content-Type'));
		// echo $content;
		// exit;

		// Use simplexml to transform XML to a PHP Object
		$xml = simplexml_load_string($content);

		// Uncomment Following Line To display Simple XML Object Structure
		// echo '<pre>';
		// print_r($xml);
		// echo'</pre>';

		// Display Profile Information as you wish
		echo 'First Name: ' . $xml->{'first-name'};
		echo '<br/>';
		echo 'Last Name: ' . $xml->{'last-name'};
		echo '<br/>';
		echo 'Headline: ' . $xml->{'headline'};

	}

} // Class End

$params = Array(    'consumerKey' => 'YOUR_CONSUMER_KEY',
'consumerSecret' => 'YOUR_CONSUMER_SECRET_KEY'
);

$linkedin = new linkedIn($params);

$linkedin->connect();

$linkedin->whoAmI();

?>