通过php为linkedin API v2创建图像共享 [英] Create a image share for linkedin api v2 by php

查看:91
本文介绍了通过php为linkedin API v2创建图像共享的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我遵循此文档 https://docs.microsoft.com/zh-CN/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中看到我的帖子.请帮助调试或提供一些解决方案.

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

推荐答案

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

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

此后,我们需要解码json响应,以供上传请求中使用的上传图像,如下所示:

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());

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

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

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

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

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

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

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.

这篇关于通过php为linkedin API v2创建图像共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