Integrating With Salesforce Using Apex | Techila
2700
single,single-post,postid-2700,single-format-standard,ajax_updown_fade,page_not_loaded,,qode_grid_1300,footer_responsive_adv,hide_top_bar_on_mobile_header,qode-content-sidebar-responsive,qode-theme-ver-9.4.2,bridge,wpb-js-composer js-comp-ver-4.12,vc_responsive
 

Integrating With Salesforce Using Apex

INTEGRATING WITH SALESFORCE USING APEX

Integrating With Salesforce Using Apex

This article concludes the series, Learning Salesforce Integration, which details various integration options with Salesforce. It covers using Apex for building integrations, which becomes a necessity for not-so-straight-forward scenarios. Though the scenarios listed here are simple, the idea is to share code snippets that can be used to quickly build a working interface.

So why take the programmatic path? Well, when I started learning Salesforce, I was curious about how Salesforce handled interfacing, more so, when it came to dealing with complex business scenarios. Coding comes to the rescue in such situations. It proves advantageous in terms of flexibility and offers control over certain situations.

For this post, I’ll offer a simple explanation  of the complex, yet interesting areas essential for the complete understanding of Salesforce Integration’s capabilities. The business scenario quoted, along with the working code samples, will be a good starting point for entering into the world of non-declarative ways for integrating with Salesforce. Here’s what I’ll cover:

  • Understanding authentication and its prerequisites
  • OAuth authentication flows for REST API calls
  • Apex triggers and callouts
  • REST API, REST web services, and Apex web services

Authentication and Its Prerequisites

Authenticating a client application is the first and foremost step while building an interface. Once authenticated, we developers are only limited by our skills (and of course by the business requirement) because programming languages provide abundant capabilities for building and implementing logic that cater to any complex requirement. Further, the direction of the call’s flow decides the interfacing ends, i.e., the source and the destination.

The authentication method depends on your chosen call type (REST or SOAP). Like in my first post, I integrated Siebel with Salesforce using SOAP. So I used the SOAP API login() call. Let’s see how to do it using REST.

Before moving any further, let’s frame a business scenario. We’ll use two Salesforce instances that exchange Account details. When a new Account is created in one org, it will flow down to the other Salesforce org, and in return the source org will get the Salesforce Record ID of the created record. These two orgs are:

  • Source Salesforce org (used for callout) – Instance S
  • Target Salesforce org (used for receiving requests) – Instance T

I planned it this way because you don’t need to depend on any other client application, and you get to learn about interfacing for both outbound and inbound calls together.

Following our business scenario, we can say that authentication is a collection of the following sub-steps. Though actual authentication calls a trigger from the Apex code, consider these steps as the prerequisites because without them being completed first, the authentication calls won’t work.

  1. Remote Site Setting in Instance S
  2. Connected App in Instance T
  3. Choosing OAuth Endpoint (to be invoked from Instance S)
  4. Choosing OAuth Authentication flow (to be used by Instance S)

Remote Site is any web address that your organization can invoke from Salesforce. For any callout to work (whether SOAP or REST), the called domain (or the domain of Instance T) needs to be registered as a remote site in Instance S. The idea behind it is to prevent any calls to unauthorized network addresses.

OAuth Authentication Flows

The REST API calls can be authenticated using any of the available three flows:

Web Server OAuth Authentication Flow – The client application requests the authorization server to redirect the user to another web server or resource that authorizes the user and sends the application an authorization code. The application uses the authorization code to request an access token.

User-Agent OAuth Authentication Flow – The client application requests the authorization server to redirect the user to another Web server or resource that is capable of extracting the access token, and passing it back to the application.

Username-Password OAuth Authentication Flow – This flow can be used to authenticate when the consumer already has the user’s credentials for the target instance.

I have used the Username-Password flow in the business scenario. Using this flow usually means that we plan to use a separate Salesforce User (we can call it an Integration User) to access the target Salesforce instance. This user’s access can be limited to whatever we wish, using its Profile settings, and can be used by various systems that integrate to the Salesforce instance.

To sum up, we have configured a few of the settings and made our choices about the authentication endpoint and flow. Now we’ll continue learning about coding an Apex Trigger, ApexClass, Authentication call, Data Request call, and Response manipulation.

Handling the Need Using Apex Trigger

Unlike other programming languages, Apex has a limited scope as defined by Salesforce. It surfaces only when we are not able to achieve the result using Point-And-Click or the Declarative approach.

Apex Trigger, as a Database trigger, refers to a piece of Apex code that sits and waits for a particular event (Data Manipulation Language event, DML) to occur. When that happens, it executes the code written to achieve the desired result. It is usually constructed using Apex-defined keywords and SOQL.

I find defining a trigger as one easy way to perform a callout, though the call that is made is asynchronous. So the user needs to refresh the page in case any update from the response has been made to the currently displayed record. An example of making a synchronous callout can be the use of a Visualforce page, but that is not in scope of this article.

trigger SendAccount on Account* (after** insert***)
{
1 for(Account a : Trigger.new)
  {
2   SendAccountUsingRESTAPI.callcreateAcc(a.Name, a.Id);
  }
}

Explanation –

  • * The object on which this Trigger is based
  • ** The execution moment, i.e., before or after
  • *** The operation, like insert, update, etc.
  • 1 Optimized to operate in bulk for handling more than one record at a time
  • 2 Invoking an @future method of a class with required arguments

After a new Account record is inserted into the database, this trigger is invoked. It can handle more than one Account record, which is helpful when dealing with bulk data load. Finally, the trigger calls a public class that has a method annotated with @future. The @future annotation provides a way to perform a callout asynchronously.

Generating the Access Token

Once the above trigger executes, it makes a call to the class that is mentioned. This class does the actual authentication processing and data exchange. In brief, the defined custom class performs three main tasks:

  1. It retrieves an access token from Instance T to authenticate Instance S. It is an HTTP POST request that uses the OAuth Endpoint, along with the Consumer Key and Consumer Secret generated from the Connect App record. The response is then deserialized to retrieve the access token.
  2. It makes a data call to Instance T. This call can be a REST API/SOAP API call (Data Layer) or REST/Apex Web Service call (Business Logic Layer) and depends on our need or the complexity of the requirement. We will discuss REST API, REST Web Service, and Apex Web Service separately to understand the general code to be used.
  3. It handles the response from Instance T, deserializes it, and updates Instance S with the relevant information.

“Know more about Salesforce Consulting at Techila”

Author: techila

No Comments

Post A Comment