For anyone who is reading this and would like to use the LinkedIn Profile API
the solution to my problem was that I did not have a valid Access Token
when I attempted to make the first request.
The first thing I did was create a link that would direct the user to LinkedIn
authentication dialog box.
Next the user would then choose to approve or reject my applications request to access their profile. Regardless of their choice they are redirected to my redirect url
.
From here I now have an access code
which I can use to request an access token
and thus make api calls.
if (isset($_GET['error'])) {
echo $_GET['error'] . ': ' . $_GET['error_description'];
} elseif (isset($_GET['code'])) {
getAccessToken();
//$user = fetch('GET', '/v1/people/~:(firstName,lastName)');//get name
//$user = fetch('GET', '/v1/people/~:(phone-numbers)');//get phone numbers
$user = fetch('GET', '/v1/people/~:(location:(name))');//get country
var_dump($user);
}
The getAccessToken()
method that I used based on the code on the LinkedIn Developers site
https://developer.linkedin.com/documents/code-samples
function getAccessToken() {
$params = array(
'grant_type' => 'authorization_code',
'client_id' => 'MY API KEY',
'client_secret' => 'MY SECRET KEY',
'code' => $_GET['code'],
'redirect_uri' => 'MY REDIRECT URL',
);
// 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;
}
Then the fetch()
method, also from LinkedIn API
function fetch($method, $resource, $body = '') {
$opts = array(
'http' => array(
'method' => $method,
'header' => "Authorization: Bearer " .
$_SESSION['access_token'] . "\r\n" .
"x-li-format: json\r\n"
)
);
$url = 'https://api.linkedin.com' . $resource;
if (count($params)) {
$url .= '?' . http_build_query($params);
}
$context = stream_context_create($opts);
$response = file_get_contents($url, false, $context);
return json_decode($response);
}
By doing the above, I had no problem making requests to the API
. In fairness to Cbroe who commented above. I was missing this information. If he/she would like to leave an answer I'll gladly accept but just incase I've included my solution for anyone who runs into the issue I had.