Skip to content

Instantly share code, notes, and snippets.

@undees
Created February 10, 2010 09:23
Show Gist options
  • Save undees/300175 to your computer and use it in GitHub Desktop.
Save undees/300175 to your computer and use it in GitHub Desktop.
Connect Ruby to Salesforce via OAuth
require 'oauth'
consumer_key = '...' # from SalesForce
consumer_secret = '...' # from SalesForce
oauth_options = {
:site => 'https://login.salesforce.com',
:scheme => :body,
:request_token_path => '/_nc_external/system/security/oauth/RequestTokenHandler',
:authorize_path => '/setup/secur/RemoteAccessAuthorizationPage.apexp',
:access_token_path => '/_nc_external/system/security/oauth/AccessTokenHandler',
}
consumer = OAuth::Consumer.new consumer_key, consumer_secret, oauth_options
# consumer.http.set_debug_output STDERR # if you're curious
request = consumer.get_request_token
authorize_url = request.authorize_url :oauth_consumer_key => consumer_key
puts "Go to #{authorize_url} in your browser, then enter the verification code:"
verification_code = gets.strip
access = request.get_access_token :oauth_verifier => verification_code
puts "Access Token: " + access.token
puts "Access Secret: " + access.secret
require 'oauth'
require 'rexml/document'
consumer_key = '...' # from SalesForce
consumer_secret = '...' # from SalesForce
access_token = '...' # from the previous step
access_secret = '...' # from the previous step
# Log in and request a URL/session.
consumer = OAuth::Consumer.new consumer_key, consumer_secret
access = OAuth::AccessToken.new consumer, access_token, access_secret
login_url = 'https://login.salesforce.com/services/OAuth/u/20.0'
result = access.post login_url, '', {'content-type' => 'application/x-www-form-urlencoded'}
# Parse the URL/session.
doc = REXML::Document.new result.body
session_id = doc.elements['*/sessionId'].text
server_url = doc.elements['*/serverUrl'].text
# The part of the request that isn't boilerplate:
body = <<HERE
<search xmlns="urn:partner.soap.sforce.com">
<searchString>find {McFakerson Co} in name fields returning account(id)</searchString>
</search>
HERE
# The rest (sigh).
request = <<HERE
<?xml version=\"1.0" encoding="utf-8" ?>
<soap:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:partner="urn:partner.soap.sforce.com">
<soap:Header>
<partner:SessionHeader soap:mustUnderstand='1'>
<partner:sessionId>#{session_id}</partner:sessionId>
</partner:SessionHeader>
</soap:Header>
<soap:Body>
#{body}
</soap:Body>
</soap:Envelope>
HERE
headers = {
'Content-Type' => 'text/xml',
'SOAPAction' => '""',
}
# Finally, we can make the request...
result = access.post server_url, request, headers
# ... and parse the response.
doc = REXML::Document.new result.body
result_id = doc.elements['*/*/*/*/*/*/sf:Id'].text
puts "First matching ID: #{result_id}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment