Posting to linkedin from php and codeigniter

I recently got tasked with posting offline messages to twitter, i.e when a user completes an action on my application, there would be a message posted to linkedin.

I looked at the many oauth libraries about on the web for php and codeigniter and couldn’t find one that worked perfectly for my situation so i mashed a few together and ended up with this- and i learnt a few lessons on the way.

Where I got the php libraries that where built around the linkedin api, nothing was clean and coherent.. and simple so I found a twitter library and modified it to my needs- both linkedin and twitter are built around OAUTH (so is facebook) and this made it super easy to change a few urls and directories and have a working library.

The source for my derived work came from this library listed here - https://www.packtpub.com/article/user-authentication-with-codeigniter-1.7-using-twitter-oauth if you check my code you will see i edited slightly to change it for use with linkedin. If your using this library you will also need the PHP oauth Library which is listed here- http://oauth.googlecode.com/svn/code/php/

The library- save this as linked.php in your application/libraries folder- also save your “OAuth.php” in there as well

The llibrary

 
<?php
 
require_once("OAuth.php");
 
class linkedin
{
 var $consumer;
 var $token;
 var $method;
 var $http_status;
 var $last_api_call;
 var $callback;
 
	function linkedin($data)
	{
		$this->method = new OAuthSignatureMethod_HMAC_SHA1();
		$this->consumer = new OAuthConsumer($data['consumer_key'], $data['consumer_secret']);
		$this->callback = $data['callback_url'];
 
		//print_r($data);
 
 
		if(!empty($data['oauth_token']) && !empty($data['oauth_token_secret']) && !empty($data['callback_url']))
		{
			$this->token = new OAuthConsumer($data['oauth_token'],$data['oauth_token_secret']);
 
 
		}
		else
		{
			$this->token = NULL;
		}
 }
 
 function debug_info()
{
 echo("Last API Call: ".$this->last_api_call."<br />\n");
 echo("Response Code: ".$this->http_status."<br />\n");
 }
 
 function get_request_token()
{
	 $args = array();
 
	 $request = OAuthRequest::from_consumer_and_token($this->consumer,
		 $this->token, 'GET',
		  "https://api.linkedin.com/uas/oauth/requestToken", $args);
 
	$request->set_parameter("oauth_callback", $this->callback);
	$request->sign_request($this->method, $this->consumer,$this->token);
	$request = $this->http($request->to_url());
 
	 parse_str($request,$token);
 
	 $this->token = new OAuthConsumer($token['oauth_token'],$token['oauth_token_secret'],$this->callback);
 
	 return $token;
 }
 
	function get_access_token($oauth_verifier)
	{
		$args = array();
 
		$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, 'GET', "https://api.linkedin.com/uas/oauth/accessToken",$args);
		$request->set_parameter("oauth_verifier", $oauth_verifier);
		$request->sign_request($this->method, $this->consumer,$this->token);
		$request = $this->http($request->to_url());
 
		echo $request ;
 
		parse_str($request,$token);
		//echo $oauth_verifier;
 
		$this->token = new OAuthConsumer($token['oauth_token'],
		$token['oauth_token_secret'],1);
 
		return $token;
	}
 
	 function parse_request($string)
	 {
		 $args = explode("&", $string);
		 $args[] = explode("=", $args['0']);
		 $args[] = explode("=", $args['1']);
 
		 $token[$args['2']['0']] = $args['2']['1'];
		 $token[$args['3']['0']] = $args['3']['1'];
 
		 return $token;
	 }
 
	function parse_access($string)
	{
		$r = array();
 
		foreach(explode('&', $string) as $param)
		{
			$pair = explode('=', $param, 2);
			if(count($pair) != 2) continue;
			$r[urldecode($pair[0])] = urldecode($pair[1]);
		}
		return $r;
	}
 
	function get_authorize_URL($token)
	{
		if(is_array($token)) $token = $token['oauth_token'];
		return "https://api.linkedin.com/uas/oauth/authorize?oauth_token=" .
		  $token;
	}
 
	function http($url, $post_data = null)
	{
		$ch = curl_init();
 
		if(defined("CURL_CA_BUNDLE_PATH"))
		curl_setopt($ch, CURLOPT_CAINFO, CURL_CA_BUNDLE_PATH);
 
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
 
		if(isset($post_data))
		{
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		}
 
		$response = curl_exec($ch);
		$this->http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		$this->last_api_call = $url;
		curl_close($ch);
 
		return $response;
	}
 
  function share($comment, $title, $url, $imageUrl,$access_token) {
      $shareUrl = "http://api.linkedin.com/v1/people/~/shares";
 
      $xml = "<share>
              <comment>$comment</comment>
              <content>
                 <title>$title</title>
                 <submitted-url>$url</submitted-url>
                 <submitted-image-url>$imageUrl</submitted-image-url>
              </content>
              <visibility>
                 anyone
              </visibility>
            </share>";
		//echo $this->consumer;
		//echo "<br>at : ".$this->access_token."<br>";
 
 
	//echo "<b>".$access_token."</b>";
      $request = OAuthRequest::from_consumer_and_token($this->consumer, $access_token, "POST", $shareUrl);
      $request->sign_request($this->method, $this->consumer, $access_token);
      $auth_header = $request->to_header("https://api.linkedin.com");
 
	  /*
		echo $xml . "\n";
		echo $auth_header . "\n";
	*/
		//$auth_header = preg_replace("/Authorization\: OAuth\,/", "Authorization: OAuth ", $auth_header);
		//$auth_header = preg_replace('/\"\,/', '", ', $auth_header);
 
 
      $response = $this->httpRequest($shareUrl, $auth_header, "POST", $xml);
	  echo $response;
      return $response;
  }
 
 
	function httpRequest($url, $auth_header, $method, $body = NULL) {
 
		if (!$method) {
			$method = "GET";
		};
 
		//echo $url. " " .$method. " " .$body;
 
		//echo $auth_header;
 
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HEADER, 0);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_HTTPHEADER, array($auth_header)); // Set the headers.
 
		//echo $auth_header;
 
		if ($body) {
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
			curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
			curl_setopt($curl, CURLOPT_HTTPHEADER, array($auth_header, "Content-Type: text/xml;charset=utf-8"));  
 
 
		}
 
		$data = curl_exec($curl);
		echo curl_getinfo($curl, CURLINFO_HTTP_CODE);
		//if ($this->debug) {
			//echo "bla";
			echo $data . "\n";
		//}
 
		curl_close($curl);
 
		return $data; 
	}
}
?>

