1

I write a code which share a post on linkedin account. My code is working fine for text post but facing issue in image post. I tried and search a lot but not find any success for now. Here is my code for image share in linkedin V2 api.

I follow this doc https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin?context=linkedin/consumer/context

/*1.Register your image to be uploaded.*/

$imageData = array (
                  'registerUploadRequest' => 
                  array (
                    'recipes' => 
                    array (
                      0 => 'urn:li:digitalmediaRecipe:feedshare-image',
                    ),
                    'owner' => 'urn:li:person:'.$data['identifier'],
                    'serviceRelationships' => 
                    array (
                      0 => 
                      array (
                        'relationshipType' => 'OWNER',
                        'identifier' => 'urn:li:userGeneratedContent',
                      ),
                    ),
                  ),
                );
                
                $headers = [
                            'Content-Type' => 'application/json',
                            'x-li-format'  => 'json',
                            'X-Restli-Protocol-Version' => '2.0.0',
                        ];
         
                
                $image_request = $adapter->apiRequest('assets?action=registerUpload', 'POST', $imagedata, $headers);
                
                $image_request = json_decode(json_encode($image_request), True);
                
/*2.Upload your image to LinkedIn.*/

                $media = $image_request['value']['asset'];
                $image_path = '/var/www/domain.com/img/laptop-green-bg.jpg';

                $postfield = array("upload-file" => $image_path );


                $headers = array();
                $headers[] = 'Authorization: Bearer '.$tokens['access_token'];// token generated above code
                $headers[] = 'X-Restli-Protocol-Version: 2.0.0';
                $headers[] = 'Content-Type: data/binary';
                $headers[] = 'Content-Length: 0';


                $ch = curl_init();
                $options = array(
                    CURLOPT_HEADER => true,
                    CURLOPT_CUSTOMREQUEST => 'POST',
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_URL => $image_request['value']['uploadMechanism']['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest']['uploadUrl'],
                    CURLOPT_HTTPHEADER => $headers,
                    CURLOPT_SSL_VERIFYPEER => false,
                    CURLOPT_FOLLOWLOCATION => true,
                    CURLOPT_POST => true,
                    CURLOPT_SAFE_UPLOAD => false,
                    CURLOPT_POSTFIELDS => $postfield
                );
                curl_setopt_array($ch, $options);
                $imgResponse = curl_exec($ch);
                if (curl_error($ch)) {
                    $error_msg = curl_error($ch);
                }
                $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);

                $assets = explode(":", $media);
                
                $assetRequest = $adapter->apiRequest('assets/'.$assets[3], 'GET');

/*3. Create the image share.*/

                $status = $this->imagePostArray($data, $media);
                
                function imagePostArray($data, $media) {

                  $newData = array (
                    'author' => 'urn:li:person:'.$data['identifier'],
                    'lifecycleState' => 'PUBLISHED',
                    'specificContent' => 
                    array (
                      'com.linkedin.ugc.ShareContent' => 
                      array (
                        'shareCommentary' => 
                        array (
                          'text' => $data['introtext'],
                        ),
                        'shareMediaCategory' => 'IMAGE',
                        'media' => 
                        array (
                          0 => 
                          array (
                            'status' => 'READY',
                            'description' => 
                            array (
                              'text' => $data['introtext'],
                            ),
                            'media' => $media,
                            'title' => 
                            array (
                              'text' => $data['introtext'],
                            ),
                          ),
                        ),
                      ),
                    ),
                    'visibility' => 
                    array (
                      'com.linkedin.ugc.MemberNetworkVisibility' => 'PUBLIC',
                    ),
                  );

                  return $newData;

            }
                
                $response = $adapter->apiRequest('ugcPosts', 'POST', $status, $headers);
                
                print_r($response);
                /*responsestdClass Object
                (
                    [id] => urn:li:share:XX4665961029465XXXX
                
                )*/
                
               print_r($imgResponse);
               
               /*HTTP/1.1 201 Created
              Date: Tue Jun 18 08:15:02 UTC 2019
              Server: Play
              Set-Cookie: lang=v=2&lang=en-us; Path=/; Domain=api.linkedin.com
              x-ambry-creation-time: Tue Jun 18 08:15:02 UTC 2019
              access-control-allow-origin: https://www.linkedin.com
              Content-Length: 0
              X-Li-Fabric: prod-lor1
              Connection: keep-alive
              X-Li-Pop: prod-esv5
              X-LI-Proto: http/1.1
              X-LI-UUID: z1rSbeU8qRUA8kkBZSsXXX==
              Set-Cookie: lidc="b=OB77:g=1398:u=7:i=1560845701:t=1560926538:s=AQG2sbwmHWudXf8tikgpzQdf4uhbXXX"
              X-LI-Route-Key: "b=OB77:g=1398:u=7:i=1560845701:t=1560926538:s=AQG2sbwmHWudXf8tikgpzQdf4uhbXXX"*/
               
                
                

But still cannot see my post in linkedin. Please help to debug or provide some solution.

Sachin
  • 397
  • 4
  • 13
  • I answered this question in another thread here: https://stackoverflow.com/questions/54836957/how-to-convert-curl-call-with-i-upload-file-into-php/58241724#58241724 – iMilan Oct 04 '19 at 18:52

2 Answers2

1

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.

KCP
  • 929
  • 9
  • 29
0

Work For Me

              $curl = curl_init(); //CURL version: 7.29, PHP version: 7.4.26

              $imageData = array (
              'registerUploadRequest' => 
              array (
                'recipes' => 
                array (
                  0 => 'urn:li:digitalmediaRecipe:feedshare-image',
                ),
                'owner' => 'urn:li:person:'.$linkedin_id,
                'serviceRelationships' => 
                array (
                  0 => 
                  array (
                    'relationshipType' => 'OWNER',
                    'identifier' => 'urn:li:userGeneratedContent',
                  ),
                ),
              ),
            );

            $image_request = json_encode($imageData);

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.linkedin.com/v2/assets?action=registerUpload',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_TIMEOUT => 300,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $image_request,
           CURLOPT_HTTPHEADER => array('content-type: application/json', "Accept: application/json",
            "Authorization: Bearer ".$access_token)
        ));

        $response = json_decode(curl_exec($curl),true);
        echo "<pre>";
        print_r($response);
br patel
  • 1
  • 1
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 24 '22 at 08:55