Wednesday, 8 May 2013

Linkedin Gem for Rails : How to share dynamic contents to Linkedin from your Rails Application


After Facebook & Twitter share ,its time for Linkedin. I would suggest you to refer my 2 prev posts before going through this article.

Include "linkedin" gem in your Gemfile and bundle .

gem 'linkedin'

Route file:

 match '/linkedin_share/auth'   => 'linkedin_share#auth' , :method => :get , :as => :linkedin_auth

 match '/linkedin_share/callback' => 'linkedin_share#callback' , :method => :get , :as =>  :linkedin_callback


LinkedinShare Controller & Actions : 

class LinkedinShareController < ApplicationController

  def init_client
    
    key = "APP KEY"
    secret = "SECRET KEY"

    linkedin_configuration = { :site => 'https://api.linkedin.com',
        :authorize_path => '/uas/oauth/authenticate',
        :request_token_path =>'/uas/oauth/requestToken?scope=rw_nus',
        :access_token_path => '/uas/oauth/accessToken' }

    @linkedin_client = LinkedIn::Client.new(key, secret,linkedin_configuration )
  end

  def auth
    init_client
  
    cookies["title"] = { :value => "#{params[:title]}", :expires => 1.minute.from_now }
    cookies["url"] = { :value => "#{params[:url]}", :expires => 1.minute.from_now }
  
    request_token = @linkedin_client.request_token(:oauth_callback => "http://#  {request.host_with_port}/linkedin_share/callback")
    session[:rtoken] = request_token.token
    session[:rsecret] = request_token.secret
  
    redirect_to @linkedin_client.request_token.authorize_url
  end

  def callback
    init_client
  
    if session[:atoken].nil?
      pin = params[:oauth_verifier]
      atoken, asecret =  @linkedin_client.authorize_from_request(session[:rtoken], session[:rsecret], pin)
      session[:atoken] = atoken
      session[:asecret] = asecret
    else
      @linkedin_client.authorize_from_access(session[:atoken], session[:asecret])
    end

    c = @linkedin_client
    
    title = "#{cookies["title"]}"
    url = "#{cookies["url"]}"

    c.add_share({
        :comment => title,
        :content => {
          :title => title,
          :submitted_url => url,
          :submitted_image_url => "IMAGE PATH",
          :description => 'YOUR DESCRIPTION'
        }
      })

    redirect_to root_path
  end
end






1 comment:

  1. Hello,

    I used your code but get error below.

    LinkedIn::Errors::AccessDeniedError in SocialAccountsController#share_message_linkedin

    (403): Access to posting shares denied

    Anything wrong here.

    Thanks

    ReplyDelete