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 = '';
request+='';
request+= '';
request+= '';
request+= ''+accessToken+' ';
request+= ' ';
request+= ' ';
request+= '';
request+= '';
request+= 'AccessTokenTest ';
request+= ' ';
request+= ' ';
request+=' ';
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.
Great work...keep it going
ReplyDeleteThis comment has been removed by the author.
DeleteThanks :)
DeleteCan you please publish some component related to Lightning web component ?
ReplyDeleteThanks for Suggestion I will do ASAP...
Delete