Thursday, 26 November 2015

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

30 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 a blog administrator.

    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
  13. I acknowledge the author for his brilliant work for making this exceptionally useful and informative content to guide us.
    salesforce integration

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

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

    ReplyDelete
  16. 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
  17. 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
  18. 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
  19. 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
  20. how do i create an email escaltion from one URL of salesforce to another ?

    ReplyDelete
  21. 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
  22. Thank you for sharing such great information very useful to us.
    Salesforce Training in Gurgaon

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

    ReplyDelete
  24. 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
  25. 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

lightning:pillContainer and dialog(openModel or openPopup)

lightning:pillContainer and dialog(openModel or openPopup) AddAttendees.cmp <aura:component controller="AddAttendeesCo...