Getting record from other Salesforce organization OR communication between multiple salesforce organization

In this article, I will explain the code which can be used for connecting and getting the records from different or multiple salesforce organization using Apex and REST Service.

Note : Here is new article to connect two salesforce instances in just 5 lines of code using Named Credentials.

To start first we will need to authorize below two URL which can be accessed from salesforce environment.
This can be done from “Setup | Administration Setup | Security Controls | Remote Site Settings”

  1. https://www.salesforce.com
  2. https://ap1-api.salesforce.com
Salesforce Remote Site Setting
Salesforce Remote Site Setting


It is possible that you may need to change first URL it may be https://www.na1-api.salesforce.com or https://www.na2-api.salesforce.com

This application will prompt for the Username and Password of the other salesforce account and display the 10 records of the Account.

Connect Other Salesforce Account - Output Screen
Connect Other Salesforce Account – Output Screen

Apex Code:

public with sharing class FetchAccount {

    //Login Domain May be test, prerellogin.pre
    String LOGIN_DOMAIN = 'www';
    public String pwd{get;set;}
    public String userName{get;set;}
    public List<Account> acc{get;set;}
    public String errMsg{get;set;}
    public String displayError{get;set;}

    public FetchAccount()
    {
        displayError = 'none';
    }

    public void fetch()
    {
        errMsg  = 'Some error occurred, please try again';
        try
        {
        //-----------------------------------
        // Login via SOAP/XML web service api
        //-----------------------------------
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://' + LOGIN_DOMAIN + '.salesforce.com/services/Soap/u/22.0');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'text/xml;charset=UTF-8');
        request.setHeader('SOAPAction', '""');
        //not escaping username and password because we're setting those variables above
        //in other words, this line "trusts" the lines above
        //if username and password were sourced elsewhere, they'd need to be escaped below
        request.setBody('<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"><Header/><Body><login xmlns="urn:partner.soap.sforce.com"><username>' + userName+ '</username><password>' + pwd+ '</password></login></Body></Envelope>');
        Dom.XmlNode resultElmt = (new Http()).send(request).getBodyDocument().getRootElement()
          .getChildElement('Body', 'http://schemas.xmlsoap.org/soap/envelope/')
          .getChildElement('loginResponse', 'urn:partner.soap.sforce.com')
          .getChildElement('result', 'urn:partner.soap.sforce.com');

        //-------------------------------
        // Grab session id and server url
        //--------------------------------
        final String SERVER_URL = resultElmt.getChildElement('serverUrl', 'urn:partner.soap.sforce.com') .getText().split('/services')[0];
        final String SESSION_ID = resultElmt.getChildElement('sessionId', 'urn:partner.soap.sforce.com') .getText();

        //----------------------------------
        // Load first 10 accounts via REST API
        //---------------------------------
        final PageReference theUrl = new PageReference(SERVER_URL + '/services/data/v22.0/query/');
        theUrl.getParameters().put('q','Select a.Phone, a.Name, a.CreatedBy.FirstName, a.CreatedById From Account a limit 10');
        request = new HttpRequest();
        request.setEndpoint(theUrl.getUrl());
        request.setMethod('GET');
        request.setHeader('Authorization', 'OAuth ' + SESSION_ID);

        String body = (new Http()).send(request).getBody();

        JSONParser parser = JSON.createParser(body);

        do{
            parser.nextToken();
        }while(parser.hasCurrentToken() && !'records'.equals(parser.getCurrentName()));

        parser.nextToken();

        acc = (List<Account>) parser.readValueAs(List<Account>.class);
        }
        catch(Exception e)
        {
            displayError = 'block';
        }

    }
}

Visualforce Code:

<apex:page controller="FetchAccount" standardStylesheets="true">
<style type="text/css">
.errorMsg{
    font-size:0.8 em;
    color:red;
}
</style>
<apex:pageBlock >
<apex:form >
<apex:outputLabel value="UserName : " for="userName"/>
<apex:inputText required="true" id="userName" value="{!userName}" />
<br />
<apex:outputLabel value="Password : " for="pwd"/>
<apex:inputsecret id="pwd" value="{!pwd}"/>
<br />
<apex:commandButton id="getRecords" value="Get Records" action="{!fetch}" rerender="wrapper" status="waitStatus" />
<apex:actionStatus startText="Requesting..." stopText="" id="waitStatus"/>
<hr />
<apex:outputPanel id="wrapper">
<div class="errorMsg" style="display:{!displayError}"> {!errMsg} </div>
<apex:pageBlockTable value="{!acc}" var="account" id="accTable" rowClasses="odd,even" styleClass="tableClass">

    <apex:column >
        <apex:facet name="header">Account Name</apex:facet>
         <apex:outputText value="{!account.name}"/>
    </apex:column>

    <apex:column >
        <apex:facet name="header">Created By</apex:facet>
         <apex:outputText value="{!account.CreatedBy.FirstName}"/>
    </apex:column>

    <apex:column >
        <apex:facet name="header">Phone</apex:facet>
         <apex:outputText value="{!account.Phone}"/>
    </apex:column>