I have commented the code more so than giving a run through of how it works.

The codeigniter stuff :)

<?php
session_start();
 
class User extends controller {
 
 
	var $data;
 
	function user(){
 
		parent::Controller();
 
		parse_str(substr(strrchr($_SERVER['REQUEST_URI'], "?"), 1), $_GET);
		$this->load->helper('url');
		$this->load->library('session');
 
		$this->data['consumer_key'] = "";
		$this->data['consumer_secret'] = "";
		$this->data['callback_url'] = "yourcallback";
 
	}
 
	function index(){
 
 
 
 
	}
 
 
	function linkedin(){
 
 
		$this->load->library('linkedin', $this->data);
		$token = $this->linkedin->get_request_token();
 
		$_SESSION['oauth_request_token'] = $token['oauth_token'];
		$_SESSION['oauth_request_token_secret'] =   $token['oauth_token_secret'];
 
		$request_link = $this->linkedin->get_authorize_URL($token);
 
		$data['link'] = $request_link;
 
 
		header("Location: " . $request_link);
	}
 
 
	function linkedin_submit(){
 
 
 
		$this->data['oauth_token'] = $_SESSION['oauth_request_token'];
		$this->data['oauth_token_secret'] = $_SESSION['oauth_request_token_secret'];
 
		//
		//laod the library with the variables defined in the constructor
		//
		$this->load->library('linkedin', $this->data);
		//echo $_REQUEST['oauth_verifier'];
 
		$_SESSION['oauth_verifier']     =  $_REQUEST['oauth_verifier'];
 
		/* Request access tokens from linkedin */
		$tokens = $this->linkedin->get_access_token($_SESSION['oauth_verifier']);
		/*Save the access tokens.*/
		/*Normally these would be saved in a database for future use. */
		$_SESSION['oauth_access_token'] = $tokens['oauth_token'];
 
		$_SESSION['oauth_access_token_secret'] = $tokens['oauth_token_secret'];
 
 
 
		//store your user info
		//if your going to store the tokens you will need to serialise in and out of the db
		//
		// you will need to write your own models- simple storage- serialization done here in the controller
 
		$this->load->model('muser');
		$data_id = array('linked_in' => serialize($this->linkedin->token),'id' => $user_id,'oauth_secret' => $_REQUEST['oauth_verifier']);
 
		//i used this to store the link_in tokens in the db
 
		if(!$this->muser->store_id($data_id)){
 
			//error
 
		}
 
 
	}
 
	function linkedin_post(){
 
		$id = $this->input->get('id');	
 
		//
		//this is the get from db
		//
		//you will have to make your own models
		//
 
 
		$row = $this->muser->get_by_id($id);
 
		$linked_in = $row['linked_in'];
 
 
		//
		//setup the post info
		//
 
		$comment = "message";
		$title = "story title";
		$targetUrl = "http://link";
		$imgUrl = "image title";
 
		//
		//
		//load the library for linkedin with the variables defined in the constructor 
		//
 
		$this->load->library('linkedin', $this->data);
 
 
		$apiCallStatus    =   $this->linkedin->share($comment, $title, $targetUrl, $imgUrl,unserialize($linked_in));
 
	}
 
?>

View Comments

  1. I just tried using this …. everything goes well and I dont get any errors….. so I just thought of printing  $apiCallStatus it shows me a long string of numbers and alphabets …. but nothing happens on linked ….. could you guide me where am I making a mistake

  2. uncaught exception: [Exception... "prompt aborted by user"  nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)"  location: "JS frame :: resource://gre/components/nsPrompter.js :: openTabPrompt :: line 468"  data: no]
    I get this as uncaught exception

  3. it may just be a problem with serializing the access token.

  4. But I am doing everything the same as you showed

  5. I stripped the code out of the database, I would have serialized the
    tokens in and out of the db.

  6. could you please give an example of how could i achieve this without storing the token in database … I tried not using serialization at all doesnt work

  7. i’ll do a stripped down version now and post it in a minute (im posting from multiple disqus accounts)

  8. Awesome post. Thank you!

  9. Hi,

    Doesn’t work with 2.0.3, could you update the code?  Would appreciate it :)

  10. Great Work. Thanks for sharing coding. Its a nice informative post and its great resource for lots of peoples.

  11. Thanks for sharing coding language. It is very useful for me. I would like to thank you for the efforts you have made in writing this article.

  12. You have given the exact coding, which will be really useful for me. Thanks for sharing the important codings.

  13. Well written article.I appreciate your writing skills.Its great.Thanks for sharing this coding with us.You are really a nice tutor.You have done a great job by sharing this post with us.I like this post.Keep sharing with us in future too.

Leave a comment

blog comments powered by Disqus