Ad Code

Responsive Advertisement

Salesforce to Salesforce Integration Using REST API and OAuth

Lets Start with Salesforce to Salesforce Integration Using REST API and OAuth.
Here I wanted to Access the All contacts for an Account From Target Org(2nd Salesforce Org)

Step-1: 

In Source Org Create one Connected App:

Login into Salesforce Sandbox or Salesforce Developer Org
then goto Setup-> App->Connected App
Click New

Change the Oauth CallBack URL according to your instance. Here my instance is "CS30"

https://cs30.salesforce.com/services/oauth2/callback




Then Save it.

After Save you will get Consumer Key & Consumer Secret




After this now we have to Develop one Apex RestService in the Same Source Org.

Step 2: Click on Setup-> Develop->Apex Class
Click New and Save it.
The purpose of this method is to return all contacts related to AccountId

  1. @RestResource(urlMapping='/v1/getContacts/*')
  2.    global with sharing class getContact {
  3.      @Httpget
  4.       global static list<contact> fetchAccount(){
  5.         RestRequest req = RestContext.request;
  6.         RestResponse res = Restcontext.response;
  7.         Id accId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
  8.         list<contact> lstcontact =[Select id , name,Phone,Fax,Email from contact where Accountid=:accId ];
  9.         
  10.         return lstcontact ;
  11.       }
  12.    }
Step-3: Now we have to consume the above Apex Rest Service in Target Salesforce Org.
  1. Login into Target Org
  2. Create new Apex Class "SendAccountUsingRESTAPI " see below
Replace following 4 values in your Apex Class
  • clientId 
  • clientSecret 
  • username 
  • password 
Also Change the Endpoint(line no.18) in which org you are trying to login. means where you have create your Connected App

req.setEndpoint('https://test.salesforce.com/services/oauth2/token');

Also Change the Endpoint(line no.32) in which org you are trying to access all the Contacts. means where you have developed your Apex RestService

String endPoint = 'https://cs30.salesforce.com/services/apexrest/v1/getContacts/' +accId;

APEX CLASS
*********************************************************************
public class SendAccountUsingRESTAPI {
  private final String clientId = 'XXXX1qDQKpai6KLQyEHS3pvpCcteS2b5rWP2A6JpuqP._w2byvgpP8EC56LtyVNOg7.p7';
   private final String clientSecret = '17825308XXX';
   private final String username = 'abaranwal@kloudrac.com.full';
   private final String password = 'XXX';
  public class deserializeResponse
   {
      public String id;
      public String access_token;
   }
  public String ReturnAccessToken (SendAccountUsingRESTAPI 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://test.salesforce.com/services/oauth2/token');
      HttpResponse res = h.send(req);
     deserializeResponse resp1 = (deserializeResponse)JSON.deserialize(res.getbody(),deserializeResponse.class);
     system.debug('@@@@access_token@@'+resp1 );
      return resp1.access_token;
   }
     
   public static list<Contact> callgetContact (String accId)
   {
           SendAccountUsingRESTAPI acount1 = new SendAccountUsingRESTAPI();
           String accessToken;
           accessToken = acount1.ReturnAccessToken (acount1);
           list<Contact> LstContact=new List<Contact>();
           if(accessToken != null){
           String endPoint = 'https://cs30.salesforce.com/services/apexrest/v1/getContacts/' +accId;
           //String jsonstr = '{"accId" : "' + accId+ '"}';
           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.setBody(jsonstr);
           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<Contact> contList=new set<Contact>();
            
            while (parser.nextToken() != null) {
                //Id
                
                if((parser.getCurrentToken() == JSONToken.FIELD_NAME) ){
                    Contact cont;
                    if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'Id')) {
                    // Get the value.
                    parser.nextToken();
                    // Compute the grand total price for all invoices.
                    string sId= parser.getText();
                    cont=new Contact();
                    cont.Id=sId;
                    system.debug('Id@@@' + sId);
                    
                    parser.nextToken();
                    if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && 
                        (parser.getText() == 'Name')) {
                        // Get the value.
                        parser.nextToken();
                        // Compute the grand total price for all invoices.
                        string sName= parser.getText();
                        cont.LastName=sName;
                        system.debug('Name@@@' + sName );
                    }
                    
                    //Email
                    parser.nextToken();
                    if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && 
                        (parser.getText() == 'Email')) {
                        // Get the value.
                        parser.nextToken();
                        // Compute the grand total price for all invoices.
                        string sEmail= parser.getText();
                        cont.Email=sEmail;
                        system.debug('Email@@@' + sEmail);
                    }
                    
                
                }
                contList.add(cont); 
                }
                
                
                
                contList.remove(null);
                
            }
            LstContact.AddAll(contList);
            system.debug('ContList@@@@'+Json.serialize(LstContact));
            
            
           
        
        }
        return LstContact;
   }
   
}



