Integrating One Salesforce Org to Another Salesforce Org Using REST API
Hello guys,
Today, I will show you how you can integrate one Salesforce org to another Salesforce Org using REST API. For this, you will need the following things -
- Source Org (Salesforce Org)
- Target Org (Salesforce Org)
STEP BY STEP INTEGRATION of Source and Target Salesforce Org-
Step 1 - Create a Connected App in Target Org.
By going, Setup-> Create->Apps OR (Search “Apps” in Quick Find Box).
Click on New and fill the details as per your requirements but your callback URL looks like this-
https://<domain>.my.salesforce.com/services/oauth2/callback
After clicking on Save you will see the Client Id and Client Secret key (Save that, we will need it for Integration)
Step 2 - Create an Apex Class in Target Org to retrieve 10 Accounts from Target Org.
Go to Developer Console and Create New Apex Class.
@RestResource(urlMapping='/v1/getAccounts/*') global with sharing class FetchAccount { @HttpGet global static list<account> fetchAccount(){ RestRequest req = RestContext.request; RestResponse res = Restcontext.response; List<account> listAccount =[Select Id , Name from Account LIMIT 10 ]; return listAccount ; } }
Step 3 - Create a Remote Setting on Source Org.
Search “Remote Site Setting” in Quick find Box and Enter Remote Site URL of your Target org, the format is like that -
https://<domain>.my.salesforce.com
Step 4 - Create an Apex Class in Source Org, which will callout Apex class of Target Org and return you 10 Accounts.
Here is the code:
public class GetAccountUsingRESTAPI { private final String clientId = 'XXXXXXXXXXXXXXXX'; private final String clientSecret = 'XXXXXX8XXX'; private final String username = 'SalesforceUserName'; private final String password = 'Password'; public class deserializeResponse { public String id; public String access_token; } public String ReturnAccessToken (GetAccountUsingRESTAPI acount) { String reqbody = 'grant_type=password&client_id=' +clientId+'&client_secret=' +clientSecret+'&username=' +username+'&password='+password; Http h = new Http(); HttpRequest req = new HttpRequest(); req.setBody(reqbody); req.setMethod('POST'); req.setEndpoint('https://login.salesforce.com/services/oauth2/token'); HttpResponse res = h.send(req); deserializeResponse response = (deserializeResponse)JSON.deserialize(res.getbody(),deserializeResponse.class); system.debug('@@@@access_token@@'+response ); return response.access_token; } public static list<account> callGetAccount() { GetAccountUsingRESTAPI acount1 = new GetAccountUsingRESTAPI(); String accessToken; accessToken = acount1.ReturnAccessToken (acount1); list<account> ListAccount=new List<account>(); if(accessToken != null) { String endPoint = 'https://avnish1.salesforce.com/services/apexrest/v1/getAccounts/'; Http h2 = new Http(); HttpRequest req1 = new HttpRequest(); req1.setHeader('Authorization','Bearer ' + accessToken); req1.setHeader('Content-Type','application/json'); req1.setHeader('accept','application/json'); req1.setMethod('GET'); req1.setEndpoint(endPoint); HttpResponse res1 = h2.send(req1); String trimmedResponse = res1.getBody().unescapeCsv().remove('\\'); system.debug('@@@RESPONSE@@'+trimmedResponse); JSONParser parser = JSON.createParser(res1.getBody()); set<account> accList=new set<account>(); while (parser.nextToken() != null) { if((parser.getCurrentToken() == JSONToken.FIELD_NAME) ) { Account acc; if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'Id')) { parser.nextToken(); String sId= parser.getText(); acc=new Account(); acc.Id=sId; system.debug('Id@@@' + sId); parser.nextToken(); if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'Name')) { parser.nextToken(); string sName= parser.getText(); acc.Name=sName; system.debug('Name@@@' + sName ); } } accList.add(acc); } accList.remove(null); } ListAccount.AddAll(accList); system.debug('AccountList@@@@'+Json.serialize(ListAccount)); } return ListAccount; } }
In this code you will need to replace the following things:-
- client
- clientSecret
- username
- password
Also, Change the Endpoint in method ReturnAccessToken() in which org you are trying to log in. means where you have created your Connected Appreq.setEndpoint(‘https://login.salesforce.com/services/oauth2/token’);
Also, Change the Endpoint in method callGetAccount() in which org you are trying to access all the Contacts. means where you have developed your Apex RestService
String endPoint = ‘https://avnish1.salesforce.com/services/apexrest/v1/getAccounts/’;
Now call the function “callGetAccount()”. Feel free to ask questions in a comment box.
Thanks.
Happy Coding.
Hi Avnish,
I did the same way you have mentioned above but I am getting bad request while accessing the oauth token. I tried in all possible ways to solve this but no luck. Can you please help me to solve this issue?
When I check logs, I see below error -
CALLOUT_REQUEST|[22]|System.HttpRequest[Endpoint=https://democlass1-dev-ed.my.salesforce.com/services/oauth2/token, Method=POST]
CALLOUT_RESPONSE|[22]|System.HttpResponse[Status=Bad Request, StatusCode=400]
Thanks,
Raji M
hi..
Im not getting response. first im not getting access token, it getting null.
Hi Lavanya Ravirala,
Please add the remote setting on both the Salesforce Org.
Thanks.
Hello
In ReturnAccessToken method you have to pass reqbody value as following
String reqbody = 'grant_type=password' + '&client_id='+clientId +
'&client_secret='+clientSecret + '&username='+username + '&password='+password;
For me its working when i change like above code
Thanks
Siri Chandana
hello
for password field you have to pass
password = password+security token (Not Access token)
Creation of Security token :
Go to your org -> My Settings -> search (Reset My Security Token) ->Check your registered mail -> there you get Security Token
Hey Avnish
I am getting the same error access_token = null and id = null
I have added remote setting in both orgs.
Hi Avnish,
I did the same way you have mentioned above but the error below occurs.
I have also set Remote Setting for both orgs.
''System.JSONException: No content to map to Object due to end of input''