Create a image share for linkedin api v2 by php

廉价感情. 提交于 2019-12-06 20:33:26

I've solved posting using Guzzle library of php. It's simple and straight forward. First we need to upload the image using following code:

$linkedInClient = new GuzzleHttp\Client(['base_uri' => 'https://api.linkedin.com']);

$response = $linkedInClient->post(
        '/media/upload', [
            'headers' => [
                'Accept'                => 'application/json',
                'Authorization'         => 'Bearer {accessToken}',
            ],
            'multipart' => [
                [
                    'name'     => 'fileupload',
                    'contents' => fopen('image-path', 'r'),
                ],
            ],
        ]
    );

After that we need to decode the json response the uploaded image to use in the post request as follow:

$contents = json_decode($response->getBody()->getContents());

Now, prepare the data for linkedin post:

$data = array (
        'author' => 'author-id',
        'lifecycleState' => 'PUBLISHED',
        'specificContent' => 
        array (
            'com.linkedin.ugc.ShareContent' => 
            array (
                'media' => 
                array (
                  0 => 
                  array (
                    'media' => $contents->location,
                    'status' => 'READY'
                  ),
                ),
              'shareCommentary' => 
                    array (
                    'attributes' => [],
                    'text' => 'Some Comments',
                    ),
              'shareMediaCategory' => 'IMAGE',
            ),
          ),
        'visibility' => 
        array (
          'com.linkedin.ugc.MemberNetworkVisibility' => 'PUBLIC',
        ),
      );

Next, we can use this data to post in linkedin as below:

$linkedInClient->post("/ugcPosts", $data);

I hope this helps. We can see the post in the linkedin. However, in my case the post will be visible but the image only gets displayed after some time of upload. But you can see the image on popup after clicking the blank image block. Thanks.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!