Do you want to share posts on LinkedIn using PHP? You may wish to build an automated system that can share your post on LinkedIn programmatically. In this article, I show you how to send a post on LinkedIn using LinkedIn API and PHP.
Sharing posts on social networks helps you to bring more traffic and audiences to your website. LinkedIn is a professional network that will give you genuine readers.
If you have a lot of posts being written then posting a link manually on LinkedIn is not a wise choice. It is always better to have an automated system that sends a post on your feed programmatically.
LinkedIn provides a Share API using which you can post a link along with a title, description, and image on your feed.
We will go through all the steps required for sharing a post on LinkedIn. These steps include
- Register an application on LinkedIn Developer Network.
- Generate an access token. We’ll build OAuth flow to grab the access token.
- Fetch your LinkedIn profile ID.
- Finally, send a post on your LinkedIn Feed.
Create LinkedIn Application
In order to start with Share API, you first need to register the application with your LinkedIn Developer account. Integrating LinkedIn APIs requires having the access token. And this access token is created using your application’s keys – client id and client secret.
While registering the application, you also need to set an authorized redirect URL. For testing purposes, I am going to use my local server URL. You should adjust this URL as per your flow.
- Go to LinkedIn Developer Network.
- Click on the ‘Create App’ button.
- Complete the setup as prompted.
- Add
http://localhost/linkedin/callback.php
in the Authorized Redirect URLs field. - Under the ‘Products’ tab, select 2 products – Sign In with LinkedIn and Share on LinkedIn.
- Copy the Client ID and Client Secret keys.
Generate an Access Token for LinkedIn Account
An access token is an identifier that is required to perform API operations on the user’s account. Sharing posts programmatically on LinkedIn requires an access token. LinkedIn verifies this access token and then performs the requested operations.
To generate an access token, you need to authorize your account. This authorization can be done via OAuth. During this process, you need to send HTTP requests to the OAuth endpoint. To send the HTTP requests and handle the response, install the Guzzle library using the Composer command.
composer require guzzlehttp/guzzle
Next, create a config.php
file and pass the credentials in the file as shown below.
<?php
define('CLIENT_ID', 'YOUR_CLIENT_ID');
define('CLIENT_SECRET', 'YOUR_CLIENT_SECRET');
define('REDIRECT_URL', 'http://localhost/linkedin/callback.php');
define('SCOPES', 'r_emailaddress,r_liteprofile,w_member_social');
Make sure to replace placeholders with actual values. Here, I set my local server URL as a REDIRECT_URL. In your case, this URL is different. To the SCOPES constant, I have passed the default permissions which are enough for our end goal.
Build an Authorization URL
It needs to build an authorization URL to fetch the access token. This URL requires a client_id, redirect_uri, and scope as additional parameters. The authorization URL takes you to the LinkedIn website where you have to complete the authentication. After completing authentication, you will redirect back to the callback URL. In this callback URL, we’ll write a code to grab the access token.
Let’s create a index.php
and add the code to generate the authorization URL as follows.
<?php
require_once 'config.php';
$url = "https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=".CLIENT_ID."&redirect_uri=".REDIRECT_URL."&scope=".SCOPES;
?>
<a href="<?php echo $url; ?>">Login with LinkedIn</a>
Exchange Authorization Code for an Access Token
As I said after completing the authorization, you will redirect back to the callback URL. When it comes back, it has the Authorization code in the get parameter. From the callback file, we’ll send a POST request to the LinkedIn API along with the required parameters including this authorization code. In return, LinkedIn API provides an access token.
callback.php
<?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_URL,
"client_id" => CLIENT_ID,
"client_secret" => CLIENT_SECRET,
],
]);
$data = json_decode($response->getBody()->getContents(), true);
$access_token = $data['access_token']; // store this token somewhere
} catch(Exception $e) {
echo $e->getMessage();
}
Upon receiving the access token, save it in a safe place. You may store it in the database. LinkedIn does not generate long-lived access tokens. The access token is valid for 60 days. You need to regenerate an access token before expiry by following the above process again. It is a kind of ugly thing but currently, programmatic refresh tokens(which are used to regenerate access tokens in the background) are available for a limited set of partners only. You may read more about this on LinkedIn documentation.
Get Your LinkedIn ID
You got the access token for your LinkedIn account. The next part is fetching your LinkedIn ID. This ID is required to share a post on your LinkedIn feed. Get this ID by sending a GET request to the LinkedIn API endpoint /v2/me.
<?php
require_once 'config.php';
require_once 'vendor/autoload.php';
use GuzzleHttp\Client;
$access_token = 'YOUR_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);
$linkedin_profile_id = $data['id']; // store this id somewhere
} catch(Exception $e) {
echo $e->getMessage();
}
Like an access token, you should also store this LinkedIn ID. You will require both the access token and LinkedIn ID in the next step.
Send Post on LinkedIn Using LinkedIn API and PHP
Now the last step is to send a post on LinkedIn. The Share API documentation explains the request format required to execute this operation. Taking a reference from it, our PHP code would be as follows:
<?php
require_once 'vendor/autoload.php';
use GuzzleHttp\Client;
$link = 'YOUR_LINK_TO_SHARE';
$access_token = 'YOUR_ACCESS_TOKEN';
$linkedin_id = 'YOUR_LINKEDIN_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 = 'YOUR_POST_TITLE';
$body->owner = 'urn:li:person:'.$linkedin_id;
$body->text->text = 'YOUR_POST_SHORT_SUMMARY';
$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 'Post is shared on LinkedIn successfully.';
} else {
echo 'Error: '. $response->getLastBody()->errors[0]->message;
}
} catch(Exception $e) {
echo $e->getMessage(). ' for link '. $link;
}
In the above code, I have added a few placeholders that should be replaced with their values. After calling the API endpoint /v2/shares, you will get a ‘201’ HTTP code. It means the post is created(shared) on LinkedIn.
Related Articles
- How to Implement Login with LinkedIn in Website with PHP
- Login with LinkedIn in Laravel Using Laravel Socialite
- How to Integrate Google Sheets API with PHP
If you liked this article, then please subscribe to our YouTube Channel for video tutorials.
how to post an image from input fields
Maybe you figured out already, I hope that it helps to others:
Our JsonBody requires “entityLocation”, “thumbnails” for post an image:
{
“content”:{
“contentEntities”: [
{
“entityLocation”: “https://www.example.com”, //Here your Website or URL related to the image
“thumbnails”: [
{
“resolvedUrl”: “https://www.example.com/image.jpg” // Here the URL to the image
}
]
}
]
…
}
You can check the docs for more info:
https://docs.microsoft.com/en-us/linkedin/marketing/integrations/community-management/shares/share-api?view=li-lms-unversioned&tabs=http#how-to-use-images-in-share
Can anyone tell me if there is a simple way to link to a page and have it ready to share on LinkedIn? Thanks
Hi,
This code shares a post on my person linkedin page, but how do I share a post on my company’s page?
Hi,
Great Artical. Very useful.
Would you please also let us know how to get user feed using API?
mine is saying not having enough permission to post.what could be the problem
Hi.
In my case i have to add sigin access on “products” tab of linkedin’s app settings page.
After that, that error gone and have no problem getting the access token.
Right. I added this info in the article.
Hello,
Can you please tell me how to add LINE Breaks in the LinkedIn API? As when I send multiple line text in my post then all the lines come up in a single line. I tried almost all solutions but nothing worked.
Please let me know how to send LINE Breaks in the API.
If you look at the documentation, it mentioned String format for this ‘text’ field. I didn’t find any possible way from their doc to share text with HTML tags.
https://docs.microsoft.com/en-us/linkedin/marketing/integrations/community-management/shares/share-api#share-text-and-mentions
Hi
How do I can publish a post for visibility anyone?
Same problem here can anyone have a solution?
Thanks for your post !!
That help me to setup quickly
Thanks , for your post, great work,
Please share the example code for Image and video share on Linkedin using php
Many many thanks.
have you code in asp.net mvc
what are the parameters of POST API when I want to post some data on linkedin through my webste?
Hello,
Thanks for the help,your code is working,but if I want to share post on company page then should i do?
help me ???
Hi,
This code shares a post on my person linkedin page, but how do I share a post on my company’s page?
Yes same problem here??
To post a link on the company page requires additional product request ‘Marketing Developer Platform’ on the LinkedIn app.
I want to write an article on sharing a post on the LinkedIn page. So, I created an app and requested for the additional product but it is still in a review and I am waiting for a LinkedIn reply.
Meanwhile, you can get an idea about it on official documentation https://docs.microsoft.com/en-us/linkedin/marketing/integrations/community-management/shares/company-pages-migration#create-a-company-share
on the step “Exchange Authorization Code for an Access Token” I always get this:
Client error: `POST https://www.linkedin.com/oauth/v2/accessToken` resulted in a `400 Bad Request` response:
{“error”:”invalid_redirect_uri”,”error_description”:”Unable to retrieve access token: appid/redirect uri/code verifier d (truncated…)
It keeps saying that’s an invalid redirect uri, but that’s the one that worked in the step before (as matter of fact, it’s the exact URI where this error is thrown), and it’s registered with the application in LinkedIn’s app config (or else the previous step wouldn’t work).
What can be wrong?