Rest API Callout for Integration of Salesforce orgs

Rest API Callout for Integration of Salesforce orgs

Sharing is caring!

Salesforce Integration is about connecting Salesforce and other platforms, tools, and apps. The integration allows you to streamline different processes and ensures an automated data flow between these systems. The integration takes place by using data, user interface, and business logic.  

Salesforce Integration helps in a smooth and seamless data flow between various departments and automatic data synchronisation. The integration facilitates an automated data flow between the systems.

In this digital era, companies are looking for new ways to stay competitive since they need to increase efficiency and customer experience. Now, systems hardly work in isolation. To carry out in a faster and scalable manner, integration is the need of the hour for businesses and must integrate in a better way. 

In this post, we have two salesforce org; one is source org(org A), and the other is destination org(org B), so when any account record is created in source org, it will automatically be pushed into the destination org (B). You learn about the REST API to Salesforce integration. This post provides information on API, REST API, its methods, Salesforce, its key features and versions, and the methods and steps involved in setting up REST API to Salesforce connection

Integration of One Salesforce Org to Another Salesforce Org by using Rest API Callout  

Source org(Org A)

Let’s Start with the Source Org. In source org, we have to create a remote site setting, and we follow the following steps to fix the remote site setting.

  • Go to setting >> Setup >> Quick Find box >> Remote site setting >> New 
  • Create two new remote site setting
  • In the First new remote site setting, enter the salesforce login URL:    https://login.salesforce.com
  • In the second new remote site setting enter the destination org(Org B) url : https://cloudanalogy-60c-dev-ed.my.salesforce.com
  • In Org, a developer console creates an Apex class which will use future callout, and Trigger which calls future class on Insertion.
  • Create remote site setting as in the figure below:
  • Then write a Trigger in the developer console of source org, which calls the future method on insertion.
  • And create an Apex class for triggers.

Apex Class(Org A)

/*

Org A (Source Org)

Class Name : OrgSendAccountTrigger_Handler

Trigger Name : OrgSendAccountTrigger

Created By : Aman Maindola

Created Date : 15-12-2021

Description : Integration of two salesforce org, when an account record is created in Org A it will be automatically created in Org B.

*/

public class IntegeratingTwoSalesforceOrgHandler {

    //Write below clientId, clientSecret, username, password from Org B Destination Org)

public class IntegeratingTwoSalesforceOrgHandler {

    //Write below clientId, clientSecret, username, password from Org B Destination Org)

 private final String clientId =

‘3MVG9fe4g9fhX0E69RhJE6x8sBfW5PCJqaD9A79u2nfXPSSUVROI2C7KmkmdxWhuQGyGrrhu5ZhqcVzTNKWGQ’;

    private final String clientSecret =

’54FCD8F4C2810223AA57244DF2972189E30E42CED866961E09B0C56CFF891EA7′;

    private final String username = ‘amanmaindola@cloudanalogy.com’;

    private final String password = ‘Aman1234’;

    public class resWrapper

    {

        public String id;

        public String access_token;

    }

    public class accountWrap{

        public string case_region;

        public String wName;

        public String wPhone;

        public accountWrap(String name,String phone)

        {

            this.wName =name;

            this.wPhone =phone;

        } 

    }