</apex:pageBlockTable>
</apex:outputPanel>
</apex:form>
</apex:pageBlock>
</apex:page>

Posted

in

, , ,

by


Related Posts

Comments

70 responses to “Getting record from other Salesforce organization OR communication between multiple salesforce organization”

  1. Arunarapolu Avatar
    Arunarapolu

    Hi ,
     
    I was trying this example in my personal environment , but i am getting below exception
     
    16:45:22:037 EXCEPTION_THROWN [23]|System.CalloutException: Unauthorized endpoint, please check Setup->Security->Remote site settings. endpoint = https://www.salesforce.com/services/Soap/u/22.0
     
    In Remote settings  under site url ” https://www.na14-api.salesforce.com” for salesforce login
    and for api https://ap14-api.salesforce.com  or https://ap1-api.salesforce.com also tryed both.

    could you please tell me why i am getting unauthorized endpoint.

  2.  Avatar
    Anonymous

    Hi,
    Please add “https://www.salesforce.com” in remote site. Let me know if you face error.

    Regards,
    Jitendra Zaa

    1. siva Avatar
      siva

      SAME ERROR IS FACING GIVING REMOTE SITE As you said

    2. Ramadhar Mishra Avatar
      Ramadhar Mishra

      I’m also trying to run same example in my dev org. I’ve added following Remite site sessings urls.

      1) https://www.salesforce.com

      2)https://ap1-api.salesforce.com

      3)https://www.na5-api.salesforce.com

  3.  Avatar
    Anonymous

    sir i want to hello world program plz send mail

    1.  Avatar
      Anonymous

      Hello world program of what?
      if you are talking about the salesforce tutorial from starting then this article might be very useful to you.
      https://jitendrazaa.com/blog/salesforce/step-by-step-salesforce-tutorial-creating-custom-object-1-of-n/

      Regards,
      Jitendra Zaa

      1. Sukumar Avatar
        Sukumar

        iam trying to (selected check list lead ids ,text field  have  ( i
        written something  the text field)     message will be sent  the
        particular lead emails) how to solve plz tell me……… but the error
        occured

        public class leadmails {

           
        public leadmails()
        {
        }

        private final List leadids;
          public List ld;
          public leadmails(ApexPages.StandardController controller)
          {
             ld = [select Id from lead limit 10 ];
             for(Integer i=0;i<10;i++)
             {
                 leadids.add(ld[i].Id);
              } 
          }

           
        public class leadwrap
        {

        public ID id;
        public string lname{get;set;}
        public string company{get;set;}
        public string email{get;set;}
        public boolean check{get;set;}
        public string emailtext{get;set;}
        }
         list lw = new list();
         public list getinfo()
         {
         list ls=[select id,name, Company,email,emailtext__c from lead];
         for(lead l:ls)
         {
         leadwrap w = new leadwrap();
         w.id=l.id;
         w.lname=l.name;
         w.company=l.company;
         w.email=l.email;
         w.emailtext=l.emailtext__c;
         lw.add(w);
         }
         return lw;
         }
         list dlist=new list();
         lead le;
         public pagereference send()
         {
         for(leadwrap lp:lw)
         {
         if(lp.check == true)
         {
         le=[select id from lead where id=:lp.id];
         dlist.add(le);
         }
         }
         update dlist;
         
         pagereference pr= page.leadmail;
         pr.setredirect(true);
         return pr;
         
         
          
         
         Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
               mail.setTargetObjectIds(leadids);
               mail.setTemplateId(”);
              Messaging.SendEmailResult [] r =  Messaging.sendEmail(new Messaging.massEmailMessage[] {mail});
        return null;

               }

  4. Sukumar Avatar
    Sukumar

    iam trying to (selected check list lead ids ,text field  have  ( i written something  the text field)     message will be sent  the particular lead emails) how to solve plz tell me……… but the error occured

    public class leadmails {

       
    public leadmails()
    {
    }

    private final List leadids;
      public List ld;
      public leadmails(ApexPages.StandardController controller)
      {
         ld = [select Id from lead limit 10 ];
         for(Integer i=0;i<10;i++)
         {
             leadids.add(ld[i].Id);
          } 
      }

       
    public class leadwrap
    {

    public ID id;
    public string lname{get;set;}
    public string company{get;set;}
    public string email{get;set;}
    public boolean check{get;set;}
    public string emailtext{get;set;}
    }
     list lw = new list();
     public list getinfo()
     {
     list ls=[select id,name, Company,email,emailtext__c from lead];
     for(lead l:ls)
     {
     leadwrap w = new leadwrap();
     w.id=l.id;
     w.lname=l.name;
     w.company=l.company;
     w.email=l.email;
     w.emailtext=l.emailtext__c;
     lw.add(w);
     }
     return lw;
     }
     list dlist=new list();
     lead le;
     public pagereference send()
     {
     for(leadwrap lp:lw)
     {
     if(lp.check == true)
     {
     le=[select id from lead where id=:lp.id];
     dlist.add(le);
     }
     }
     update dlist;
     
     pagereference pr= page.leadmail;
     pr.setredirect(true);
     return pr;
     
     
      
     
     Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
           mail.setTargetObjectIds(leadids);
           mail.setTemplateId(”);
          Messaging.SendEmailResult [] r =  Messaging.sendEmail(new Messaging.massEmailMessage[] {mail});
    return null;

           }
           }

    1. JitendraZaa Avatar
      JitendraZaa

      Hi,
      What actually you are trying to achieve and what error you are getting?

      1. Sukumarmalladi22 Avatar
        Sukumarmalladi22

         hi
        error is     Illegal assignment from LIST to LIST
        Error occurred
        loading controller ‘leadmails’ for page leadmail

        and my requirment is like  selected check list lead ids ,text field  have  ( i written something 
        the text field)     message will be sent  the particular lead emails)
        how to solve plz tell me……… but the error occured

  5. Milan Sanghani Avatar
    Milan Sanghani

    hi,
    Can we access junction object record from one org to another org using this Rest Api.

    1. JitendraZaa Avatar
      JitendraZaa

      Yeah.. With help of REST API.. you can do it

  6. Vikram Avatar
    Vikram

    HI, how do I soap Login in customer portal….

    Its Urgent

  7. saurabh Avatar
    saurabh

    How can I get access token for rest api using window phone .net4.5 vs2012

  8. Amit Avatar
    Amit

    Hi.. This is wonderful and very helpful post. I have tried this and it works like a charm. Thanks a bunch for this post… I have one question here, Can we use this rest api to send attachments from one SF org to other same like what have you done with Accounts?

    1. JitendraZaa Avatar
      JitendraZaa

      Yes we can

      1. Amit Avatar
        Amit

        Could you please provide me the example of the same.

      2. sudha Avatar
        sudha

        hi i m getting error like

        Some error occurred, please try again

        pls help me out

    2. NewBee Avatar
      NewBee

      Hello @disqus_YusS9Xpwpw:disqus ,

      Can you please guide if it is possible to move few content files from one SF org to other?

  9. Alex Avatar
    Alex

    Do the remote site details need to be configured on in the Salesforce instance that is requesting or giving the records?

  10. JitendraZaa Avatar
    JitendraZaa

    Have you tried to adding Salesforce.com also in Remote Site Setting?

  11. sunil Avatar
    sunil

    Unknown property ‘account.name’ im getting this error

  12. kapil p Avatar
    kapil p

    Hi , Above code not working for me…
    I am getting error…”Some error occurred, please try again”

    Regrads-
    Kapil

  13. kapil p Avatar
    kapil p

    Hey As a password filed need type only password OR Password+Security Token.

  14. hareesh Avatar
    hareesh

    thanks its working for me

  15. aritra mukherjee Avatar
    aritra mukherjee

    excellent 😀 @JitendraZaa:disqus

    1. JitendraZaa Avatar
      JitendraZaa

      Thanks Bhai..

      1. hareesh Avatar
        hareesh

        How we will get more than one organization data lets say…
        We have 3 different sales force account (Org1, Org2, Org3)…
        Want to acccess all three data at a time…?

      2. hareesh Avatar
        hareesh

        Dynamic dependent pick list using apex : i created one Location__c object in that i Created two Pick Lists Country__c and State__c in Country__c pick list i added India,pakistan valus and in state__c pick list i added Andrapradesh,Madhyapradesh,lohore,Quetta if i select a value as India from Country__c pick list in State__c only able to see Andrapradesh,Madhyapradesh if i select a value as pakistan from country_c picklist in state__c only able to see lohore,Quetta by using apex

  16. Guest Avatar
    Guest

    How we will get more than organization data lets say…
    We have 3 different sales force account (Org1, Org2, Org3)…
    Want to acccess all three data at a time…?

    Thanks in advance…. Kapil

  17. kapil p Avatar
    kapil p

    How we will get more than one organization data lets say…
    We have 3 different sales force account (Org1, Org2, Org3)…
    Want to acccess all three data at a time…?

    Thanks in advance…. Kapil

  18. hareesh Avatar
    hareesh

    how to geti multiple organizations data at a time

  19. hareesh Avatar
    hareesh

    How we will get more than one organization data lets say…
    We have 3 different sales force account (Org1, Org2, Org3)…
    Want to acccess all three data at a time…?

  20. Vishal Avatar
    Vishal

    Hey first of all, congrats for putting up an excellent tutorial.

    Two questions:
    1) Are the remote site settings going to be same once we set it?
    2) How can be insert multiple records to other org via just one http callout since there is restriction on number of callouts?

    Appreciate your response.

    – Vishal

  21. Ankush Somani Avatar
    Ankush Somani

    can you tell me how to invoke apex class method of one org from another org. ?

  22. oo Avatar
    oo

    I’m getting an error because of the SFDC instance.

    On one of my orgs , I have na11 so I added an endpoint to it. But I have another on na17 and it doesn’t works when try to do the httprequest to na17.

    Is there a way to fix this without creating an endpoint for each possible instances?

    Thanks in advance

    1. JitendraZaa Avatar
      JitendraZaa

      What error you are getting ? Have u added na17 in remote site setting ?

      1. oo Avatar
        oo

        Thanks for your quick response! I’ve added it and it’s working now.

        But I think it will fail again if the instance change to another one (suppose na16).

        I was wondering if there is a way to prevent that, without adding one site setting for each of the possible instances (na1 to na21 & cs1 to cs32)

        1. JitendraZaa Avatar
          JitendraZaa

          It’s actually security in salesforce that you cannot connect to external websites if its not added in remote settings. So no way to bypass .

          1. oo Avatar
            oo

            ok, thank you, and great post!

          2. Muneendar Avatar
            Muneendar

            can u please provide step by step document.Send the mail

            “muneendar.sforce@gmail.com”

  23. Ravi Avatar
    Ravi

    I am getting below problem
    System.HttpRequest[Endpoint=https://www.salesforce.com/services/Soap/u/22.0, Method=POST]
    15:01:47.804 (804200848)|CALLOUT_RESPONSE|[33]|System.HttpResponse[Status=Server Error, StatusCode=500]

  24. raju Avatar
    raju

    Hi,
    How to move one Data to another org using apex in salesforce?

    thanks,

  25. raju Avatar
    raju

    Hi,
    How to move one Organization Data to another organization using apex in salesforce?
    Example:Account
    thanks,

  26. Chethan Jagan Avatar
    Chethan Jagan

    This does not work dude 🙁

    1. Jitendra Zaa Avatar

      What error you are getting?

      1. Chethan Jagan Avatar
        Chethan Jagan

        it simply doesnot fetch account details…even after proving the correct username and password 🙁
        it says – Some error occurred, please try again. Please help.

        1. Chethan Jagan Avatar
          Chethan Jagan

          Jitendra – You know why is it not fetching the records?

      2. Chethan Jagan Avatar
        Chethan Jagan

        You know why is it not fetching the records?

  27. Nilesh Avatar
    Nilesh

    Is there any limitation for the number of times we can call? like normal API limit is 15000/day

  28. Kruti Avatar
    Kruti

    It’s working without any issues…and fetching Account records too, but while I am trying to fetch other object records like contact am not able to get, please help, and one more request can you please show how can we fetch multiple object records at a time..

    Thank you
    Kruti

    1. Jitendra Zaa Avatar

      Hi Kruti, are you able to fetch contact from normal SOQL query ? also, please check this new blog with less code – https://www.jitendrazaa.com/blog/salesforce/salesforce-to-salesforce-integration-using-named-credentials-in-just-5-lines-of-code/

    2. Sukanya Gade Avatar
      Sukanya Gade

      Can U Share Ur Files With Me Please

  29. kullai Avatar
    kullai

    Throwing this Error ,Find below Attached Please Help To me

    1. Jitendra Zaa Avatar

      Can you check developer console to get exact error detail or you can try this other approach – https://www.jitendrazaa.com/blog/salesforce/salesforce-to-salesforce-integration-using-named-credentials-in-just-5-lines-of-code/

      1. NewBee Avatar
        NewBee

        Hello @JitendraZaa:disqus

        I am getting the same error.
        Getting error at 67-Attempt to dereference a null object
        System.HttpResponse[Status = server error,Status code=500]
        Please help

  30. Poonam Agarwal Avatar
    Poonam Agarwal

    I am getting below error message..please help
    (17114034)|CALLOUT_REQUEST|[76]|System.HttpRequest[Endpoint=https://www.salesforce.com/services/Soap/u/22.0, Method=POST]
    10:32:57.0 (496655457)|CALLOUT_RESPONSE|[76]|System.HttpResponse[Status=Server Error, StatusCode=500]

  31. Mallikarjun kaparthi Avatar
    Mallikarjun kaparthi

    I tried to access the visual force page form one dev org to other org. I have downloaded the prtner wsdl for org1 and generated the apex class from wsdl file in org2. So I can able to login using login call in the apex class. I got he session URL and sessionID. Now i need to access the vf page in org1 to org2. May i know how i can use the sessionid generated while making login call. I was added the org1 vf page in the iframe which is org2. Please help me on the approach.

  32. Montosh Avatar
    Montosh

    Hi..Is it possible to perform update on the fetched data from external system without SAVING the same in salesforce and sending the updates back to the external system by using web service callout?

  33. Raghu Avatar
    Raghu

    Hi @JitendraZaa:disqus

    Thanks again for the wonderful post. Your posts are really very knowledgable and very helpful in polishing the technical skills.

    I was playing around with some deep concepts of REST web services. I found that we can’t fetch more then 2000 records. To overcome this I tried using “NextRecordsUrl” to fetch all records greater than 2000 and I am facing some challenges in that.

    Just wanted to know if you have some sample snippet to share with which we can fetch more than 2000 records using REST API.

    Regards

  34. Bhuvnesh Maheshwari Avatar
    Bhuvnesh Maheshwari

    Hi @JitendraZaa:disqus ,
    I want to login into another org using REST API without creating connected Apps.
    Is there any possible way to achieve this?

  35. bhanu Avatar

    Hi Jitendra Zaa,

    I have tried to connect org using above snippet
    getting error that : Some error occurred, please try again
    Tried using couple of orgs facing same issue for every org.

  36. PP Avatar
    PP

    followed the same steps and all alternate options but Getting error – System.CalloutException: Unexpected end of file from server.
    Please Guide..

  37. mitsviki Avatar

    I have TWO logins one for USA and one for CAN. A case gets created in CAN, somehow should be created/shared to USA instance. how is this possible using the above? please advice.

  38. Sai Avatar
    Sai

    Hi, Thank you very much and it is working fine. I am getting the records from one to org to other org. Now I want to get these records to be inserted into the object. Please let me know how?

  39. Sai Avatar
    Sai

    Hi ,

    In the above code, we are able to get the records from account object and only for some fields.Could you please let me know on how to get all the fields of the account object with the above code.

    Thank you.

  40. Pulkit Sharma Avatar
    Pulkit Sharma

    Hi Jitendra,

    I have implemented following process in my 2 orgs.
    1. Service Provider Org – https://n26developerorg-dev-ed.my.salesforce.com
    >> I have created Connected App in this org.
    >> This contains my Accounts
    2. IDP – https://pulkitsharma1313-dev-ed.my.salesforce.com
    >> I have created Auth Provider & Named Credentials & Remote Site Settings here
    >> I want to fetch accounts in this org.
    3. I have implemented above code and getting following error:-
    System.CalloutException: Unable to tunnel through proxy. Proxy returns “HTTP/1.1 503 Service Unavailable”

    I have added IP Ranges as well and added Security Token in Password before submitting fetch button.
    Please help!!

  41. Pulkit Sharma Avatar
    Pulkit Sharma

    Hi Jitendra,
    I tried above steps and did following in my 2 dev orgs
    1. Service Provider – https://n26developerorg-dev-ed.my.salesforce.com
    >> Created Connected App
    >> Contains Account Data

    2. IDP – https://pulkitsharma1313-dev-ed.my.salesforce.com
    >> Created Auth Provider, Named Credentials & Remote Site Settings
    >> In Remote Site Setting – Added above SPs URL
    >> Want to Fetch Account Data from above SP org.

    3. Used the same class and VF Page, but getting following error:-
    >> NOTE:- Used Username & Password with Security Token
    Error – System.CalloutException: Unable to tunnel through proxy. Proxy returns “HTTP/1.1 503 Service Unavailable”

    Please help!!

    Thanks,

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading