通过php为linkedin API v2创建图像共享

时间:2019-06-18 12:55:57

标签: php curl linkedin-api

我写了一个共享代码的代码,该代码共享一个linkedin帐户。我的代码在文本发布中正常工作,但在图像发布中遇到问题。我尝试并搜索了很多,但暂时没有找到任何成功。这是我在Linkedin V2 api中用于图像共享的代码。

我遵循此文档 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"*/
               
                
                

但仍然无法在linkedin中看到我的帖子。请帮助调试或提供一些解决方案。

1 个答案:

答案 0 :(得分:1)

我已经解决了使用Guzzle php库发布的问题。简单而直接。 首先,我们需要使用以下代码上传图片:

$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'),
                ],
            ],
        ]
    );

之后,我们需要对上传的图片进行解码,以对json响应进行解码,如下所示:

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

现在,为linkedin发布准备数据:

$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',
        ),
      );

接下来,我们可以使用以下数据在linkedin中发布信息:

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

我希望这会有所帮助。我们可以在linkedin中看到该帖子。但是,就我而言,该帖子将可见,但仅在上传一段时间后才会显示该图片。但是单击空白图像块后,您可以在弹出窗口中看到图像。 谢谢。