Search code examples
ruby-on-railsruby-on-rails-4linkedin-api

Send Linked IN Message without gem


I try to send a message to linked in users via several gems, but I get Faraday::Error.

Is there a way to send it without gems? How ?

Iam using ruby 2.0.0 and rails 4.1.6.


Solution

    • You can send it using Net::HTTP.

    • Make sure you have the granted permission for scope w_messages


    Here is how to send it:

    # token : user's token (who is going to send the message)
    # subject : Subject of the message
    # body : body of the message
    # recipient_ids : array of recipient ids (on linkedin) 
    
    require "net/http"
    
    def send_linkedin_message(token, subject, body, recipient_ids)
      path = "https://api.linkedin.com/v1/people/~/mailbox"
      message = {
        subject: subject,
        body: body,
        recipients: {
          values: recipient_ids.map do |profile_path|
            {person: {_path: "/people/#{profile_path}"} }
          end
        }
      }
    
      uri = URI.parse(path)
      request = Net::HTTP::Post.new(uri)
      request.body = message.to_json
      request.initialize_http_header({ "x-li-format" => "json", "Authorization" => "Bearer #{token}" })
      request.content_type = 'application/json'
      response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http| http.request request}
    end