Wednesday, January 9, 2019

Salesforce rest api integration to create a record in external system using HTTP POST

Let say I have two salesforce org, ORG A and ORG B.

Our requirement is whenever an account record is inserted in ORG A , Same record should be automatically created in ORG B if the account type is "Prospect".

Let's start,

ACTIVITIES WE NEED TO DO IN ORG B.

1) Create a connected app.
2) Rest api webservice in ORG B to create account record in ORG B.

1) WHAT IS CONNECTED APP IN SALESFORCE?

For an external application that needs to authenticate with salesforce application, we need to create a connected app so as to inform about the new authentication entry point. Connected app uses standard OAuth 2.0 protocol to authenticate.

Salesforce rest api integration to create a record in external system using HTTP POST


Note down the Consumer key, Consumer secret(We need to provide it ORG A for authentication purpose along with username, password, security token of the user which ORG A will be using for authentication).

2) REST API WEBSERVICE:

@RestResource(urlMapping='/createAccountRecord/*')

   global with sharing class createAccountRecord {

     @HttpPost

      global Static string createAccount(){

      RestRequest req = RestContext.request;

      RestResponse res = Restcontext.response;

      string jsonString=req.requestBody.tostring();

      system.debug('jsonString'+jsonString);

      boolean successCheck;

      List<responseWrapper> wRespList=(List<responseWrapper>) JSON.deserialize(jsonString,List<responseWrapper>.class);

      Account obj=new Account();

      List<Account> accList= new List<Account>();

      for(responseWrapper wResp: wRespList){

      obj.Name=wResp.Name;

      obj.Description=wResp.Description;

      obj.Type=wResp.Type;

      obj.Industry=wResp.Industry;

      accList.add(obj);

      }

      try{

      if(accList.size() > 0){

      Insert accList;

      successCheck=true;

      }

      }

      catch(Exception e){

      successCheck=false;

      }

      if(successCheck)

      return 'Success';

      else

      return 'Failure';

      }

      global class responseWrapper{

       global string Name;

       global string Description;

       global string Type;

       global string Industry;

      }

   }



ACTIVITIES WE NEED TO DO IN ORG A.

1) Create an apex trigger and apex controller.
2) Create a remote site setting for the URL of ORG B.

Create a custom metadata to store the username, password, Consumer key, Consumer secret provided by ORG B as shown below.

Note: The password will be combination of password and security token.

Salesforce REST API create record

Now, create a record under the above custom metadata as shown below.

Salesforce REST API POST example

APEX TRIGGER IN ORG A:

trigger Accounttrigger on Account (after insert) {
    Set<id> accIdSet=new Set<id>();
    for(Account acc:trigger.new){
        if(acc.name!=Null){
            accIdSet.add(acc.id);
        }
    }
    if(accIdSet.size() > 0){
        callWebserviceClass.getConList(accIdSet);
    }
}

CREATE AN APEX CONTROLLER:

public class restApiToCreateRecord {

    private string cKey;

    private string cSecret;

    private string uName;

    private string passwd;

    public string instanceURL;

    public restApiToCreateRecord () {

    }

    public class responseWrapper {

        public string id;

        public string access_token;

        public string instance_url;

    }

    public responseWrapper getRequestToken() {

        List < Store_Cred__mdt > connectionParam = [SELECT Id, MasterLabel, client_id__c, client_secret__c, username__c, password__c from Store_Cred__mdt];

        if(connectionParam.size() >0){

        cKey=connectionParam[0].client_id__c;

        cSecret=connectionParam[0].client_secret__c;

        uName=connectionParam[0].username__c;

        passwd=connectionParam[0].password__c ;

        }

        System.debug('Store_Cred__mdt' + connectionParam);

        string reqBody = 'grant_type=password&client_id=' + cKey + '&client_secret=' + cSecret + '&username=' + uName + '&password=' + passwd;

        Http h = new Http();

        HttpRequest req = new HttpRequest();

        req.setBody(reqBody);

        req.setMethod('POST');

        req.setEndpoint('https://login.salesforce.com/services/oauth2/token');

        HttpResponse hresp = h.send(req);

        responseWrapper wResp = (responseWrapper) JSON.deserialize(hresp.getBody(), responseWrapper.class);

        system.debug('reqBody '+reqBody );

        system.debug('wResp'+wResp );

        system.debug('Instance url' + wResp.instance_url);

        system.debug('session id' + wResp.access_token);

        return wResp;

    }

    @future (callout=true)

    public static void createAccount(Set < id > accIdSet) {

        list < account > accList = new list < account > ();

        String accToken;

        String instanceUrl;

        string responseBody;

        string email = 'testemail123@gmail.com';

        string phone = '123';

        restApiToCreateRecord obj = new restApiToCreateRecord();

        responseWrapper obj1= obj.getRequestToken();

        accToken = obj1.access_token;

        instanceUrl = obj1.instance_url;

        string endPoint = instanceURL+'/services/apexrest/createAccountRecord';

        system.debug('endPoint'+endPoint );

        system.debug('access token' + accToken);

        if (accToken != '') {

            for (Account acc: [SELECT Id,Name,Description,Type,Industry from account where id in: accIdSet]) {

            accList.add(acc);

            }

            Http h1 = new Http();

            HttpRequest req1 = new HttpRequest();

            req1.setHeader('Authorization', 'Bearer ' + accToken);

            req1.setHeader('Content-Type', 'application/json');

            //req1.setHeader('Accept','application/json');

            req1.setMethod('POST');

            req1.setEndpoint(endPoint);

            req1.setBody(JSON.serialize(accList));

            HttpResponse hresp1 = h1.send(req1);

            system.debug('hresp1'+hresp1 );

            system.debug('hresp1.getStatusCode()'+hresp1.getStatusCode());

             system.debug('hresp1.getBody()'+hresp1.getBody());

            if (hresp1.getStatusCode() == 200) {

                system.debug('Callout Success');

            }

        }

    }

}


REMOTE SITE STORED IN ORG A:

The remote site url here is nothing but the instance URL of ORG B.


Now, Let's try to create an account record in ORG A manually. Now, check the same record will be created in ORG B as well.

                                                    Creating a record in ORG A:

REST API callout Salesforce example HTTP POST

Record automatically created in ORG B:

REST API callout Salesforce example HTTP POST

2 comments: