PHP Developer
PHP Developer

Reputation: 107

How to Post on Linkedin Company page via Linkedin API v2 in PHP

I created a personal account on LinkedIn and later i created a company page with the same personal ID. What i am trying to achieve is. I want to create auto scheduler in php so that i can post some content on the company page.

I have created the app in LinkedIn developers section and also approved it. I shows that the app has below permission

r_emailaddress
r_basicprofile
w_member_social
w_organization_social
rw_organization_admin

I have created an Oauth for linkedin for which i get the access token, after getting the access token i get my linkedin ID then then i try to post content on linkedin via API.

When i make the post request it posts on the personal profile and not on the company page that it manages.

Below is my Config File

<?php
        define('CLIENT_ID', 'ID_HERE');
        define('CLIENT_SECRET', 'SECRET_HERE');
        define('REDIRECT_URI', 'call_back_url_here');
        define('SCOPES', 'r_emailaddress,r_basicprofile,w_member_social,w_organization_social,rw_organization_admin');
?>

I'm using below code as my index

<?php
        require_once 'config.php';
        $state = substr(str_shuffle("0123456789abcHGFRlki"), 0, 10);
        $url = "https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=".CLIENT_ID."&redirect_uri=".REDIRECT_URI."&scope=".SCOPES."&state=".$state;
?>

<a href="<?php echo $url; ?>">Login with LinkedIn</a>

Below is my callback.php file

<?php
require_once 'config.php';
require_once '../../../vendor/autoload.php';
use GuzzleHttp\Client;

try {
    $client = new Client(['base_uri' => 'https://www.linkedin.com']);
    $response = $client->request('POST', '/oauth/v2/accessToken', [
        'form_params' => [
                "grant_type" => "authorization_code",
                "code" => $_GET['code'],
                "redirect_uri" => REDIRECT_URI,
                "client_id" => CLIENT_ID,
                "client_secret" => CLIENT_SECRET,
        ],
    ]);
    $data = json_decode($response->getBody()->getContents(), true);
    $access_token = $data['access_token']; // store this token somewhere
    echo $access_token;
} catch(Exception $e) {
    echo $e->getMessage();
}

?>

Then i try to get linkedin ID using below request

<?php
require_once 'config.php';
require_once '../../../vendor/autoload.php';
use GuzzleHttp\Client;

$access_token = '';
try {
    $client = new Client(['base_uri' => 'https://api.linkedin.com']);
    $response = $client->request('GET', '/v2/me', [
        'headers' => [
            "Authorization" => "Bearer " . $access_token,
        ],
    ]);
    $data = json_decode($response->getBody()->getContents(), true);
    echo $linkedin_profile_id = $data['id']; // store this id somewhere
} catch(Exception $e) {
    echo $e->getMessage();
}
?>

And i finally use the below page to post the content on linkedin

<?php
require_once '../../../vendor/autoload.php';
use GuzzleHttp\Client;

$link = 'https://www.demo-url.com';
$access_token = '';
// $linkedin_id = 'ubcwiQjr8'; //please note this is demo linkedin ID, but i get some similar ID when i trigger above file
$linkedin_id = '67900000'; //please note this is demo company ID
$body = new \stdClass();
$body->content = new \stdClass();
$body->content->contentEntities[0] = new \stdClass();
$body->text = new \stdClass();
$body->content->contentEntities[0]->thumbnails[0] = new \stdClass();
$body->content->contentEntities[0]->entityLocation = $link;
// $body->content->contentEntities[0]->thumbnails[0]->resolvedUrl = "THUMBNAIL_URL_TO_POST";
$body->content->title = 'Demo title';
$body->owner = 'urn:li:person:'.$linkedin_id;
$body->text->text = 'Somse Dsdfgjjijekdjkjdmo tditle summar1y';
$body_json = json_encode($body, true);

try {
    $client = new Client(['base_uri' => 'https://api.linkedin.com']);
    $response = $client->request('POST', '/v2/shares', [
        'headers' => [
            "Authorization" => "Bearer " . $access_token,
            "Content-Type"  => "application/json",
            "x-li-format"   => "json"
        ],
        'body' => $body_json,
    ]);

    if ($response->getStatusCode() !== 201) {
        echo 'Error: '. $response->getLastBody()->errors[0]->message;
    }

    echo 'Post is shared on LinkedIn successfully';
} catch(Exception $e) {
    echo $e->getMessage(). ' for link '. $link;
}

?>

The code works perfect when i want to post on the personal profile, but the code does not work for posting on the page that it is admin. I scratched my head and did everything i could i tried to use $body->owner = 'urn:li:organization:'.$linkedin_id; and $body->owner = 'urn:li:company:'.$linkedin_id; but no luck.

Could anyone let me know how should i post on the company page? I stucked here from 2 days, any help / source would be appreciated.

I used this tutorial to refer: https://artisansweb.net/share-post-on-linkedin-using-linkedin-api-and-php/

The error that i get is Client error:POST https://api.linkedin.com/v2/sharesresulted in a400 Bad Requestresponse: {"message":"com.linkedin.restli.client.RestLiResponseException: Response status 400, serviceErrorMessage: com.linkedin.p (truncated...) for link <some_url>

Below is the JSON code that i'm sending to linkedin API call

{
"content": {
  "contentEntities": [
    {
      "entityLocation": "https://www.some-demo-url.com/cyber-security/how-to-keep-my-phone-and-laptop-safe",
      "thumbnails": [
        {}
      ]
    }
  ],
  "title": "Demo Title 1"
},
"owner": "urn:li:organization:739472893749", //organization id
"subject": "Some Subject",
"text": {
  "text": "In the last article, we discussed in detail about passwords and related concepts. Today, we want to take care of the devices that you use to access the internet 1"
}

}

Upvotes: 4

Views: 3646

Answers (1)

Frederik van Lierde
Frederik van Lierde

Reputation: 66

To post on a Business/Showcase page, the author ID you use is probably wrong, (you should not use your urn:li:person ID, even you approved the access with that ID)

In your case, you use urn:li:person:'.$linkedin_id

Personal Account: person Business Page: organization Showcase Page: organizationBrand

To get the ID and Type of your page, you can call the https://api.linkedin.com/v2/organizationalEntityAcls endpoint.

Or you can get them online https://frederik.today/codehelper/tools/linkedin/page-access-control

Upvotes: 0

Related Questions