Salesforce.com : Connecting two salesforce instances using OAuth

Today we will talk about connecting two salesforce instances using OAuth authentication to share data between two salesforce instances. You may ask, why to go via this route at all, when we can use out of the box Salesforce to Salesforce feature. Well yes, you can but you do not have much flexibility there to deal with the data you received and what you do with it. Using the steps I am going to share here, we will share a REST API , which can receive a request and give you the desired response. As indicated earlier I will be using the Named Credentials from previous post to get this done. If you did not see the previous post, you can always go there :  Salesforce.com : How to use Named Credentials ?

The Use Case:

We will create a connection to another salesforce instance from one instance and sent an Phone number. The other org will get this request and search for all contacts with the phone number. If there is a contact with this phone number the REST service will send the contact Name and email address as a response to the calling org.

Simple enough for now, but it will give you a starting point from where sky is the limit. 🙂 So, let’s start.

Steps for Connecting two salesforce instances using OAuth :

We will first create a sample class(These are only sample classes so did not care about the best practices in coding 🙂 ) to expose the REST Service to the other parties. This class will receive a single parameter (string), which is the phone number as part of the request body. The response will be in JSON , which will include the contact name and email address if found. Here is the class to expose the service for others to be consumed:

(Salesforce service provider org steps)

@RestResource(urlMapping='/contactsearch/*')
global with sharing class SearchContact{

@HttpPost
global static returnData getDetails() {
      returnData data= new returnData();
      RestRequest req = RestContext.request;

     List con= [select id,name,email from contact where phone =:(req.requestBody).toString()];
     if(con.size()>0){
         data.Name=con[0].name;
         data.email=con[0].email;
      }
     return data;
}

global class returnData{
    global String Name;
    global String email;

}

}

The above class will receive a POST method request to get you the result. By creating the above class you actually exposed a REST based service from your salesforce instance. This was one of the major work you had to do for Connecting two salesforce instances using OAuth.

Now we need to establish a connection between two salesforce instances, so that we can utilise the above service just created. Let’s start with creating a connected App. You can create a connected app under app menu in your setup area. In this step you will get a consumer key and a consumer secret. These are our basic requirement for Oauth authentication. Here is a sample screenshot of the connected App page in our service provider org. Let’s call this org as Service provider org going forward as this org is providing the REST service.

Connected App SearchContact Salesforce Developer Edition

(Salesforce consumer org steps)

Now let’s login to the consumer org, from where we will fire the request with the phone number and receive the name and email address. As the title of this post suggest : Connecting two salesforce instances using OAuth , we will be using OAuth for our authentication.  In this second org we will create an Auth Provider and a Named Credential ,to use this Auth Provider. For creating Named credential please go the the link for my previous post and follow the steps : Click Here. On that post we used basic authentication, here you will select OAuth.

My Named credential is looking like below now.

NamedCred

Next step for connecting two salesforce instances using OAuth is , to create a caller class. We will use the Named Credential to call the provider service.

Here is how the class looks like :


public class RESTCall {
    
    public static void apicall(){
        http http = new http();
        Httprequest req= new httprequest();
        Httpresponse resp= new Httpresponse();
        
        req.setEndpoint('callout:SearchContact/services/apexrest/contactsearch');
        req.setMethod('POST');
        req.setBody('(312) 596-1000');
        resp = http.send(req);
        system.debug('@@Request>'+resp.getBody());
    }
}

Now as we are ready with the caller class , we can to to the developer console and in the Execute anonymous block window write :

RESTCall.apicall();

and hit execute. Once this call was successful you can see in your debug log something similar to the below response:

12:35:32:124 USER_DEBUG [12]|DEBUG|@@Request>{“Name”:”Amit Sahu”,”email”:”testuser@getthekt.com”}

All done!!!! Pretty simple isn’t it

Next Step:

This is for you to do 🙂 Here are multiple options you have, as many as you can think of. The response is in JSON format,
so you can parse it using JSON parser class and use the data in your visualforce page or store the data in your objects etc.

Conclusion:

As you see this was connecting two salesforce instances using OAuth. But you can similarly connect to various other 3rd party systems as well using the same steps explained here. Please share if you are stuck at some step. Happy to help!

Keep reading .. Keep sharing….


Comments

3 responses to “Salesforce.com : Connecting two salesforce instances using OAuth”

  1. sampath Avatar
    sampath

    Hi Amit ,

    I have tried the above example in my login but it is showing error message as ” “errorCode”:”URL_NOT_RESET”,”message”:”Destination URL not reset. The URL returned from login must be set” ”
    I am not getting what is the problem . Can you help me in this
    Thanks

    1. Yes, you might have incorrect values in the callback url. Can you share the connected app callback url and Auth Provider callback url. You can also try changing the url to whatever domain you have enabled. If still facing issues let me know we can do a webex to fix this.
      Regards,
      Amit

      1. sampath Avatar
        sampath

        Hi Amit,

        I have tried the way you said but still unable to resolve the issue . Can you tell me ur available timing so that will have webex.
        My mail id = saisampath123@gmail.com

Leave a Reply

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