*********************************************************************

Yes now we are ALL set, you can call this  "callgetContact " in your visualforce Controller Class or in your Apex Trigger wherever you wanted to Show the List of Contacts..from Source Org.


Access List of Contact Using Following Syntax

SendAccountUsingRESTAPI.callgetContact('001n0000007lQ90');


Need help, please call me +91-95823-88885 or email me amulhai@gmail.com

Reactions

Post a Comment

48 Comments

  1. Its really good steps to Salesforce to Salesforce Integration Using REST API and OAuth .

    ReplyDelete
  2. Owesome solution with step by step description.

    ReplyDelete
  3. if i want to integration with legacy systm then.....

    ReplyDelete
  4. can u explain integretion with legacy system any one

    ReplyDelete
    Replies
    1. what legacy system you have. we can integrate with java, .net

      Delete
  5. I hope this is the custom REST api, correct me if I'm wrong

    ReplyDelete
  6. hi salesfroce 2 salesfroce integration is paossibke by using REST API. same as one salesforce Organization data integrate with Other Organization not salesforce is it possible.
    if Possible how to do.....

    ReplyDelete
    Replies
    1. I did get your point. If Data Transfer you are looking from org to another Org. use ETL tool or Dataloader CLI.

      Delete
  7. Thanks for sharing the informative post on salesforce integration.

    Salesforce Integration Services

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. Can you please share the visual force code too. thanks

    ReplyDelete
  10. thanks for your information excelllent blog good support for salesforce
    sales force mostly important topices

    ReplyDelete
  11. When we login with user name and password, salesforce also provides a security token string that must be appended to the password. How is that handled here? Should we hardcode that security token in the code? when the password/token changes for the integrated user, the code must be changed??

    ReplyDelete
  12. Hi,
    I am trying to learn integration using the code you provided. However when I try to display contact information from source org in my destination org(using vf page) I get the error :
    Status Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') at input location [1,2]

    02:06:53.0 (8960006)|CALLOUT_REQUEST|[19]|System.HttpRequest[Endpoint=https://ravideepappbuilder-dev-ed.my.salesforce.com/oauth2/token, Method=POST]
    02:06:53.0 (69643751)|CALLOUT_RESPONSE|[19]|System.HttpResponse[Status=Not Found, StatusCode=404]

    I think it means my endpoint url is wrong but I did how it was asked and still doesn't work.Here's my endpoint url:
    https://ravideepappbuilder-dev-ed.my.salesforce.com/oauth2/token

    Can you kindly tell me what is wrong in it or what I am missing.

    ReplyDelete
    Replies
    1. Hi, hope it's resolved for you. if not, let me tell you, you missed to add '/services'. Use below.
      https://ravideepappbuilder-dev-ed.my.salesforce.com/services/oauth2/token

      Delete
  13. Very good and easy understanding, Why cant you add a VF page code as well where all contacts are organized in pageblocktable.

    ReplyDelete
  14. can you please provide the trigger code for callout

    ReplyDelete
  15. Hey, Wow all the posts are very informative for the people who visit this site. Good work! We also have a Website. Please feel free to visit our site. Thank you for sharing.
    Salesforce Services
    Keep Posting:)

    ReplyDelete
  16. For every request, it'll take 2 api calls. 1- get access_token and 2 - get contact. Can we store the access_token in somewhere, check the token valid. if not, we'll refresh the token, if token still valid, we can continue use it.

    ReplyDelete
  17. So nice to read.Its very useful for me to get more valuable info about Medical Billing Coding Service.Thanks for it.Keep going.
    html training in chennai |
    html5 training in chennai |
    html5 courses in chennai

    ReplyDelete
  18. Most of the healthcare institutes are procuring the software packages for their coding and billing process from medical
    Salesforce Training in Chennai |
    Salesforce Training |
    Salesforce Training Institutes in Chennai

    ReplyDelete
  19. how do i create an email escaltion from one URL of salesforce to another ?

    ReplyDelete
  20. Hi, I am trying perform the same as per this post, and my code is also similar except the Parser Instance. But I am getting an error when I tried to run the class through Anonymous window. The error is "System.HttpResponse[Status=Bad Request, StatusCode=400]". Any help would be highly appreciated. Thanks!

    ReplyDelete
  21. Really nice post, Thanks for sharing such an informative post.
    To Create Bulk Fields in Salesforce click this links

    ReplyDelete
  22. I really enjoyed while reading your article and it is good to know the latest updates. Do post more. Please also read my topics about

    Salesforce Products
    Salesforce Consultant
    Salesforce Integration Service

    ReplyDelete
  23. ExpressTech Software Solutions is known as best custom Rest API Integration Services in India, USA, has the best in the industry specialization to deliver seamless API integration and development services. Our system integration services make sure that your web application or website is without flawlessly integrated with the standard or custom APIs.

    ReplyDelete
  24. How to write a test class for above class?

    ReplyDelete
  25. This comment has been removed by the author.

    ReplyDelete
  26. I want to insert those contact records in target org. Please help me out of this.....I need full code for inserting.......

    ReplyDelete
  27. I want to insert these contacts in target org. Please help???

    ReplyDelete

  28. We have prepared Cloud Consultant Sample Paper
    (ADM-201) certification sample questions to make you aware of actual exam properties. http://www.salesforcecertifications.com/ADM201.html

    ReplyDelete
  29. Thanks for the valible information sales force

    Salesforce Billing training india, Salesforce Online training Contact us@ +91 9550102466.

    ReplyDelete
  30. Techforce services is a Salesforce Consulting Services in Australia Specializing in delivering end to end Salesforce solutions ,Consulting, Implementation DevOps partners in Australia We deliver applications and services more rapidly and reliably, but it’s more than a methodology – it cuts to the very core. Salesforce Data Analytics let us help you become a data driven organization and ensure your data is working hard for your business, This includes implemention
    Salesforce consulting companies
    Salesforce top partners
    Staff augmentation companies
    Salesforce DevOps services
    Salesforce integration companies
    Salesforce Implementation services
    Salesforce Health Check
    Salesforce DevOps
    Managed project services

    ReplyDelete
  31. Hello, Amul! Thanks for this helpful article. I also recommend another one: https://skyvia.com/blog/salesforce-to-salesforce-integration, which also talks about Salesforce to Salesforce integration using rest API. I think it complements your guide and shows some other alternative methods.

    ReplyDelete
  32. This comment has been removed by the author.

    ReplyDelete
  33. I appreciate your website. Its really very help full. Thanks for sharing the great information.
    Biobanks| biorepositories
    tissue-bank|human-biospecimens
    human-samples|patient-samples
    human-tissue-samples

    ReplyDelete
  34. Do you want to know about Nina Marie Daniele Net Worth, early life, biography, age, and relationship status?

    ReplyDelete
  35. Streamline operations by integrating two Salesforce instances using REST API and OAuth. Enjoy consistent data, real-time updates, and improved collaboration. how to use watch any nfl game Follow secure authentication steps, map data accurately, and test thoroughly for optimal results. Elevate efficiency and decision-making with this powerful integration

    ReplyDelete
  36. Eye4Future is the best API Integration Services provider in India. our API Integration Services make sure that your website is without perfectly combined with the standard or custom APIs. https://www.eye4future.com/api-integration-services/

    ReplyDelete
  37. Great insights on Salesforce Platform Events! Clear and helpful breakdown. Excited to apply these tips in my projects. Thanks for sharing

    salesforce time tracking

    salesforce timesheet

    Salesforce Time Tracking Integration

    ReplyDelete
  38. Digital Transformation in India: A Landscape of Growth
    India's business landscape is undergoing a rapid digital transformation. Companies are adopting digital transformation services to optimize operations, enhance customer experience and gain a competitive edge. These services encompass a wide range of solutions ranging from cloud migration and data analytics to mobile app development and automation.

    ReplyDelete