limeygent
limeygent

Reputation: 426

LinkedIn API - posting to a group or profile share returns a 401 authentication code

I had a problem with no documented solution that I could find. Now that I found it, I'm posting it here in the event someone runs into the same issue.

I followed the steps to authenticate with LinkedIn and get an access token, I was able to retrieve my profile information and groups that I belong to without any issue.

Next, I wanted to make a post to a group using the API.

The LinkedIn API docs show the use of file_get_contents, but it was not working for me. The access token was correct, but I was receiving a 401 response. Refer to https://developer.linkedin.com/documents/code-samples. Because I added ignore_errors=1, the group post was made, but still returning a 401.

As reference, this was the piece of code that I had to change to resolve the 401:

$context = stream_context_create(
  array('http' => 
    array('method' =>"POST",                        
      'header'=> "Content-Type:application/json\r\n",
      'content' => $body,
      'ignore_errors' => '1'
    )
  )
);
$res = file_get_contents($url, false, $context);

Upvotes: 1

Views: 2730

Answers (1)

limeygent
limeygent

Reputation: 426

Solution Overview

Using the LinkedIn API to post to a group, the steps are:

Set up the URL:

$params = array('oauth2_access_token' => YOUR_ACCESS_TOKEN);

$url = 'https://api.linkedin.com/v1/groups/{group_id}/posts?' . http_build_query($params);

Set the body for the POST

$bodyArray = array(
  'title' => $title,
  'summary' => $userMessage,
  'content' => array(
    'title' => '$title2',
    'submitted-image-url' => $pictureUrl,                
    'submitted-url' => $redirectUrl,
    'description' => $userMessage                
  )            
);
$body = json_encode($bodyArray);

Use CURL instead of get_file_contents This is what I needed to change to get it working.

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => $url,
    CURLOPT_POST => 1,
    CURLOPT_HTTPHEADER => array('x-li-format: json', "Content-Type: application/json"),
    CURLOPT_POSTFIELDS => $body,
));     

// here we execute the code and check for response code
curl_exec($curl);
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if ($http_status == "201"){
  echo date('g:i') . ' Posted to LinkedIn group <br>';
}else{
  echo date('g:i') . '<b>LinkedIn error: ' . $http_status . '</b><br>';
}

Upvotes: 2

Related Questions