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



我遇到了一个问题,没有我能找到的文档解决方案。 现在我找到了它,如果有人遇到同样的问题,我把它发布在这里。

我按照步骤向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/jsonrn",
      'content' => $body,
      'ignore_errors' => '1'
    )
  )
);
$res = file_get_contents($url, false, $context);

解决方案概述

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

设置网址:

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

设置开机自检的主体

$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>';
}

最新更新