如何使用REST-API v2在LinkedIn上共享?

时间:2019-04-02 12:24:04

标签: php api linkedin php-curl

我很难在linkedin上分享。我试图通过Linkedin API v2发布LinkedIn共享,并且每次发出发布请求时,都会从服务器收到请求超时(状态504)的答案。这是我的代码:

$url = https://api.linkedin.com/v2/ugcPosts?oauth2_access_token=".$row[0]['accesstoken'];
$fields = '{
    "author": "urn:li:person:XXX",
    "lifecycleState": "PUBLISHED",
    "specificContent": {
        "com.linkedin.ugc.ShareContent": {
            "shareCommentary": {
                "text": "Hello World! This is my first Share on LinkedIn!"
            },
            "shareMediaCategory": "NONE"
        }
    },
    "visibility": {
        "com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
    }
}';

$headers = array(
 'Content-Type' => 'application/json',
 'X-Restli-Protocol-Version' => '2.0.0'
 'Authorization' => 'Bearer'. $token);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_POSTFIELDS, $fields);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($curl);

And here is the error message :
{
  "message": "Request timed out",
  "status": 504
}

2 个答案:

答案 0 :(得分:1)

尝试以下代码:

$url = "https://api.linkedin.com/v2/ugcPosts";

$headers = array('Content-Type: application/json','X-Restli-Protocol-Version: 2.0.0','x-li-format: json','Authorization: Bearer '.$token);

$fields = '{
    "author": "urn:li:person:*Person URN ID*",
    "lifecycleState": "PUBLISHED",
    "specificContent": {
        "com.linkedin.ugc.ShareContent": {
            "shareCommentary": {
                "text": "Hello World! This is my first Share on LinkedIn!"
            },
            "shareMediaCategory": "NONE"
        }
    },
    "visibility": {
        "com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
    }
}';


$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $fields);
$httpCode = curl_getinfo($curl , CURLINFO_HTTP_CODE); // this results 0 every time
$response = curl_exec($curl);

if ($response === false) 
    $response = curl_error($curl);

echo stripslashes($response);

curl_close($curl);
  1. 正确的API调用URL是-https://api.linkedin.com/v2/ugcPosts(您不必在URL中包含?oauth2_access_token=

  2. 由于某些原因,您定义的标头数组的格式引发错误。所以我修改了它。

  3. 人的URN ID 必须替换为必须由另一个API调用生成的用户的URN ID-有关如何操作的更多详细信息,请参见URN ID API实现这一目标。

答案 1 :(得分:0)

问题已解决

在URL和标头中添加了access_token。 现在代码正在运行。除此之外,一切都保持不变。

$url      = "https://api.linkedin.com/v2/ugcPosts?oauth2_access_token=".$this->accesstoken;

$headers = array('Content-Type:application/json','X-Restli-Protocol-Version:2.0.0','x-li-format: json','Authorization:    Bearer'.$this->accesstoken);