LinkedIn API - 发布到组或配置文件共享返回401身份验证代码

时间:2014-02-11 22:22:00

标签: php api linkedin

我遇到了一个问题,我找不到任何记录的解决方案。现在我找到了它,如果有人遇到同样的问题,我会把它发布在这里。

我按照步骤对LinkedIn进行身份验证并获取访问令牌,我能够毫无问题地检索我所属的个人资料信息和群组。

接下来,我想使用API​​向论坛发帖。

LinkedIn API文档显示file_get_contents的使用,但它不适用于我。访问令牌是正确的,但我收到了401 response。请参阅https://developer.linkedin.com/documents/code-samples。由于我添加了ignore_errors=1,因此发布了小组帖子,但仍然返回了401

作为参考,这是我必须更改以解析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);

1 个答案:

答案 0 :(得分:2)

解决方案概述

使用LinkedIn API发布到论坛,步骤如下:

设置网址:

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

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

设置POST的正文

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

使用CURL代替get_file_contents这是我需要更改以使其正常工作。

$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>';
}
相关问题