Ever Wondered How to Connect Salesforce to Salesforce using Apex WebServies? Now you're at right Place.

In this Post we talk about following points, As we talk more about two Salesforce Orgs I will say one Org as Source Org and other as Destination Org

  1. WebService - Assuming you Created a Webservice in any Source Org, Let's say it as BU1_Service.(If you need help on Webservices click here)

  2. Partner WSDL - Now you need to generate Partner WSDL from Source Org from Setup ->Develop -> API -> Generate Partner WSDL Click 'Generate Partner WSDL' save it as WSDL/XML, Lets say it as BU1_Partner_sforce
    NOTE: Why to Generate Partner WSDL here? you cannot directly access salesforce Objects/records directly you need to be authenticated, so we will use Partner WSDL.

  3. Destination Org - Now move to Destination Org, Here we need to Invoke Webservice in two Steps,

    a) Invoke WSDL which we generated `BU1_Partner_sforce` in STEP 2 in Order to get SessionId as shown
    BU1_Partner_sforce.Soap pService = new BU1_Partner_sforce.Soap();
    BU1_Partner_sforce.LoginResult partnerLoginResult = pService.login('username@domain.demo', 'Password');
    // In your Case Pass actual salesforce org credentials above as Paramerts
    ```</ol><ol>		
    	<b>b)</b> Now Invoke WebService `BU1_Service` you Created in <b>STEP1</b> Pass <b>SessionId</b> as shown
    ```java
    
    // Pass Above Generated WSDL SessionId to WebService Header Element as shown
    BU1_Service.SessionHeader_element wsHeader = new BU1_Service.SessionHeader_element();
    wsHeader.sessionId = partnerLoginResult.sessionId; // passing SessionId
    
    // Pass Above 'SessionHeader_element' => wsHeader to WebService as shown
    BU1_Service.Service_AppExchangeInfo s = new BU1_Service.Service_AppExchangeInfo();
    s.SessionHeader = wsHeader; // Assigning header 
    
Thats! it Now Invoke your Webservice `BU1_Service` methods just like normal Apex Methods as `s.();` here `s` is instance of `BU1_Service` webService (which we initialise above)

Happy Coding! if you find Difficulty Please comment