LinkedIn API basics

LinkedIn's docs are relatively good, but don't quite explain everything. I thought I'd share what I learned while setting up my first app.

At first it just wouldn't work. With the help of Debugging cURL Requests In PHP, I was able to pinpoint the cause: SSL certificate problem: unable to get local issuer certificate. For it to work, you have to either set CURLOPT_SSL_VERIFYPEER to false or try to fix the problem. It's most likely caused by a missing certificates file. You can download cacert.pem here.

<?php

$state = 'unique-random-string';
$uri = 'http://localhost/dev/linkedin.php';

if (isset($_GET['code']) && isset($_GET['state']) && $_GET['state'] === $state)
{
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, 'https://www.linkedin.com/uas/oauth2/accessToken');
	curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
	curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(array(
		'grant_type' => 'authorization_code',
		'code' => $_GET['code'],
		'redirect_uri' => $uri,
		'client_id' => 'YOUR_CLIENT_ID',
		'client_secret' => 'YOUR_CLIENT_SECRET',
	)));
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	$response = curl_exec($curl);
	curl_close($curl);

	var_dump(json_decode($response));
}

else
{
	$url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query(array(
		'response_type' => 'code',
		'client_id' => 'YOUR_CLIENT_ID',
		'redirect_uri' => $uri,
		'state' => $state,
		'scope' => 'r_basicprofile',
	));

	echo '<a href="' . $url . '">Authorize</a>';
}

?>

Once you've signed in and authorized your app, you'll get an access token that's valid for 60 days. You can test it by visiting https://api.linkedin.com/v1/people/~?oauth2_access_token=YOUR_TOKEN.

Comments