Create a image share for linkedin api v2 by php

泪湿孤枕 提交于 2019-12-23 03:29:14

问题


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://docs.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.


回答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.



来源:https://stackoverflow.com/questions/56649688/create-a-image-share-for-linkedin-api-v2-by-php

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