Connect two Salesforce org

Connect two Salesforce Orgs using OAuth2 authentication


Use Case: You need to access data hosted on another Salesforce Org from your own Salesforce Org, to perform any type of operations


It often happens that you have available in another sandbox some data which you’d like to fetch, manipulate and get loaded into another Salesforce org in the blink of an eye, by avoiding the pain of having to extract them, manipulate them using a text editor and load them back using a dataloader tool.

If you are a minimum well versed in Apex code and feel confortable building a reusable script running at the speed of light, this article will help you connecting your 2 orgs. A bunch of articles are being worked upon currently to guide you through and end to end scenario and guide you step by step. This one is the first step of this collection of article.

Here are the high levels steps that you need to understand in order to achieve this:

  • Configure your source org. The source org is where the data you want to copy are
  • Configure your target org. The target org is where you want the remote data to be loaded
  • Execute a script from your target org. From your target org the script will connect and fetch the data from the source org

Setup your source Org


In order to connect from one Salesforce org to another, we’ll use the standard OAUTH2 Username/Password flow. This will allow us to establish the connection and then, thanks to the token generated, to play with the standard REST API.

In order to do so, you’ll need:

In order to validate the connectivity to the org with your setup, just go through the following article explaining how to test your connected app with Postman.


Setup your destination Org


On your destination org, you need to grant access to the source org, by setting two Remote Sites Settings as shown below.

The first URL is the generic Salesforce URL (https://test.salesforce.com for sandboxes or https://login.salesforce.com for production orgs or developer orgs).
The second URL is the MyDomain URL. Just put your domain concatenated with .my.salesforce.com.


Execute script from your Salesforce destination org


Now all the prerequisites are set up, let’s have a look on the script part.

/******************************/
// Authentication method using OAUTH2 Username/Password flow
/******************************/
void OAuthAuthentication(){
    //Connected App information
    String clientId = '5OPG9d3kbIopE1owJgtEhjkwY5p5MQ1ILnAKPpmV.8O4LHZTpY6hHoeIUc8QmVTvQWEnNRwlZzlmWpk';
    String clientSecret = 'G77555B48E61E395089947G80A70F5F6843EEB65FA065YF32CBC25247C0892RE';
	
    //API User information
    String username='apiuser@sourceorg.com';
    String password='apiuserpassword_andtokenifrequired';
		
    // Generating the Access Token
    HttpRequest req = new HttpRequest();
    req.setMethod('POST');
    req.setEndpoint('https://test.salesforce.com/services/oauth2/token');
    req.setBody('grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password);
        
    Http http = new Http();
    HTTPResponse res = http.send(req);
    String str = res.getBody();
    wrapObj = (Wrapper)Json.deserialize(str,Wrapper.class);
    accessToken = wrapObj.access_token;
    instanceUrl = wrapObj.instance_url;
}
        
/******************************/
// Wrapper Class to store the value from the JSON
/******************************/
class Wrapper{
    String id;
    String instance_url;
    String access_token;
    String issued_at;
    String signature;
}

/******************************/
// Global variables
/******************************/
    String accessToken;
    String instanceUrl;
    Wrapper wrapObj{get;set;}

/******************************/
// Executing the methods
/******************************/
    OAuthAuthentication();

The whole code above can simply be executed in the Developer Console in Anonymous mode, or you can create classes – this is your choice depending on your use case.
You can then easily improve the code by testing HTTP code returned by the authentication call and drive the success and error path as you want.

Some inputs to configure also depending on your own situation:

  • setEndpoint: set the endpoint depending on your situation (https://test.salesforce.com for sandboxes or https://login.salesforce.com for production orgs or developer orgs)
  • Don’t forget to generate and append the security token to your password in case IP filtering is not activated at the profile level

Here it is! You know all the basics and can adapt it to your own situation.


Have you found this interesting? Please share!


Leave a Comment

Your email address will not be published. Required fields are marked *