Creating Web-services in Salesforce

Salesforce : Calling from another Salesforce System

Recently I had a requirement where one of my client wanted to interact with their Salesforce org to insert some information in their org from another salesforce, and they wanted it through web-services. This post will cover what I have learned in regards to web-services with this requirement and what steps I had taken for this.

Target Org : SetUp

Creating Web Services in Force.com is as simple as creating an Apex class. Here is an Example:

global class WebServiceContact {
    webservice static string createContact(String contactLastName) {
        try {
            Contact c = new Contact(lastName = contactLastName);
            insert c;
            return c.id;
        }catch(System.Exception e) {
            System.debug('Callout error: '+ e);
            return 'Server Error...';
        }
    }
}

Generate and Download WSDLs with below steps
To get your org-specific WSDLs see below Steps.
1. Go to Apex class for Quick Search.
2. Select Specific class and Click on Generate WSDL button.
3. Generate Apex class from WSDL (Apex Class Page have "Generate from WSDL" button).
4. Use this class for Request and Response form Any External system.
Now that your environment is ready to go, for request from another System. This is all about source org SetUp.
Note : For Web Service we have to use on Authorization Process to execute. We are use ConnectedApp for this so create one connectedApp in Target Org

Source Org : SetUp

For WebService Request we will create one Util Class in Target Org (Salesforce)

//Authorization to Source Org using ConnectedApp
public class RequestToWebservice{
    public static string getAccessToken(){
        string username= USER_NAME_SOURCE_ORG;
        string password = PASSWORD_SOURCE_ORG;
        string clientId = CLIENTID_SOURCE_ORG;;
        string clientSecret= CLIENT_SECRET_SOURCE_ORG;
                    
        String body ='grant_type=password&client_id=' + clientId +'&client_secret=' + clientSecret +'&username=' + EncodingUtil.urlEncode(username, 'UTF-8') +'&password='+EncodingUtil.urlEncode(password, 'UTF-8');
        
        string urlStr = 'https://login.salesforce.com/services/oauth2/token';
        
        HttpRequest req = new HttpRequest();
        req.setHeader('accept','application/json');
        req.setEndpoint(urlStr);
        req.setBody(body);
        req.setMethod('POST');
        Http http = new Http();
        HTTPResponse res = http.send(req);
        Map accessResult = (Map) JSON.deserializeUntyped(res.getBody());
        system.debug('accessResult '+accessResult);
        string accessToken=accessResult.get('access_token')+'';
        system.debug(accessToken);
        return accessToken;
    }
//Request to WebService 
    public static void sentRequest(){
        string accessToken=getAccessToken();
        if(accessToken != null){           
            String strEndpoint = URL_OF_WEBSERVICE_OR_SOURCE_ORG
            
            String request = '<!--xml version="1.0" encoding="UTF-8"?-->';
            request+='<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
            request+=   '<env:Header>';
            request+=       '<SessionHeader xmlns=" URL_OF_WEBSERVICE_OR_SOURCE_ORG">';
            request+=           '<sessionId>'+accessToken+'</sessionId>';
            request+=       '</SessionHeader>';
            request+=     '</env:Header>';
            request+=     '<env:Body>';
            request+=     '<createContact xmlns="URL_OF_WEBSERVICE_OR_SOURCE_ORG">';
            request+=       '<contactLastName>AccessTokenTest</contactLastName>';
            request+=       '</createContact>';
            request+=           '</env:Body>';
            request+='</env:Envelope>'; 
            
            Http h = new Http();
            HttpRequest req = new HttpRequest();
            req.setMethod('POST');
            req.setHeader('SOAPAction',URL_OF_WEBSERVICE_OR_SOURCE_ORG(WITHOUT HTTPS));
            req.setHeader('Content-Type','text/xml;charset=UTF-8');
            req.setBody(request);
            req.setEndpoint(strEndpoint);
            
            string bodyRes = '';
            
            try {
                
                HTTPResponse res = h.send(req);
                System.debug('Response:' + res.getStatusCode());
                bodyRes = res.getBody();
                System.debug('bodyRes: '+ bodyRes);
                String parsedRes = parseResponse(bodyRes);
                System.debug('@#@# ' + parsedRes);                
            }catch(System.CalloutException e) {
                System.debug('Calloutor: '+ e);
            }
        }

    }
//Parse SOAP XML
    public static string parseResponse(String res){
        Dom.Document doc = new Dom.Document();
        doc.load(res);
        String createContactResponse ='';
        for(Dom.XmlNode node :doc.getRootElement().getChildElements()){
            system.debug('node.getName()' + node.getName());
            if(node.getName() == 'Body'){
                
                for(Dom.XmlNode node2: node.getChildElements()){
                    system.debug('node2.getName()' + node2.getName());
                    if(node2.getName() == 'createContactResponse'){
                        for(Dom.XmlNode node3: node2.getChildElements()){
                            if(node3.getName() == 'result'){
                                system.debug('node3.getName()' + node3.getName());
                                system.debug('node3.getText()' + node3.getText());
                                if(String.isNotBlank(node3.getText())){
                                    createContactResponse  = node3.getText();
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        return createContactResponse;
    }
}

Thanks to my coworker and Friend @ Anirudh Mathur for help me out in research.

Happy Sharing...

Everyone has their own favorites, so please feel free to share yours in the comments below!

Comments

  1. Great work...keep it going

    ReplyDelete
  2. Can you please publish some component related to Lightning web component ?

    ReplyDelete

Post a Comment

Popular posts from this blog

Salesforce LWC : Compact Layout on Hover

Salesforce LWC With Third Party JS : D3

Communications between Lightning Components : Salesforce