    public String getRequestToken(OrgSendAccountTrigger_Handler accnt){

        try{              String reqbody = ‘grant_type=password’ + ‘&client_id=’+clientId +’&client_secret=’+clientSecret + ‘&username=’+username + ‘&password=’+password;

            Http h1 = new Http();

            system.debug(‘reqbody ‘+reqbody);

            HttpRequest req = new HttpRequest();

            req.setBody(reqbody);            

            req.setMethod(‘POST’);

            req.setEndpoint(‘https://login.salesforce.com/services/oauth2/token’);

            System.debug(‘req–> ‘+req);

            HttpResponse res = h1.send(req);

            system.debug(‘Response status is:’+res.getStatusCode());

            system.debug(‘(resWrapper)JSON.deserialize(res.getBody(),resWrapper.class) –> ‘+(resWrapper)JSON.deserialize(res.getBody(),resWrapper.class));

 resWrapperresponse = (resWrapper)JSON.deserialize(res.getBody(),resWrapper.class);

            System.debug(‘response—>>>’+res);

            System.debug(‘response.access_token—>>>’+response.access_token);

            return response.access_token;

        }catch(exception e){

            system.debug(‘Error:’+e.getMessage()+’At Line’+e.getLineNumber());

            return Null;

        }

    }

    @future(callout=true)

    public static void createAccountMethod(Set accIdSet){

        OrgSendAccountTrigger_Handler accnt = new OrgSendAccountTrigger_Handler();

        String accessToken;

        String JSNBody;

        accessToken = accnt.getRequestToken(accnt);

        System.debug(‘accessToken:::::’+accessToken);

        List accList = new List();

        if(accessToken != null) {

            //Set Endpoint URL Of the Destination Org WebserviceClass

StringendPoint=’https://cloudanalogy-60c-dev-ed.my.salesforce.com/services/apexrest/v1/accountRecordCreate/’;  

            system.debug(‘endPoint:::::::’+endPoint);

            For(Account acc:[SELECT Id, Name, Phone FROM Account WHERE Id IN: accIdSet]){

                accList.add(acc);

                if(accList.size() > 0)

                {

                    accountWrap accObj = new accountWrap(accList[0].name ,accList[0].phone );

                    JSNBody = JSON.serialize(accObj);

                    system.debug(‘accountWrap Serialize JSON:::::::’+accObj);

                }  

                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(‘POST’);

                req1.setBody(JSNBody);

                System.debug(‘body—>>’+JSNBody);

                req1.setEndpoint(endPoint);

                HttpResponse res1 = h2.send(req1);

            }

        }

    }

   // Callout to Delete Records

    @future(callout=true)

    public static void deleteAccountMethod(Set accIdToDelete)

    {              

        String accToken;

        String JSNBody;  

        if(accIdToDelete!= null){

            accountWrap accObj = new accountWrap(”,”,accIdToDelete.iterator().next());

            JSNBody = JSON.serialize(accObj);

        }

string

endPoint=’https://cloudanalogy-60c-dev-ed.my.salesforce.com/services/apexrest/v1/accountRecordCreate/’;

        IntegeratingTwoSalesforceOrgHandler accnt = new IntegeratingTwoSalesforceOrgHandler();

        accToken=accnt.getRequestToken(accnt);

        system.debug(‘access token’+ accToken);

        if(accToken != null)

        {

            Http h1=new Http();

            HttpRequest req1=new HttpRequest();

            req1.setHeader(‘Authorization’,’Bearer ‘+accToken);

            req1.setHeader(‘Content-Type’,’application/json’);            

            req1.setMethod(‘DELETE’);

            req1.setBody(JSNBody);

            req1.setEndpoint(endPoint);

            HttpResponse hresp1=h1.send(req1);            

        }                        

    }        

}

Trigger(Org A)

trigger IntegeratingTwoSalesforceOrg on Account (after insert,after update,After Delete) {    

    set accSetId = new set();

    Set extenalIdSet = new set();

    if((Trigger.Isinsert || Trigger.Isupdate)  && Trigger.isAfter){

        for(Account acc: Trigger.new){

            if(acc.name!=NULL){

                accSetId.add(acc.Id);

            }

        }

        if(accSetId.size()>0){

            IntegeratingTwoSalesforceOrgHandler.createAccountMethod(accSetId);       

        }

    }    

    if(Trigger.isDelete && Trigger.isAfter){

        for(Account acc: Trigger.old){

            if(acc.name!=NULL){

                extenalIdSet.add(acc.ExternalId__c);

            }

        }        

        if(extenalIdSet.size()>0){

            IntegeratingTwoSalesforceOrgHandler.deleteAccountMethod(extenalIdSet);

        }        

    }      

}

Now, we come to the destination org.

Destination org(Org B)

In the Destination org, create a connected app and obtain clientId, clientsecret, username, and password that will be used in the source org code.

  • To implement connected app setting follow the following steps:
  1. Login to Salesforce as an administrator.
  2. In the drop-down list of the account (in the upper-right corner), select    Setup.
  3. In the left-hand pane, go to App Setup > Home > Quick Find Box > App Manager > New Connected App
  4. In the new connected app enter the following required field.
  • Connected App Name. For Example, S2S Integration.
  • API name. For example, S2SIntegration.
  • Contact Email.

 5.   Go to API (Enable OAuth Settings), and select Enable OAuth Settings.

  • In the Callback URL field, enter: https://login.salesforce.com
  • In the Selected OAuth Scopes field, select Full Access then click add

6. Now click the save button to save a new connected app.

7. In the Connected Apps list, find the App that you just created, and then click    Manage then click edit.

8.   Now connected app setting should be as in the following image:

 9. Note down the Consumer Key and Consumer Secret, which will be used for the configuration of Credential in S2S Integration.

White List IP address (Org B)

