Thursday, February 23, 2017

Salesforce to Salesoforce Rest API

===============================
vf page: need to provide username, pwd+securitytoken
==================================

<apex:page controller="othersfaccounts" 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>
==================================================
Integration ccontroller
==================================================

public with sharing class othersfaccounts {

    //Login Domain May be test, prerellogin.pre
    String LOGIN_DOMAIN = 'chitti-sp-testing-dev-ed.my';
    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 othersfaccounts()
    {
        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/37.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/v37.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';
        }

    }
}

Salesforce to salesforce SOAP API

Salesforce Org to Salesforce Org Integration using soap api(Partner wsdl)



Steps:

1) Download the partner wsdl of one org(destination).
setup --> Develop --> api --> Click on Generate Partner WSDL.



Save the file as xml for example partnerwsdl.xml
sample wsdl will be as follows



2)Open another sf org(source).
Goto setup -->develop --> Click on Apex Classes --> click on Generate from WSDl button.


select the downloaded xml file and then click "parse wsdl" button.
It results in generation of four classes.
1)sobjectPartnerSoapSforceCom
2)faultPartnerSoapSforceCom
3)partnerSoapSforceCom
4)AsyncPartnerSoapSforceCom.

3)Now you can interact with partner or destination org as follows.

Open Developer console and place the below code in execute anonymous block.

partnerSoapSforceCom.Soap  s=new partnerSoapSforceCom.Soap ();
String username = 'username';
String password = 'password+securitytoken';

partnerSoapSforceCom.LoginResult lr = s.login(username, password);
s.SessionHeader = new partnerSoapSforceCom.SessionHeader_element();
s.endpoint_x=lr.serverurl;
s.Sessionheader.sessionid = lr.sessionid;
s.getUserInfo();
system.debug('sssssssssssssss'+s.getUserInfo());