Tuesday, January 17, 2017

How to silently or offline post content to user wall Linkedin[Solved] ?

Hey Guys,

I had lot of research for silent post into LinkedIn user wall and company page , finally I have integrated as custome the solution and and get long live access token of user/page from Linked to share their user wall/page wall.

Below are the step to post LinkedIn

Step1 -> Login to LinkedIn developer account create app
Step 2 -> Download LinkedIn API 


#######################LinkedIn.OAuth2.class.php#################
<?php

require_once('OAuth2.class.php');

class LinkedInOAuth2 extends OAuth2 {

public function __construct($access_token=''){
$this->access_token_url = "https://www.linkedin.com/uas/oauth2/accessToken";
$this->authorize_url = "https://www.linkedin.com/uas/oauth2/authorization";
parent::__construct($access_token);
$this->access_token_name='oauth2_access_token';
}

public function getAuthorizeUrl($client_id,$redirect_url,$scope=''){
$additional_args = array();
if($scope!=''){
if(is_array($scope)){
$additional_args['scope']=implode(" ",$scope);
$additional_args['scope'] = $additional_args['scope'];
}else{
$additional_args['scope'] = $scope;
}
}
$additional_args['state'] = md5(time());
return parent::getAuthorizeUrl($client_id,$redirect_url,$additional_args);
}

public function getAccessToken($client_id="", $secret="", $redirect_url="", $code = ""){
$result = parent::getAccessToken($client_id, $secret, $redirect_url, $code);
$result = json_decode($result,true);
if(isset($result['error'])){
$this->error = $result['error'].' '.$result['error_description'];
return false;
}else{
$this->access_token = $result['access_token'];
return $result;
}
}

public function getProfile(){
$params=array();
$fields = array(
'current-status',
'id',
'picture-url',
'first-name',
'last-name',    
'public-profile-url',
'num-connections',
);
$request = join(',',$fields);
$params['url'] = "https://api.linkedin.com/v1/people/~:({$request})";
$params['method']='get';
$params['args']['format']='json';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getUserProfile($user_id){
$params=array();
$fields = array(
'current-status',
'id',
'picture-url',
'first-name',
'last-name',    
'public-profile-url',
'num-connections',
);
$request = join(',',$fields);
$params['url'] = "https://api.linkedin.com/v1/people/".$user_id.":({$request})";
$params['method']='get';
$params['args']['format']='json';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getConnections(){
$params=array();
$params['url'] = "https://api.linkedin.com/v1/people/~/connections";
$params['method']='get';
$params['args']['format']='json';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getGroups(){
$fields = array(
'group:(id,name)',
'membership-state',
'show-group-logo-in-profile',
'allow-messages-from-members',
'email-digest-frequency',    
'email-announcements-from-managers',
'email-for-every-new-post'
);
$request = join(',',$fields);
$params['url'] = "https://api.linkedin.com/v1/people/~/group-memberships:({$request})";
$params['method']='get';
$params['args']['format']='json';
$params['args']['count']=200;
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getGroup($group_id=""){
if(!$group_id) return false;
$fields = array(
'id',
'small-logo-url',
'large-logo-url',
'name',
'short-description',
'description',
'site-group-url',
'num-members'
);
$request = join(',',$fields);
$params['url'] = "https://api.linkedin.com/v1/groups/".$group_id.":({$request})";
$params['method']='get';
$params['args']['format']='json';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getCompanies(){
$fields = array(
'id',
'name'
);
$request = join(',',$fields);
$params['url'] = "https://api.linkedin.com/v1/people/~:(first-name,positions:(company:({$request})))";
$params['method']='get';
$params['args']['format']='json';
$params['args']['count']=100;
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getCompany($company_id=""){
if(!$company_id)return false;
$fields = array(
'id',
'name',
'website-url',
'square-logo-url',
'logo-url',
'blog-rss-url',
'description',
'num-followers'
);
$request = join(',',$fields);
$params['url'] = "https://api.linkedin.com/v1/companies/".$company_id.":({$request})";
$params['method']='get';
$params['args']['format']='json';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getAdminCompanies(){
$fields = array(
'id',
            'name'
);
$request = join(',',$fields);

$params['url'] = "https://api.linkedin.com/v1/companies:({$request})";
$params['method']='get';
$params['args']['format']='json';
$params['args']['count']=100;
$params['args']['is-company-admin']='true';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getFollowedCompanies(){
$fields = array(
'id',
'name'
);
$request = join(',',$fields);
$params['url'] = "https://api.linkedin.com/v1/people/~/following/companies:({$request})";
$params['method']='get';
$params['args']['format']='json';
$params['args']['count']=200;
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getStatuses($self = false, $start=0,$count = 20){
$params['url'] = "https://api.linkedin.com/v1/people/~/network/updates";
$params['method']='get';
$params['args']['format']='json';
if($start != 0 )$params['args']['start']=$start;
if($count != 0 )$params['args']['count']=$count;
if($self){
$params['args']['scope']='self';
}
$params['args']['type']='SHAR';
$params['args']['order']='recency';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getUserStatuses($user_id, $self = true, $start=0,$count = 20){
$params['url'] = "https://api.linkedin.com/v1/people/id=".$user_id."/network/updates";
$params['method']='get';
$params['args']['format']='json';
if($start != 0 )$params['args']['start']=$start;
if($count != 0 )$params['args']['count']=$count;
if($self){
$params['args']['scope']='self';
}
$params['args']['type']='SHAR';
$params['args']['order']='recency';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getGroupPosts($group_id, $start=0,$count = 20, $order="", $category="",$role=""){
$fields = array(
'id',
'creator:(id,first-name,last-name,picture-url,headline)',
'title',
'summary',
'likes',
'comments',
'site-group-post-url',
'creation-timestamp',
'attachment:(image-url,content-domain,content-url,title,summary)',
'relation-to-viewer'
);
$request = join(',',$fields);
if($role !=""){
$params['url'] = "https://api.linkedin.com/v1/people/~/group-memberships/".$group_id."/posts:({$request})";
}else{
$params['url'] = "https://api.linkedin.com/v1/groups/".$group_id."/posts:({$request})";
}
$params['method']='get';
$params['args']['format']='json';
if($start != 0 )$params['args']['start']=$start;
if($count != 0 )$params['args']['count']=$count;
if($order != '' )$params['args']['order']=$order;
if($category != '' )$params['args']['category']=$category;
if($role != '' )$params['args']['role']=$role;
$params['args']['ts']=time();
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getCompanyUpdates($company_id, $start=0,$count = 20){
if(!$company_id)return false;
$params['url'] = "https://api.linkedin.com/v1/companies/".$company_id."/updates";
$params['method']='get';
$params['args']['format']='json';
if($start != 0 )$params['args']['start']=$start;
if($count != 0 )$params['args']['count']=$count;
$params['args']['order']='recency';
$params['args']['ts']=time();
$params['args']['event-type']='status-update';
$params['args']['twitter-post']='false';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}
//returns as ARRAY, if chaning to object change in getGroupPostResponses
protected function getPostMeta($post_id){
$fields = array(
'id',
'site-group-post-url',
'creation-timestamp'
);  
$request = join(',',$fields);
$params['url'] = "https://api.linkedin.com/v1/posts/".$post_id.":({$request})";
$params['method']='get';
$params['args']['format']='json';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getGroupPostResponses($post_id, $start = 0){
$fields = array(
'id',
'text',
'creator:(id,first-name,last-name,picture-url)',
'creation-timestamp'
);
$post_info = $this->getPostMeta($post_id);
$request = join(',',$fields);
$params['url'] = "https://api.linkedin.com/v1/posts/".$post_id."/comments:({$request})";
$params['method']='get';
$params['args']['format']='json';
$params['args']['count']=500;
if($start != 0 )$params['args']['start']=$start;
$params['args']['order']='recency';
$content_return =  $this->makeRequest($params);
$content_return = json_decode($content_return,true);
$content_return['siteGroupPostUrl'] = isset($post_info['siteGroupPostUrl']) ? $post_info['siteGroupPostUrl'] : '';
return $content_return;
}

public function getNetworkPostResponses($update_key){
$params['url'] = "https://api.linkedin.com/v1/people/~/network/updates/key=".$update_key."/update-comments";
$params['method']='get';
$params['args']['format']='json';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function getCompanyUpdateResponses($company_id,$update_id){
$params['url'] = "https://api.linkedin.com/v1/companies/".$company_id."/updates/key=".$update_id."/update-comments";
$params['method']='get';
$params['args']['format']='json';
$params['args']['event-type']='status-update';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function shareStatus($args=array()){
$params['url'] = 'https://api.linkedin.com/v1/people/~/shares';
$params['method']='post';
$params['headers']['Content-Type']='application/json';
$params['headers']['x-li-format']='json';
$json=array();
if(isset($args['comment']))
{
$json['comment'] = $args['comment'];
}
if(isset($args['title']) || isset($args['submitted-url']) || isset($args['submitted-image-url']) || isset($args['description']) ){
$json['content']=array();
if(isset($args['title'])){
$json['content']['title'] = $args['title'];
}
if(isset($args['submitted-url'])){
$json['content']['submitted-url'] = $args['submitted-url'];
}
if(isset($args['submitted-image-url'])){
$json['content']['submitted-image-url'] = $args['submitted-image-url'];
}
if(isset($args['description'])){
$json['content']['description'] = $args['description'];
}
}
$json['visibility']['code']='anyone';

$params['args']=json_encode($json);

$result =  $this->makeRequest($params);
return json_decode($result,true);
// return: array('updateKey'=>'...','updateUrl'=>'...')
}

public function postToGroup($group_id,$title,$message,$content=array()){
$params['url'] = 'https://api.linkedin.com/v1/groups/'.$group_id.'/posts';
$params['method']='post';
$params['headers']['Content-Type']='application/json';
$params['headers']['x-li-format']='json';
$json = array('title'=>$title,'summary'=>$message);

if(is_array($content) AND count($content)>0) {
// If the content of the post is specified (e.g., a link to a website), add it here
$json['content'] = array();
if(isset($content['title'])){
$json['content']['title'] = $content['title'];
}
if(isset($content['submitted-url'])){
$json['content']['submitted-url'] = $content['submitted-url'];
}
if(isset($content['submitted-image-url'])){
$json['content']['submitted-image-url'] = $content['submitted-image-url'];
}
if(isset($content['description'])){
$json['content']['description'] = $content['description'];
}
}
$params['args']=json_encode($json);
$result =  $this->makeRequest($params);
return json_decode($result,true);
}


public function postToCompany($company_id,$message,$content=array())
{
$params['url'] = 'https://api.linkedin.com/v1/companies/'.$company_id.'/shares';
$params['method']='post';
$params['headers']['Content-Type']='application/json';
$params['headers']['x-li-format']='json';
$json = array('comment'=>$message , 'visibility'=> array('code'=>'anyone'));

if(is_array($content) AND count($content)>0) {
// If the content of the post is specified (e.g., a link to a website), add it here
$json['content'] = array();
if(isset($content['title'])){
$json['content']['title'] = $content['title'];
}
if(isset($content['submitted-url'])){
$json['content']['submitted-url'] = $content['submitted-url'];
}
if(isset($content['submitted-image-url'])){
$json['content']['submitted-image-url'] = $content['submitted-image-url'];
}
if(isset($content['description'])){
$json['content']['description'] = $content['description'];
}
}
$params['args']=json_encode($json);
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function deleteFromGroup($post_id){
$params['url'] = 'https://api.linkedin.com/v1/posts/'.$post_id;
$params['method']='delete';
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function commentToGroupPost($post_id,$response_text){
$params['url'] = 'https://api.linkedin.com/v1/posts/'.$post_id.'/comments';
$params['method']='post';
$params['headers']['Content-Type']='application/json';
$params['headers']['x-li-format']='json';
$json = array('text'=>$response_text);
$params['args']=json_encode($json);
$result =  $this->makeRequest($params);
return json_decode($result,true);
}

public function commentToNetworkPost($post_id,$response_text){
$params['url'] = 'https://api.linkedin.com/v1/people/~/network/updates/key='.$post_id.'/update-comments';
$params['method']='post';
$params['headers']['Content-Type']='application/json';
$params['headers']['x-li-format']='json';
$json = array('comment'=>$response_text);
$params['args']=json_encode($json);
$result =  $this->makeRequest($params);
return json_decode($result,true);
}


/**
* Set the access token manually
*
* @param string $token
* @throws \InvalidArgumentException
* @return \LinkedIn\LinkedIn
*/
public function setAccessToken($token)
{
$token = trim($token);
if (empty($token)) {
throw new \InvalidArgumentException('Invalid access token');
}

$this->access_token = $token;

return $this;
}
}

?>



######################LinkedIn.OAuth2.class.php#################




#######################OAuth2.class.php#########################

<?php

class OAuth2{

    protected $access_token;
    protected $access_token_url;
    protected $authorize_url;
    protected $access_token_name;
    public $error;

    function __construct($access_token=''){
        $this->access_token = $access_token;
        $this->error = "";
        $this->access_token_name='access_token';
    }

    public function getAuthorizeUrl($client_id,$redirect_url, $additional_args=array() ){
        $auth_link = $this->authorize_url.
                    "?response_type=code".
                    "&client_id=".$client_id.
                    "&redirect_uri=".urlencode($redirect_url);
        foreach($additional_args as $k=>$v){
            $auth_link.='&'.$k.'='.urlencode($v);
        }
        return $auth_link;
    }


    public function getAccessToken($client_id="", $secret="", $redirect_url="", $code = ""){
        if($code==""){
            $code = isset($_REQUEST['code'])?$_REQUEST['code']:"";
        }
        $params=array();
        $params['url'] = $this->access_token_url;
        $params['method']='post';
        $params['args']=array(  'code'=>$code,
                                'client_id'=>$client_id,
                                'redirect_uri'=>$redirect_url,
                                'client_secret'=>$secret,
                                'grant_type'=>'authorization_code');
        $result = $this->makeRequest($params);
        return $result;
    }

    protected function makeRequest($params=array()){
        $this->error = '';
        $method=isset($params['method'])?$params['method']:'get';
        $headers = isset($params['headers'])?$params['headers']:array();
        $args = isset($params['args'])?$params['args']:'';
        $url = $params['url'];

        $url.='?';
        if($this->access_token){
            $url .= $this->access_token_name.'='.$this->access_token;
        }

        if($method=='get'){
            $url.='&'.$this->preparePostFields($args);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        if($method=='post'){
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $this->preparePostFields($args));
        }elseif($method=='delete'){
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
        }elseif($method=='put'){
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
        }
        if(is_array($headers) && !empty($headers)){
            $headers_arr=array();
            foreach($headers as $k=>$v){
                $headers_arr[]=$k.': '.$v;
            }
            curl_setopt($ch,CURLOPT_HTTPHEADER,$headers_arr);
        }
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    protected function preparePostFields($array) {
        if(is_array($array)){
            $params = array();
            foreach ($array as $key => $value) {
                $params[] = $key . '=' . urlencode($value);
            }
            return implode('&', $params);
        }else{
            return $array;
        }
    }

}

?>
######################OAuth2.class.php#########################

Step 3-> create a LinkedInconfig.php

#################Start Paste into config file############################
define("LINKEDIN_API_KEY", "XXXXXXX");
define("LINKEDIN_API_SECRETE_KEY", "XXXXXXXX");
define("LINKEDIN_CALLBACK_URL", "http://localhost/LinkedIn/test.php");
#################End Paste into config file###############################

Step 3-> create a file linkedin_app.php
##################Start####################################
<?php

require_once('config.php');
require_once('LinkedIn.OAuth2.class.php');

class LinkedIn
{
    /**
     * Function to get LinkedIn Authorize URL and access token
    */
    function fnLinkedInConnect()
    {
        # Object of class
        $ObjLinkedIn = new LinkedInOAuth2();
        $strApiKey = LINKEDIN_API_KEY;
        $strSecreteKey = LINKEDIN_API_SECRETE_KEY;

        //put here your redirect url
        $strRedirect_url = LINKEDIN_CALLBACK_URL;

        $strCode = isset($_REQUEST['code']) ? $_REQUEST['code'] : '';

        if ($strCode == "") {

            try {
                # Get LinkedIn Authorize URL
                #If the user authorizes your application they will be redirected to the redirect_uri that you specified in your request .
                $strGetAuthUrl = $ObjLinkedIn->getAuthorizeUrl($strApiKey, $strRedirect_url);
            } catch (Exception $e) {

            }
            header("Location: ".$strGetAuthUrl);
            exit;
        }

        # Get LinkedIn Access Token
        /**
         * Access token is unique to a user and an API Key. You need access tokens in order to make API calls to LinkedIn on behalf of the user who authorized your application.
         * The value of parameter expires_in is the number of seconds from now that this access_token will expire in (5184000 seconds is 60 days).
         * You should have a mechanism in your code to refresh the tokens before they expire in order to continue using the same access tokens.
         */
        $arrAccess_token = $ObjLinkedIn->getAccessToken($strApiKey, $strSecreteKey, $strRedirect_url, $strCode);
        $strAccess_token = $arrAccess_token["access_token"];
##########################store access token into database#############################
      ### insert into table (accessToken)value($strAccess_token);
    }
###################get company page############################

function fnGetLinkedCompanyPages()
    {
         #############get access token from db####################
$strAccess_token = 'set access token from db';


        # Object of class
        $ObjLinkedin = new LinkedInOAuth2($strAccess_token);

        # Get List of company pages
        try {
            $arrAdminCompany = $ObjLinkedin->getAdminCompanies();
        } catch (Exception $e) {

        }

        $arrAdminCompanyValue = $arrAdminCompany["values"];
        $intTotalCount = count($arrAdminCompany["_total"]);

        $arrLinkedInPages = array();
        $intCount = 0;
        if (is_array($arrAdminCompanyValue) && count($arrAdminCompanyValue) > 0) {
            foreach ($arrAdminCompanyValue as $arrAdminCompanyInfo) {
                $intFlag = 0;

                $arrLinkedInPages[$intCount]["id"] = (int) $arrAdminCompanyInfo["id"];
                $arrLinkedInPages[$intCount]["name"] = stripslashes($arrAdminCompanyInfo["name"]);
            }
        }

        return $arrLinkedInPages;
    }

#########################share to linkedIn company page##############################
function postToCompanyPage($company_id)
{


                  #############get access token from db####################
$strAccess_token = 'set access token from db';

$message="this for testing Api Integration";
$content =array(
            "title" =>'Sr Software Developer(php)',
            "description" => 'Urgent opeing in Java Developer having 5+year exp at Veebrij Software pvt ltd',
            "submitted-url" => 'http://www.test/orange-software-p-ltd-noida-urgently-looking-for-2--senior-back-end-developer-c-sql-net/811/jobview',
            "submitted-image-url" => 'http://www.test/com/uploads/profileimage/recruiter/company_1460711697.jpg',

"visibility" => array(
            "code" => "anyone"
)
        );
$ObjLinkedin = new LinkedInOAuth2($strAccess_token);


try {
         
            $arrResponse = $ObjLinkedin->postToCompany($company_id, $message,$content);
         

print_r($arrResponse);
exit;

            // not post given error
            if ($arrResponse['updateKey'] == "") {
                $strErrorMessage = "SET ERROR MESSAGE";
            }

        } catch (Exception $e) {

        }

}

#########################post to user wall################################

function fnPostMessage()
{
   
        $strStatusMessage = "Sr Software engineer(Java) test";
        $strAccess_token ='get access token from db';

        # Object of class
        $ObjLinkedin = new LinkedInOAuth2($strAccess_token);
$content =array(
            "title" =>'Sr Software engineer(Java) testvvs',
            "description" => 'Urgent opeing in Java Developer having 5+year exp at Veebrij Software pvt ltd',
            "submitted-url" => 'http://www.test.com/orange-software-p-ltd-noida-urgently-looking-for-2--senior-back-end-developer-c-sql-net/811/jobview',
            "submitted-image-url" => 'http://www.test.com/uploads/profileimage/recruiter/company_1460711697.jpg',

"visibility" => array(
            "code" => "anyone"
)
        );
 try {
            $strErrorMessage = '';
       
            $arrResponse = $ObjLinkedin->shareStatus($content);

            // not post given error
            if ($arrResponse['updateKey'] == "") {
                $strErrorMessage = "SET ERROR MESSAGE";
            }

        } catch (Exception $e) {

        }
        return $strErrorMessage;
   }


}

####################### create output file LinkedsharePost.php###################


<?php
create out put final linkedin share page like LinkedsharePost.php

#Include necessary class files
require_once('linkedin_app.php');

$li = new LinkedIn();
$li->fnLinkedInConnect();
$linkedinpages = $li->fnGetLinkedCompanyPages();
##get company id from array################
print_r($linkedinpages);

$updatePostPage=$li->postToCompanyPage(PASS COMPANYID);
print_r($linkedinpages);




Finally we have done all of the step, hope it will help you. please comment if anyone face any difficulty.


2 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. Writing posts is the easy part but remembering to post them on time is tough. I really needed an app or a website that would help me schedule my post. LassoIn.com is one such site that has been helping me to schedule different posts. The site has reduced my workload and provided me with time to concentrate on other things.

    ReplyDelete