How to Text Share on LinkedIn using API in PHP

by Vincy. Last modified on May 16th, 2021.

Previously, we have seen how to sign in with LinkedIn. This is the next step that follows after signing in to post a text and share on LinkedIn.

This will be helpful if you want to allow your PHP website to share content with social network LinkedIn programmatically using API.

LinkedIn provides developers console to create and manage applications to access its API. It provides many APIs and also specialized services accordingly.

It provides good documentation for using the API. It is so easy to prepare the required API params and handle responses if you follow the API documentation.

Accessing LinkedIn API for sharing content is a two-step process. The first one is the authentication for a person or organization, then the next is to share on LinkedIn.

This article will describe with example how to use LinkedIn API in PHP and share on LinkedIn.

About LinkedIn API used to share content

Among the LinkedIn APIs, this example code uses two of them during the 2-step content sharing process.

At the end of the first step that authenticates the person, it uses the Profile API to get the LinkedIn member profile id.

Then it uses the UGC (User Generated Content) API to post the text and share on LinkedIn.

LinkedIn API allows to post media and URL also. This example PHP script sets params for creating only the text share on LinkedIn.

About this example

Share on LinkedIn to reach millions of people and make your content viral. We have seen already how to post photos or videos to Facebook using PHP SDK.

This example script will help to achieve this using PHP programming with simple understandable steps.

It includes minimal code and a custom PHP class to prepare API requests and handle responses. It decodes the LinkedIn API response and acknowledges and redirects users based on it.

The config file defines PHP constants to set the LinkedIn API app keys and tokens. These are the params used to authorize the requests initiated.

It uses the GuzzleHTTP to send the HTTPS request to the LinkedIn API. Run the below composer command to install this library into this example code.

composer require guzzlehttp/guzzle

The following file structure shows the simplicity of the implementation.

Text Share on LinkedIn Files

Steps to create text share on LinkedIn

This section is an important part of this article which describes the step-by-step process of creating a text share on LinkedIn.

  1. Create LinkedIn API application
  2. Generate and Configure API keys
  3. Retrieve authorization code
  4. Exchange authorization code for getting access token
  5. Get LinkedIn profile id
  6. Post text share on LinkedIn

Create LinkedIn API application

LinkedIn developer console allows creating apps to access the API services. Just sign in to the developer console and click on the “Create App” button.

Create Linkedin App

By clicking the “Create app”, it will show a form to enter some basic details. It will allow set permission and the callback URL.

There are permission types to be set based on the access required. This example set w_member_social permission on creating the app.

The callback URL is the application endpoint. It will be called from LinkedIn once the person approves the App to access the LinkedIn profile.

Generate and Configure API keys

After submitting the details, the LinkedIn developer dashboard will show the app keys. Copy the client id and the secret key and configure them in the application config.

This is a usual step of generating keys on working with third-party APIs. Previously, we have seen how to generate keys for the Google Recaptcha.

The following code is to set API keys with the PHP constants. It also defines the application root, callback URL and scope.

Common/config.php

<?php
namespace Phppot;

class Config
{

    const WEB_ROOT = "https://yourdomain/share-text-on-linkedin";

    // Linkedin API configuration
    const CLIENT_ID = '';

    const CLIENT_SECRET = '';

    const CALLBACK_URL = Config::WEB_ROOT . '/linkedin_callback.php';
    
    const SCOPE = 'w_member_social';
}

Retrieve authorization code

After getting the API keys, this step uses them to get the authorization code. This code is for exchanging it to get an access token in the next step.

The first step is to redirect users to the LinkedIn authorization page to approve the app.

This code ensures that the authorization is done by checking the PHP session index for the access token and the profile id. If not empty, then the redirect will happen for the first time only.

This is the landing page that shows the form to post text share on LinkedIn.

index.php

<?php
namespace Phppot;

require_once __DIR__ . '/lib/LinkedinService.php';
$linkedinService = new LinkedinService();

session_start();
if (! empty($_SESSION["access_token"]) && ! empty($_SESSION["linkedin_id"])) {
    $accessToken = $_SESSION["access_token"];
    $linkedinProfileId = $_SESSION["linkedin_id"];
} else {
    $redirectUrl = $linkedinService->getOauthURL();
    header("Location: " . $redirectUrl);
    exit();
}
session_write_close();

