Skip to content

Instantly share code, notes, and snippets.

@mohsinrasool
Created October 2, 2015 14:14
Show Gist options
  • Save mohsinrasool/3c98fbe07d2a588f23cd to your computer and use it in GitHub Desktop.
Save mohsinrasool/3c98fbe07d2a588f23cd to your computer and use it in GitHub Desktop.
WordPress Shortcode to Fetch LinkedIn Company Profile updates
<?php
class Client {
public $domain = "https://api.linkedin.com";
/**
* Authorization and AccessToken api endpoints are special in that they live on www.linkedin.com not api.linkedin.com
*/
public $authorizationUrl = "https://www.linkedin.com/uas/oauth2/authorization";
public $accessTokenUrl = "https://www.linkedin.com/uas/oauth2/accessToken";
/**
* Curl handle
*
* @var resource
*/
protected $curl;
/**
* Authorized user's access token (provided at the end of the auhorization process)
*
* @var string
*/
protected $access_token;
/**
* API key provided by LinkedIn for your application
*
* @var string
*/
protected $api_key;
/**
* API secret provided by LinkedIn for your application
*
* @var string
*/
protected $api_secret;
public function __construct($api_key, $api_secret, $curl = null) {
$this->setApiCredentials($api_key, $api_secret);
$this->setCurl($curl);
}
/**
* Performs a request on a specified URI using an access token
*
* @param string $resource The relative URI for the resource requested (e.g. "/v1/people/~:(firstName,lastName)")
* @param array $payload
* @param string $method
* @param array $type Headers : multipart/form, application/json, application/xml
* @return array
*/
public function fetch($resource, array $payload = array(), $method = 'GET', $type = array('Content-type: multipart/form-data')) {
$url = $this->domain . $resource;
$payload = array('oauth2_access_token' => $this->getAccessToken(), 'format' => 'json')
+ $payload;
return $this->_request($url, $payload, $method, $type);
}
/**
* Returns the fully qualified authorization url to redirect the client
*
* @param $redirect_uri
* @param null|string $state
* @param null|string $scope
* @return string
*/
public function getAuthorizationUrl($redirect_uri, $state = 'NOSTATE', $scope = null) {
$params = array(
'response_type' => 'code',
'client_id' => $this->getApiKey(),
'redirect_uri' => $redirect_uri,
'state' => $state,
'scope' => $scope,
);
return $this->authorizationUrl . '?' . http_build_query($params);
}
/**
* Confirms the verification code and redirect URI and produces an array containing the access token, will also set
* the access token internally if one was properly returned
*
* @param string $verification_code the code provided by LinkedIn
* @param string $redirect_uri the exact redirecturi used in the getAuthorizationUrl step
* @return array
*/
public function fetchAccessToken($verification_code, $redirect_uri) {
$params = array(
'grant_type' => 'authorization_code',
'client_id' => $this->getApiKey(),
'client_secret' => $this->getApiSecret(),
'code' => $verification_code,
'redirect_uri' => $redirect_uri,
);
$url = $this->accessTokenUrl . '?' . http_build_query($params);
$response = $this->_request($url, array(), 'GET');
$response['expires_at'] = time() + $response['expires_in'] - 3600; //Give 1 hour of fudge time for renewal
if (isset($response['access_token'])) {
$this->setAccessToken($response['access_token']);
}
return $response;
}
/**
* @param string $url full url
* @param array $payload Payload values to passed in through GET or POST parameters
* @param string $method HTTP method for request (GET, PUT, POST, ...)
* @param array $type Headers : multipart/form, application/json, application/xml
* @return array JSON-decoded response
* @throws Exception
*/
protected function _request($url, array $payload = array(), $method = 'GET', $type = array('Content-type: multipart/form-data')) {
$ch = $this->getCurl();
if(!empty($payload['oauth2_access_token'])){
$url = $url.'?oauth2_access_token='.$payload['oauth2_access_token'];
}
if (!empty($payload) && $method == 'GET') {
$url .= "&" . http_build_query($payload);
}
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
));
curl_setopt($ch, CURLOPT_VERBOSE, true);
switch (strtoupper($method)) {
case 'POST':
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $type);
if (!empty($payload) && stripos($type[0], "multipart/form-data")) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
}
else if (!empty($payload) && stripos($type[0], "application/xml")) {
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload['message']);
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
array(
$type[0],
'Content-length: ' . strlen($payload['message'])
)
);
}
break;
case 'PUT':
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: multipart/form-data'));
if (!empty($payload))
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
break;
case 'GET':
curl_setopt($ch, CURLOPT_POST, false);
break;
default:
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
}
$body = curl_exec($ch);
$errno = curl_errno($ch);
if ($errno !== 0) {
throw new Exception(sprintf("Error connecting to LinkedIn: [%s] %s", $errno, curl_error($ch)), $errno);
}
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code >= 400) {
throw new Exception(trim(strip_tags($body)), $code);
}
$response = json_decode($body, true);
if (isset($response['error'])) {
throw new Exception(sprintf("%s: %s", $response['error'], $response['error_description']), $code);
}
return $response;
}
/**
* @param string $access_token
*/
public function setAccessToken($access_token)
{
$this->access_token = $access_token;
}
/**
* @return string
*/
public function getAccessToken()
{
return $this->access_token;
}
/**
* @param string $api_key
* @param string $api_secret
*/
public function setApiCredentials($api_key, $api_secret)
{
$this->api_key = $api_key;
$this->api_secret = $api_secret;
}
/**
* @return string
*/
public function getApiKey()
{
return $this->api_key;
}
/**
* @return string
*/
public function getApiSecret()
{
return $this->api_secret;
}
/**
* @param resource $curl
*/
public function setCurl($curl) {
$this->curl = $curl;
}
/**
* @return resource
*/
public function getCurl() {
if (!is_resource($this->curl)) {
$this->curl = curl_init();
curl_setopt_array($this->curl, array(
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_MAXREDIRS => 1,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 30,
));
}
return $this->curl;
}
}
?>
<?php
require_once 'Client.php';
session_name('linkedin2');
session_start();
$redirect_uri = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'];
$api_key = "7757dp5yn0wa2d";
$api_secret = "xvR4H07qzUbpcsgv";
$client = new Client($api_key, $api_secret);
if (isset($_GET['logout'])) {
unset($_SESSION['creds']);
echo "<h1>Reset Session</h1>";
} elseif (isset($_GET['error'])) {
echo "<h1>ERROR</h1> <p>{$_GET['error_description']}</p>";
} elseif (isset($_GET['code']) && !isset($_SESSION['creds'])) {
$access_token = $client->fetchAccessToken($_GET['code'], $redirect_uri);
$_SESSION['creds'] = $access_token;
} elseif (!isset($_SESSION['creds'])) {
$url = $client->getAuthorizationUrl($redirect_uri);
echo "Redirect to... <a href='$url'>$url</a>";
}
if (isset($_SESSION['creds'])) {
echo 'Access Token is :'.$_SESSION['creds']['access_token'];
// $client->setAccessToken($_SESSION['creds']['access_token']);
/*
$response = $client->fetch('/v1/people/~:(firstName,lastName)');
echo "<pre>";
var_export($response);
echo "</pre>";
*/
// $response = $client->fetch('/v1/companies/2638112/updates');
//echo "<pre>";
//echo json_encode($response);
//echo "</pre>";
}
<?php
/**
* @author: Mohsin Rasool
* @version: 0.1
*/
/**
* WordPress Short to Fetch LinkedIn Company Profile updates
* Usage:
* 1. Create Application on LinkedIn
* 2. Use Secret and API key of created application in demo.php
* 3. Add redirect URL in LinkedIn Application
* 4. Generate Access Token by visiting demo.php
* 5. Use the same Application credentials and access token in shortcode [linkedin_company_posts]
*
*/
add_shortcode( 'linkedin_company_posts','linkedin_company_posts' );
function linkedin_company_posts( $atts ) {
// Check for transient. If none, then execute WP_Query
if ( false === ( $linkedin_cache = get_transient( 'linkedin_cache' ) ) ) {
$atts = shortcode_atts( array(
'access_token' => 'AQXsWDCI8pE-nVqGUey4t3CUOcg61leBw4_FqrIe0TcXLh6cqZ7tQXs-veYA-ACPWdH1DmgvCKIYirPs5tJMHCy6-ZzJq5pykAC05ibm5_wd7riTPNL7mkhsaB8T6EuB4HegNAe6jkfhY_HKF4rJ-4fufD-fRGCiReL6mC6rI4VkHCwsQkc',
'company_id' => '2279452',
'count' => 2,
'api_key' => '77j6a4bmr47dmp',
'api_secret'=>'dCEwv3DgrNbVowjf'
), $atts );
extract($atts);
$redirect_uri = 'http://' . $_SERVER['SERVER_NAME'] .'/oauth/linkedin/demo.php';
if(empty($api_key) || empty($api_secret)) {
return 'LinkedIn Error: api_key or api_secret is missing';
}
include_once 'includes/linkedin.php';
$client = new LinkedInClient($api_key, $api_secret);
if(empty($access_token)) {
$url = $client->getAuthorizationUrl($redirect_uri);
return 'LinkedIn Error: access_token is missing. Please <a href="'.$url.'">click here</a> to generate one.';
}
$client->setAccessToken($access_token);
// Company ID is visible in the URL of "Comment" on any post of the company
if(empty($company_id))
return 'LinkedIn Error: company_id is missing';
try {
$posts = $client->fetch('/v1/companies/'.$company_id.'/updates');
}
catch(Exception $e) {
$url = $client->getAuthorizationUrl($redirect_uri);
return $e->getMessage().'LinkedIn Error: access_token is missing. Please <a href="'.$url.'">click here</a> to generate one.';
}
ob_start();
//var_dump($posts);
if( count($posts['values']) > 0 ) {
?>
<ul class="linkedin_posts">
<?php
$i =0 ;
foreach($posts['values'] as $post) {
if($i++ >= $count)
break;
//var_dump($post['updateContent']['companyStatusUpdate']['share']);
//break;
if(!empty($post['updateContent']['companyStatusUpdate']['share'])) {
$content = $post['updateContent']['companyStatusUpdate']['share']['content'];
$share = $post['updateContent']['companyStatusUpdate']['share'];
?>
<li>
<div class="comment"><?=$share['comment']?></div>
<?php
// if a post is shared
if( substr($content['submittedUrl'],-4,1) != '.' && substr($content['submittedUrl'],-5,1) != '.' && !empty($content['submittedUrl']) ) {
?>
<div class="shared_post">
<?php
if(!empty($content['thumbnailUrl']) && !empty($content['description'])) {
echo '<img src="'.$content['thumbnailUrl'].'" />';
}
//<div class="desc"><?=$content['description']</div>
?>
<h3><a href="<?=$content['shortenedUrl']?>" target="_blank"><?=$content['title']?></a></h3>
</div>
</li>
<?php
} else { // if an image is shared.
?>
<li class="shared_image">
<?php if(!empty($content['title']) && substr($content['title'],-4,1) != '.' && substr($content['title'],-5,1) != '.') { ?>
<h3><a href="<?=$content['shortenedUrl']?>" target="_blank"><?=$content['title']?></a></h3>
<?php } ?>
<a href="<?=$content['shortenedUrl']?>" target="_blank"><img src="<?=$content['thumbnailUrl']?>" /></a>
</li>
<?php
}
}
}
?>
</ul>
<?php
}else {
?>
<div class="linkedin_posts">No posts found.</div>
<?php
}
$contents = ob_get_clean();
set_transient( 'linkedin_cache', $contents, 24 * HOUR_IN_SECONDS );
return $contents;
}
else
return $linkedin_cache;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment