[SalesForce] how to create an incident in serviceNow from salesforce(Case)

I'm trying to integrate salesforce and serviceNow. If I create a new case in salesforce, that should be saved as incident in serviceNow.

Here I developed some code but I'm stuck at mapping the salesforce case fields with serviveNow incident fieds.

Public with sharing class OutboundMsg {


    public static void servicenowPost(){  

        Http http = new Http();
        HttpRequest req =  new HttpRequest();
        HttpResponse res = new HttpResponse();

         String username = 'admin';
         String password = '$Test12345';

        Blob headerValue = Blob.valueOf(username + ':' + password);
        String authorizationHeader = 'BASIC ' +
        EncodingUtil.base64Encode(headerValue);
        req.setHeader('Authorization', authorizationHeader);



        req.setEndpoint('https://dev23577.service-now.com/');
        req.setMethod('POST');
        req.setHeader('Content-Type', 'application/x-www-form-urlencoded'); 



        //Id caseId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
      //  Case c = new Case(subject='',status='new',origin='web');
        //insert c;
       // req.setBody('c');

       // Create a new http object to send the request object
       // A response object is generated as a result of the request  


        res = http.send(req);
        System.debug(res.getBody());


   }
}

How can I establish the mapping between salesforce and serviceNow?

Best Answer

The ServiceNow API accepts json/xml you'll have to change your content-type to application/json and create the mappings in a json format. You can use the JSON Generator to build your request.

Here's a quick example:

Apex Class

@future
public static void servicenowPost(Case incidentCase){  

Http http = new Http();
HttpRequest req =  new HttpRequest();
HttpResponse res = new HttpResponse();

String username = 'admin';
String password = '$Test12345';

Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'BASIC ' +
EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authorizationHeader);

req.setEndpoint('https://dev23577.service-now.com/');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');

JSONGenerator gen = JSON.createGenerator(true);
gen.writeStartObject();

//you can add as many mappings as you want
gen.writeStringField('servicenowField', incidentCase.field);
gen.writeEndObject();

//you can now use String pretty as your body
String pretty = gen.getAsString();

req.setBody(pretty);
HttpResponse res = http.send(req);

system.debug(res.getBody());
}

Trigger:

trigger servicenow on Case (after insert){
for(Case c : Trigger.New){                                                  
  nameofyourcalloutclass.servicenowPost(c);                                                                          
  }
}
Related Topic