Saturday, June 24, 2017

Basics: Rest Api callout(POST) from Salesforce org to different system using OAuth

Problem Statement: Create case in target system using Oauth and update our case field(target_sys_caseNumber) with the response.

To achieve this functionality we have to follow below steps:
1) OAuth token generate
2) Http POST callout to the target system
3) Read the response


public class HttpPostTest{

//STEP 1: OAuth token generator
// This is also an http POST callout
public string oauthGenerator()
{
//For Oauth token endpointURL consists of below things which will be provided by target system
// WEb service URL + Grantype + Client id + client secret
// Below is the sample example
// Taking taking all of these from custom settings

Map<String, Test__c> testVar = Test__c.getAll(); //to get all the URLs from custom settings
    Test__c testV = testVar.get('oAuthToken');
string endpointURL = testV.URL__c + 'grant_type=client_credentials&client_id='+testV.ClientId__c +'&client_secret='+testV.ClientSecret__c;
string oAuthGenToken;

 HttpRequest req = new HttpRequest();
        req.setEndpoint(endpointURL);
        req.setMethod('POST');
   
     
        Http h = new Http();
        HttpResponse res = h.send(req); //Send the request and get the response
        String resp = res.getBody();
     
  // STEP3: There are many ways to get the token from response for eg: JSON.deserialize. here I have used JSON parser to read response fields as Token.
        JSONParser parser = JSON.createParser(resp);
        while (parser.nextToken() != null)
        {
            if(parser.getText() == 'access_token')
            {
                parser.nextToken();
                oAuthGenToken = parser.getText();            
            }
        }

        return oAuthGenToken;
}


//STEP2: Http POST callout to the target system
//This method is similar to the  oauthGenerator() as this is also an http POST callout.
//Have to pass OAuth token in header
//And have to pass payload in body
public void createCase()
{
string caseNumberCreated;
Map<String, Test__c> testVar = Test__c.getAll(); //to get all the URLs from custom settings
    Test__c testV = testVar.get('oAuthToken');
string EndPointURL = testV.URL__c

payload = CreatePayload();  // Sample payload to pass in body
string oAuthToken = oAuthForCSOne();
 
httpRequest req = new httprequest();
http h = new http();
req.setMethod('POST');
req.setEndpoint(finalEndPointURL);
req.setHeader('Content-Type', 'application/json'); //Content-Type depends of expected response if Response is in XML then use Application/XML
req.setHeader('Authorization','Bearer ' +oAuthToken); //setting OAuthToken
req.setHeader('connection', 'keep-alive');
req.setTimeout(60000); //Use this if web service is taking long time(more than 10 secs) to response.
req.setBody(payload);
 
 
httpresponse res = h.send(req); //Send the request and get the response
String resp = res.getBody();

if(resp != null)
{
JSONParser parser = JSON.createParser(resp);
while (parser.nextToken() != null)
{
if(parser.getText() == 'casenumber')
{
parser.nextToken();
caseNumberCreated = parser.getText();            
}

}
}
currentCaseNumber = Apexpages.currentpage().getparameters().get('casenumber'); //getting the casenumber from page URL.
caseData = [select id,target_sys_caseNumber__c from case where casenumber = :currentCaseNumber];
     caseData.target_sys_caseNumber__c = caseNumberCreated;
     update caseData;
}

//Sample Payload
public string CreatePayload(){
 string  samplePayload = '{'+
            '"caseCreateInfo": {'+
            '"CaseNumber": "0003600"'+
'}'+
            '}';
     
        return payload;
    }
}

P.S. This blog is just for basic functionality.