  • To get the access token white list IP  address in destination org
    In the left-hand pane, go to App Setup > Home > Quick Find Box > Profile >  
  •     System AdministratorLogin IP Address > New
  • In the new IP address enter the IP Start address 0.0.0.0 and IP end address 255.255.255

Webservice Class(Org B)

> Now open the developer console in destination org (org B) and write a web service class that consumes JSON and does operation.

/*

Org B (Destination  Org)

Class Name : AccountCreateAPI 

Created By: Aman Maindola

Created Date : 15-12-2021

Description: Integration of two salesforce org, when an account record is created in Org A it will be automatically created in Org B.

*/

@RestResource(urlMapping=’/v1/accountRecordCreate/*’)        

//web service API call  

global class AccountCreateAPI {

    @HttpPost

    global Static string createAccount(){

        try{

            RestRequest req = RestContext.request;

            RestResponse res = Restcontext.response;

            string jsonString=req.requestBody.tostring();

            System.debug(‘JsonString–>>’+jsonString);

            responseWrapperwResp=(responseWrapper) JSON.deserialize(jsonString,responseWrapper.class);

            System.debug(‘WResp–>>’+wResp);

            Account acc=new Account();

            acc.Name=wResp.wName;

            acc.Phone=wResp.wPhone;

            Insert acc;

            System.debug(‘Insert Accounts’ + acc);

            return ‘Success’;

        }catch(Exception e){

            system.debug(‘Error:’+e.getMessage()+’at Line’+e.getMessage());

            return Null;

        }

    }

    @HttpPatch

    global Static string updateAccount(){

        try{

            RestRequest req = RestContext.request;

            RestResponse res = Restcontext.response;

            string jsonString=req.requestBody.tostring();

            System.debug(‘JsonString–>>’+jsonString);

   responseWrapperwResp=(responseWrapper) JSON.deserialize(jsonString,responseWrapper.class);

            System.debug(‘WResp–>>’+wResp);

            Account acc=new Account();

            acc.Name=wResp.wName;

            acc.Phone=wResp.wPhone;

            Update acc;

            System.debug(‘Updated Accounts’ + acc);

            return ‘Success’;

        }catch(Exception e){

            system.debug(‘Error:’+e.getMessage()+’at Line’+e.getMessage());

            return Null;

        }

    }

 @Httpdelete

    global Static string deleteAccount(){

        try{

            RestRequest req = RestContext.request;

            RestResponse res = Restcontext.response;

            string jsonString=req.requestBody.tostring();

            System.debug(‘JsonString–>>’+jsonString);

            responseWrapperwResp=(responseWrapper) JSON.deserialize(jsonString,responseWrapper.class);

            System.debug(‘WResp–>>’+wResp);

            List accList = [Select Id,ExternalId__c From Account where ExternalId__c =: wResp.externalId Limit 1];

            if(accList.size() > 0){

                Delete accList;

                System.debug(‘Deleted Accounts’ + accList);

            }

            return ‘Success’;

        }catch(Exception e){

            system.debug(‘Error:’+e.getMessage()+’at Line’+e.getMessage());

            return Null;

        }

    }  

  public class responseWrapper{

        public string wName;

        public string wPhone;

    }

}

> Now save and start testing by creating a record on Account Object in Source Org. I hope you got it right. 

Conclusion: 

In this digital era, companies look for new ways to stay ahead of their competitors by increasing efficiency and delivering a superior customer experience. To run a business faster and in a scalable way, businesses must integrate in a better way.

The Salesforce integration ensures no data duplication in the systems of your organization. It improves team productivity so that they focus on meaningful tasks. Moreover, without switching systems it allows the employees to access any data from the integrated system. Finally, since it is easy to get information, it helps to analyze data trends for a superior customer experience.

Cloud Analogy, known as the top-notch Salesforce integration partner, will enable you to find effective and top-quality integration solutions for your business. We assure you with world-class Salesforce integration services to transform your business and grow your revenue. Reach out to the Cloud Analogy team and start your project today.

sachin

Sachin Arora

Scrum Master and Principal Solutions Architect
Sachin, a renowned Scrum Master and Principal Solutions Architect at Cloud Analogy, has rich experience when it comes to working on process improvement in a fast-paced environment maintaining high level of quality in all deliverables. Sachin's expertise lies in varied hardware and software environments including Cloud technologies such as Salesforce, AWS, Cloud Foundry & Google App Engine and Mobile.

Hire the best Salesforce Development Company. Choose certified Salesforce Developers from Cloud Analogy now.

× How can I help you?