if (! empty($_POST["text"])) {
    $output = $linkedinService->sharePost($accessToken, $linkedinProfileId);
}

?>
<html>
<head>
<title>Home</title>
<link rel="stylesheet" href="assets/style.css">
</head>
<body>
	<div class="phppot-container">
		<h1>Create Text Share on Linkedin</h1>
		<div class="post-form-container">
			<form name="frm-text-share" method="post" action="">
				<div>
					<textarea name="post" class="txt-post" cols="40" rows="8" required></textarea>
				</div>
				<div class="text-right">
					<input type="submit" class="btn-submit" value="Share Post" />
				</div>
			</form>
		</div>
	</div>
	<?php
if (! empty($output["type"])) {
    ?>
	<div class="<?php echo $output["type"]; ?>"><?php echo $output["message"]; ?></div>
	<?php
}
?>
</body>
</html>

Exchange authorization code for getting access token

After approving the app, LinkedIn redirects users to the callback URL as configured.

The below code shows the callback PHP endpoint. It requests the access token by sending the authorization code got in the last step.

The getAccessToken() method defined in the LinkedinService class prepares the request params to get the access token.

It also passes the grant_typeclient_idsecret_keyredirect_uri with the request params. It sets the header and content_type as instructed in the API documentation.

It uses OAuth 2.0 for the authorization and authentication process.

linkedin_callback.php

<?php
namespace Phppot;

require_once './lib/LinkedinService.php';
$linkedinService = new LinkedinService();

session_start();
if (! empty($_GET["code"])) {
    $response = $linkedinService->getAccessToken($_GET["code"]);
    if (! empty($response) && $response["type"] == "success") {
        $_SESSION["access_token"] = $response["access_token"];
        $response = $linkedinService->getProfileData($response["access_token"]);
        if (! empty($response) && $response["type"] == "success") {
            $_SESSION["linkedin_id"] = $response["linkedin_profile_id"];
            header("Location: index.php");
            exit();
        } else {
            $message = $response["message"];
        }
    } else {
        $message = $response["message"];
    }
}
session_write_close();
?>
<?php
if (! empty($message)) {
    ?>
<HTML>
<head>
<title>Problem in getting LinkedIn API access token</title>
<link rel="stylesheet" href="assets/style.css">
</head>
<body>
	<div class="phppot-container">
		<div class="error">
            <?php echo $message; ?> <a href="index.php">Try again</a>.
		</div>
	</div>
</body>
</HTML>
<?php
}
?>

Get LinkedIn profile id

For posting a text share on LinkedIn, we got one key parameter from the API. The other one is the LinkedIn profile Id to set the author of the text share.

In this step, it invokes the API endpoint to get the profile data by sending the access token.

In a previous example, we access this endpoint to get the member profile after signing with LinkedIn via API.

We have seen many examples for implementing OAuth login with Twitter, Facebook, Google. If you are looking for the Twitter OAuth login code, the linked tutorial has the code.

Post text share on LinkedIn

Thus, we have retrieved the required parameters for posting a text share on LinkedIn.

The sharePost() function of the LinkedinService class sets these parameters to send the POST request to the API.

It builds the request body and the header params for invoking the request.

It sets the author, specificContent, lifecycleState and visibility with the request body. The LinkedIn profile id is set with the author. The form post content is set with the attribute specificContent.

The lifecycleState and visibility are with the values PUBLISHED and  PUBLIC respectively.

The API documentation insists on how to set the header param. The sharePost() function prepares it by setting access token and X-Restli-Protocol-Version : 2.0.0

lib/LinkedinService.php


 <?php
namespace Phppot;

use GuzzleHttp\Client;

class LinkedinService
{

    private $clientId;

    private $clientSecret;

    private $callbackURL;

    private $scope;

    public function __construct()
    {
        require_once __DIR__ . '/../Common/Config.php';
        $this->clientId = Config::CLIENT_ID;
        $this->clientSecret = Config::CLIENT_SECRET;
        $this->callbackURL = Config::CALLBACK_URL;
        $this->scope = Config::SCOPE;
    }

    public function getOauthURL()
    {
        $authUrl = "https://www.linkedin.com/oauth/v2/authorization";
        $redirectUrl = $authUrl . "?response_type=code&client_id=" . $this->clientId . "&redirect_uri=" . $this->callbackURL . "&scope=" . $this->scope;

        return $redirectUrl;
    }

    public function getAccessToken($code)
    {
        require_once 'vendor/autoload.php';

        $params = array (
            'form_params' => array(
                "grant_type" => "authorization_code",
                "code" => $code,
                "redirect_uri" => $this->callbackURL,
                "client_id" => $this->clientId,
                "client_secret" => $this->clientSecret
            ),
            'headers' => array(
                "Content-Type" => "application/x-www-form-urlencoded"
            )
        );

        try {
            $client = new Client([
                'base_uri' => 'https://www.linkedin.com'
            ]);
            $response = $client->request('POST', '/oauth/v2/accessToken', $params);
            $data = json_decode($response->getBody()->getContents(), true);
            $output = array(
                "type" => "success",
                "access_token" => $data['access_token']
            );
        } catch (Exception $e) {
            $output = array(
                "type" => "error",
                "message" => $e->getMessage()
            );
        }
        return $output;
    }

    public function getProfileData($accessToken)
    {
        require_once 'vendor/autoload.php';
        
        $params = array(
            'headers' => array(
                "Authorization" => "Bearer " . $accessToken
            )
        );
        
        try {
            $client = new Client([
                'base_uri' => 'https://api.linkedin.com'
            ]);
            $response = $client->request('GET', '/v2/me', $params);
            $data = json_decode($response->getBody()->getContents(), true);
            $output = array(
                "type" => "success",
                "linkedin_profile_id" => $data['id']
            );
        } catch (Exception $e) {
            $output = array(
                "type" => "error",
                "message" => $e->getMessage()
            );
        }

        return $output;
    }

    public function sharePost($accessToken, $linkedinProfileId)
    {
        require_once 'vendor/autoload.php';

        $requestBody = '{
            "author": "urn:li:person:' . $linkedinProfileId . '",
            "lifecycleState": "PUBLISHED",
            "specificContent": {
                "com.linkedin.ugc.ShareContent": {
                    "shareCommentary": {
                        "text": "' . $_POST["text"] . ' "
                    },
                    "shareMediaCategory": "NONE"
                }
            },
            "visibility": {
                "com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
            }
        }';
        
        $params = array(
            'headers' => array(
                "Authorization" => "Bearer " . $accessToken,
                "Content-Type" => "application/json",
                "x-li-format" => "json",
                "X-Restli-Protocol-Version" => '2.0.0'
            ),
            'body' => $requestBody
        );

        try {
            $client = new Client([
                'base_uri' => 'https://api.linkedin.com'
            ]);
            $response = $client->request('POST', '/v2/ugcPosts', $params);

            if ($response->getStatusCode() !== 201) {
                $output = array(
                    "type" => "error",
                    "message" => $response->getLastBody()->errors[0]->message
                );
            } else {
                $output = array(
                    "type" => "success",
                    "message" => 'Post is shared on LinkedIn successfully'
                );
            }
        } catch (Exception $e) {
            $output = array(
                "type" => "error",
                "message" => $e->getMessage()
            );
        }

        return $output;
    }
}

Output – Form UI to create text share on LinkedIn

This output screenshot shows the simple form that collects text content from users. By clicking the “Share Post” button, the form posts the content in the text area to the PHP.

If PHP found the access token and the LinkedIn profile id not empty then it fires the API request to share on LinkedIn.

Form Posts Text Share on LinkedIn

Conclusion

Thus, we have implemented how to create text share on LinkedIn. It has also helped to recollect the authorization and member authentication step before sharing the content.

We have seen many OAuth login examples via API. You may also find the code Google OAuth login and Facebook open authentication with the linked articles.

I believe that this example code will make you clear to understand how the share on LinkedIn is working via API.

Download

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top