Skip to content

Instantly share code, notes, and snippets.

@richardvanhook
Created September 27, 2011 13:43
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save richardvanhook/1245068 to your computer and use it in GitHub Desktop.
Save richardvanhook/1245068 to your computer and use it in GitHub Desktop.
Apex code demonstrating how to log in from one salesforce org to another
/*
======================================================================
The following apex code demonstrates logging into another salesforce
org via the SOAP/XML web service api and then using session id to
query the standard REST API as well as the Chatter REST API.
To run this code, simply copy and paste into execute anonymous,
then replace the value of the first three variables accordingly.
NOTES:
(1) You'll need to create a remote site setting for both the login
url and the server url. If you're org is on na1, then you'll
need the following URLs as remote site settings:
https://www.salesforce.com
https://na1-api.salesforce.com
======================================================================
*/
//CHANGE THESE VARIABLES
final String LOGIN_DOMAIN = 'www'; //other options: test, prerellogin.pre
final String USERNAME = 'REPLACE_ME';
final String PASSWORD = 'REPLACE_ME';
//----------------------------------------------------------------------
// Login via SOAP/XML web service api to establish session
//----------------------------------------------------------------------
HttpRequest request = new HttpRequest();
request.setEndpoint('https://' + LOGIN_DOMAIN + '.salesforce.com/services/Soap/u/22.0');
request.setMethod('POST');
request.setHeader('Content-Type', 'text/xml;charset=UTF-8');
request.setHeader('SOAPAction', '""');
//not escaping username and password because we're setting those variables above
//in other words, this line "trusts" the lines above
//if username and password were sourced elsewhere, they'd need to be escaped below
request.setBody('<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"><Header/><Body><login xmlns="urn:partner.soap.sforce.com"><username>' + USERNAME + '</username><password>' + PASSWORD + '</password></login></Body></Envelope>');
Dom.XmlNode resultElmt = (new Http()).send(request).getBodyDocument().getRootElement()
.getChildElement('Body','http://schemas.xmlsoap.org/soap/envelope/')
.getChildElement('loginResponse','urn:partner.soap.sforce.com')
.getChildElement('result','urn:partner.soap.sforce.com');
//----------------------------------------------------------------------
// Grab session id and server url (ie the session)
//----------------------------------------------------------------------
final String SERVER_URL = resultElmt.getChildElement('serverUrl','urn:partner.soap.sforce.com').getText().split('/services')[0];
final String SESSION_ID = resultElmt.getChildElement('sessionId','urn:partner.soap.sforce.com').getText();
//----------------------------------------------------------------------
// Load first 10 accounts via REST API
//----------------------------------------------------------------------
final PageReference theUrl = new PageReference(SERVER_URL + '/services/data/v22.0/query/');
theUrl.getParameters().put('q','select id,name from Account limit 10');
request = new HttpRequest();
request.setEndpoint(theUrl.getUrl());
request.setMethod('GET');
request.setHeader('Authorization', 'OAuth ' + SESSION_ID);
String body = (new Http()).send(request).getBody();
System.debug('Accounts in JSON format: ' + body);
//----------------------------------------------------------------------
// Uncomment following if you're running on Winter '12 or later;
// JSONParser is new in Winter '12.
//----------------------------------------------------------------------
/*
JSONParser parser = JSON.createParser(body);
do{
parser.nextToken();
}while(parser.hasCurrentToken() && !'records'.equals(parser.getCurrentName()));
parser.nextToken();
//the following line is wicked cool
final List<Account> accounts = (List<Account>) parser.readValueAs(List<Account>.class);
System.debug('Accounts as native list: ' + accounts);
*/
//----------------------------------------------------------------------
// Load your news feed via Chatter REST API.
//
// Uncomment following if the org you logged into is running Winter '12
// or later; the Chatter REST API is GA in Winter '12.
//----------------------------------------------------------------------
/*
request.setEndpoint(SERVER_URL + '/services/data/v23.0/chatter/feeds/news/me/feed-items');
System.debug('My News Feed from Chatter REST API: ' + (new Http()).send(request).getBody());
*/
@hujia0601
Copy link

This is really cool! Thanks a lot for sharing.

I have a question that if we can call the Apex WS directly after login.
Like add the link of Apex WS to request.setHeader('SOAPAction', '" add some apex ws link here"');

@satyajit160988
Copy link

How could I use the above code to insert or update records from one salesforce org to another?
This is important.Please reply soon.

Thanks

@pbergner
Copy link

Thanks!

@venkataraja
Copy link

Can you please send test class for this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment