Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive
linkedin.png

LinkedIn has shown to the world to be a good professional social network. You can have your professional profile or your company profile; leave the socialité to Facebook. After a while, reading how to do a PHP code that allows you to authenticate, I didn't find a PHP lib to do that (note that my Google-Fu is very bad, I don't doubt there are some). So, here it is how I did it.

First thing is to be registered as a LinkedIn developer (just like Facebook); I won't talk about how to do this. You will need to create there your application, when you are done you will need API Key and API secret.

Here it is the little code I did:

// Change these
define('API_KEY',      'API_KEY_FROM_WEBSITE');
define('API_SECRET',   'API_SECRET_FROM_WEBSITE');
// You must pre-register your redirect_uri at https://www.linkedin.com/secure/developer
//define('REDIRECT_URI', 'CALL_BACK URL');
define('REDIRECT_URI', 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME']);
define('SCOPE', 'r_basicprofile r_emailaddress '   );

if (!defined('PHP_VERSION_ID')) {
        $version = explode('.', PHP_VERSION);
        define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
}

if (PHP_VERSION_ID >= 50400) {
       if (session_status() == PHP_SESSION_NONE) {
           session_start();
       }
}
else{
       if(session_id() == '') {
           session_start();
       }
}

// OAuth 2 Control Flow
if (isset($_GET['error'])) {
        // LinkedIn returned an error
        print $_GET['error'] . ': ' . $_GET['error_description'];
        exit;
} elseif (isset($_GET['code'])) {
        // User authorized your application
        if ($_SESSION['state'] == $_GET['state']) {
                // Get token so you can make API calls
                getAccessToken();
        }
        else {
                // CSRF attack? Or did you mix up your states?
                exit;
        }
}
else {  
        if ((empty($_SESSION['expires_at'])) || (time() > $_SESSION['expires_at'])) {
                // Token has expired, clear the state
                //$_SESSION = array();
                $_SESSION['state'] = null;
        }
        if (empty($_SESSION['access_token'])) {
                // Start authorization process
                getAuthorizationCode();
        }
}

// Congratulations! You have a valid token. Now fetch your profile  
$user = fetch('GET', '/v1/people/~:(firstName,lastName,industry,emailAddress,phoneNumbers,positions,twitterAccounts,primaryTwitterAccount,numConnecti
ons,numConnectionsCapped)');
print "Hello $user->firstName $user->lastName.";
print "You work in $user->industry.";
print "You have $user->numConnections ($user->numConnectionsCapped) contacts. ";
print "<hr/>";
$phones = $user->phoneNumbers->values;
for ($i = 0; $i < $user->phoneNumbers->_total; $i++){
       print $phones[$i]->phoneNumber."(".$phones[$i]->phoneType.")<br/>";
}

$positions = $user->positions->values;
for ($i = 0; $i < $user->positions->_total; $i++){
       print $positions[$i]->company->name."(".$positions[$i]->startDate->month."/".$positions[$i]->startDate->year.")<br/>";
}

print "best twitter: ".$user->primaryTwitterAccount->providerAccountName."<br/>";
print "other (all) twitter accounts:";
$twitters = $user->twitterAccounts->values;
for ($i = 0; $i < $user->twitterAccounts->_total; $i++){
       print $twitters[$i]->providerAccountName." ";
}

print "<pre>";
print_r($user);
print "</pre>";
exit;

function getAuthorizationCode() {
        $params = array(
                'response_type' => 'code',
                'client_id' => API_KEY,
                'scope' => SCOPE,
                'state' => uniqid('', true), // unique long string
                'redirect_uri' => REDIRECT_URI,
        );

        // Authentication request
        $url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);

        // Needed to identify request when it returns to us
        $_SESSION['state'] = $params['state'];

        // Redirect user to authenticate
        header("Location: $url");
        exit;
}

function getAccessToken() {
        $params = array(
                'grant_type' => 'authorization_code',
                'client_id' => API_KEY,
                'client_secret' => API_SECRET,
                'code' => $_GET['code'],
                'redirect_uri' => REDIRECT_URI,
        );

        // Access Token request
        $url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);

        // Tell streams to make a POST request
        $context = stream_context_create(
                 array('http' =>  
                         array('method' => 'POST',
                         )
                 )
         );

         // Retrieve access token information
         $response = file_get_contents($url, false, $context);

         // Native PHP object, please
         $token = json_decode($response);

         // Store access token and expiration time
         $_SESSION['access_token'] = $token->access_token; // guard this!  
         $_SESSION['expires_in']   = $token->expires_in; // relative time (in seconds)
         $_SESSION['expires_at']   = time() + $_SESSION['expires_in']; // absolute time

         return true;
}

function fetch($method, $resource, $body = '') {
         // print $_SESSION['access_token'];

         $opts = array(
                 'http'=>array(
                         'method' => $method,
                         'header' => "Authorization: Bearer " . $_SESSION['access_token'] . "\r\n" . "x-li-format: json\r\n"
                 )
          );

          // Need to use HTTPS
          $url = 'https://api.linkedin.com' . $resource;

          // Append query parameters (if there are any)
          if (count($params)) { $url .= '?' . http_build_query($params); }

          // Tell streams to make a (GET, POST, PUT, or DELETE) request
          // And use OAuth 2 access token as Authorization
          $context = stream_context_create($opts);

          $response = file_get_contents($url, false, $context);
          return json_decode($response);
}

exit;

And yes, it is a nasty code. I am sure it can be improved in many ways. Check the $user variable, it has all you need to feed your software.

Enjoy!

blog comments powered by Disqus

About

Read about IT, Migration, Business, Money, Marketing and other subjects.

Some subjects: FusionPBX, FreeSWITCH, Linux, Security, Canada, Cryptocurrency, Trading.