LinkedIn is the world’s largest professional social network with over 722 million users worldwide. It allows users to connect with other professionals, share content, find jobs, network, and more. One of the key features of LinkedIn is the ability to share links to articles, websites, blog posts, and other content. This helps drive traffic, build influence, and spread ideas.
In this comprehensive guide, we will walk through the steps for programmatically sharing a link on LinkedIn using PHP. We will cover:
- Getting API access keys
- Constructing the share URL
- Customizing the share content
- Posting the link with PHP
- Handling errors and tracking shares
Whether you want to auto-share new blog posts, promote content marketing campaigns, or build custom LinkedIn automation, sharing links via the API is a powerful technique. Let’s dive in!
Prerequisites
Before we start, you will need:
- A LinkedIn user account
- A LinkedIn page, Showcase page, or Company page to share from
- Basic knowledge of PHP and cURL
- A LinkedIn app and API keys
If you don’t already have a LinkedIn app set up, follow these steps:
- Go to LinkedIn Developers and log in.
- Click on My Apps in the top menu bar.
- Click the Create App button.
- Fill in details like app name, description, logo, etc.
- Agree to the terms and click Submit.
- On the next screen, copy the Client ID and Client Secret.
This will give you the API keys we need later. The app will start off in “development mode” but can be switched to production mode later.
Construct Share URL
To programmatically share links on LinkedIn, we’ll use their standardized GET request URL with various parameters. Here is the basic structure:
https://www.linkedin.com/sharing/share-offsite/?url=[URL to share]
The main parameter is the URL you want to share, encoded properly.
Some examples:
https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fwww.example.com%2Farticle
https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fwww.example.com%2Fmysite%2Fpage.html
When someone visits this URL, it will open a LinkedIn share popup with the link pre-filled.
Customizing Share Content
We can further customize the share content with these additional parameters:
- title – Sets text for the share title
- summary – Sets text for the share description
- source – Sets the source URL to attribute
Some examples:
https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fwww.example.com%2Farticle&title=Check%20this%20out&summary=This%20article%20has%2010%20tips%20for%20getting%20more%20done&source=https://www.example.com
https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fwww.example.com%2Fmysite%2Fpage.html&title=My%20Page&summary=This%20page%20explains%20how%20to%20do%20xyz.&source=https://www.example.com/mysite
This allows customizing the headline, description, and source URL that get pre-filled when someone opens the share popup.
Sharing as a Page
So far, the sharing will be done from the member’s own LinkedIn account. To share as a Company, Showcase, or other LinkedIn Page, we need to authenticate using OAuth 2.0.
This involves:
- Redirecting the user to LinkedIn to log in and authorize the app
- LinkedIn redirecting back with an authorization code
- Exchanging the code for an access token
- Using the access token in the API request
Here is an example request to get an authorization code:
https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=[CLIENT_ID]&redirect_uri=[CALLBACK_URL]&state=1234567890&scope=w_member_social
Once we exchange the code for an access token, we can make an authenticated share request like:
https://api.linkedin.com/v2/ugcPosts
With a JSON payload containing the content to share.
We will put this together in a full PHP script next.
Posting a Link with PHP
Now let’s walk through a full PHP script to share a link on LinkedIn as a Page.
First, we’ll set up constants for our credentials and URLs:
<?php const CLIENT_ID = '1234567...'; const CLIENT_SECRET = 'ABCDEF...'; const REDIRECT_URI = 'https://example.com/callback'; const TOKEN_URL = 'https://www.linkedin.com/oauth/v2/accessToken'; const SHARE_URL = 'https://api.linkedin.com/v2/ugcPosts'; ?>
The callback URL is where users will be redirected after authenticating.
Next, we can check if we already have an access token:
<?php // Check for existing access token if (isset($_SESSION['access_token'])) { $access_token = $_SESSION['access_token']; } else { // No token, need to authenticate } ?>
If no existing token is found, we need to make the user log in and authorize.
First construct the authorization URL:
<?php $auth_url = 'https://www.linkedin.com/oauth/v2/authorization'; $auth_url .= '?response_type=code'; $auth_url .= '&client_id=' . CLIENT_ID; $auth_url .= '&redirect_uri=' . REDIRECT_URI; $auth_url .= '&state=123456789'; $auth_url .= '&scope=w_member_social'; header('Location: ' . $auth_url); ?>
Redirect the user to this URL, which will initiate the login flow.
After login, LinkedIn redirects back to our callback URL with an authorization code. We can get this code:
<?php $code = $_GET['code']; ?>
Now we need to exchange this code for an access token using cURL:
<?php $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, TOKEN_URL); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([ 'grant_type' => 'authorization_code', 'code' => $code, 'redirect_uri' => REDIRECT_URI, 'client_id' => CLIENT_ID, 'client_secret' => CLIENT_SECRET ])); $result = curl_exec($ch); $data = json_decode($result); $access_token = $data->access_token; // Store token $_SESSION['access_token'] = $access_token; ?>
This exchanges the code for an access token we can use in the API. The token is stored in the session for later use.
Now that we have an access token, we can share the link!
<?php // API headers $headers = [ 'Authorization: Bearer ' . $access_token, 'Content-Type: application/json', 'x-li-format: json' ]; // Share content $data = [ 'author' => 'urn:li:organization:12345', 'lifecycleState' => 'PUBLISHED', 'specificContent' => [ 'com.linkedin.ugc.ShareContent' => [ 'shareCommentary' => [ 'text' => 'Check out this cool article!' ], 'shareMediaCategory' => 'ARTICLE', 'media' => [ [ 'status' => 'READY', 'description' => [ 'text' => '10 Tips for Productivity' ], 'originalUrl' => 'https://www.example.com/article', 'title' => [ 'text' => '10 Productivity Tips' ] ] ] ] ], 'visibility' => [ 'com.linkedin.ugc.MemberNetworkVisibility' => 'PUBLIC' ] ]; $json = json_encode($data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, SHARE_URL); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); $result = curl_exec($ch); ?>
This makes a POST request to the UGC Posts API to share the link, including the access token in the headers. Customize the share text, URL, etc.
We also set the `author` parameter to the Page’s URN to share as that Page. The `visibility` is set to public.
With this full script, we can now programmatically share links on LinkedIn to any Page we manage!
Handling Errors
When sharing links, there are some common errors that may occur:
– 401 Unauthorized – Invalid access token
– 403 Forbidden – General authorization error
– 404 Not Found – Invalid URN or share URL
– 429 Too Many Requests – Hit rate limits
We should handle these cases gracefully in our script. For example:
<?php // ...Code to share post... $result = curl_exec($ch); if (curl_errno($ch)) { echo 'Error:' . curl_error($ch); } $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($code == 401) { // Invalid token, make user re-authenticate } else if ($code == 403) { // General auth error } else if ($code == 404) { // Invalid parameter value } else if ($code == 429) { // Too many requests } ?>
We can check for these status codes and handle appropriately.
For 429 errors, we may want to implement exponential backoff with progressively longer delays between retries.
Tracking Shares
To see analytics on shares, we can use the LinkedIn Share Statistics API.
This lets you get data like:
– Total shares
– Click-throughs
– Likes, comments, reshares
– Share demographics
– Top click sources
To query share stats, make a GET request like:
GET /v2/shares?q=ORGANIC&shareId=urn:li:share:12345
Pass the `shareId` to specify the post and `q` parameter to filter stats.
We can periodically poll this to get up-to-date metrics on shares right from the API.
This completes a full guide on programmatically sharing links on LinkedIn using PHP!
Conclusion
Sharing content on LinkedIn can be a powerful technique for increasing traction. By using their standardized APIs, we can easily automate link sharing from PHP scripts.
Some key points:
– Use pre-defined share URLs with encoded parameters to create share popups
– For sharing as Pages, authenticate with OAuth 2.0 to get access tokens
– Make an API call to the UGC Posts endpoint to programmatically share
– Handle errors properly and implement retries
– Track share analytics using the Share Statistics API
This opens up many possibilities like auto-sharing new posts, promoting content campaigns, spreading viral content, and more.
LinkedIn’s APIs provide the tools – the rest is up to your imagination. Automate away!