Navigate back to the homepage

Search A Data Extension From Sales Cloud

Jason Hanshaw
February 14th, 2020 · 7 min read

When working with clients that are heavily integrated with Sales Cloud, it can be a challenge for users of the core system to identify data existing in Marketing Cloud that isn’t included in standard tracking or the SF object model. While we could provide an automated solution in Marketing Cloud to sync this data into the core system, you run the risk of confusing novice users as well as having a less dynamic approach for adhoc requests.

In this post, I’ll demonstrate an example solution, using a custom lightning component, that allows Sales and Service Cloud users to search a Send Logging data extension by email address within the core system UI.

Note: This solution uses an undocumented API endpoint in Marketing Cloud that could be modified or removed without warning by Salesforce. A sudden change to this could result in your application no longer functioning as intended. For a more reliable method of data retrieval, it is recommended that you use the SOAP API instead. Since this post is just a demonstration of this functionality, I’ll be using the REST endpoint for simplicity and as a matter of personal preference.

Before We Begin:

Assumptions:

This post assumes that you are familiar with development, version control and deployment of an SF codebase through SalesforceDX. For the ease of creating a quick proof-of-concept, you may also create your component via the Developer Console though this method should not be used in production or team-based sandbox environments. Also, we’ll assume that you have an understanding of creating unit tests as well as storing API credentials as these items will not be within the scope of this post.

With that out of the way, let’s get our Marketing Cloud environment configured.

Prerequisites:

In order for our lightning component to function, we’ll need to ensure that we have configured our data source and installed package on the Marketing Cloud side.

Send Logging Data Extension

First, you’ll need to create a Send Logging data extension with the following custom fields added:

  • view_email_url
  • send_date

The view_email_url column will automatically log the view as webpage link for each email send and will allow our SF users to view the individual email creative from our component. The send_date column will log the datetime that the email was sent to a subscriber.

Note: In order for our send_date column to populate data, we’ll need to add the following script to the emails/templates that we are deploying out of Marketing Cloud:

1%%[
2var @send_date
3set @send_date = Now()
4]%%

 
This will allow our Send Logging data extension to capture that value at send time, and will give our users more insight into the email delivery by seeing the date it deployed.

Installed Package

In addition to setting up our Send Logging data extension, we’ll also need to create an installed package so that we can authenticate and make API calls to Marketing Cloud from an external system. The process for doing this is outside the scope of this post, but you can find more information in the Salesforce documentation.

Now that we have everything configured on the Marketing Cloud side, lets start developing our lightning component.

Building Our Component:

Now that we are ready to start developing our component, lets take a look at each of our necessary files in order to get a better idea on how this application will function:

SendLogSearch.cls

This is our custom controller Apex class that will be responsible for making our API calls into Marketing Cloud and returning the data which we want to display in our component.

SendLogSearch.cmp

This is the component file that will define the markup and design of our application. It’s helpful to consider this as the “front-end” of our component.

SendLogSearch.css

This file will contain all CSS styles that are being utilized within our component file. It should be noted that all declarations in the file are prepended with the prefix .THIS (i.e. .THIS .some-class { color: red; } in order to allow SF to accurately style our application since this class will automatically be converted to our component name by the system framework.

SendLogSearchController.js

This is our client-side controller that will contain our functions related to events that occur within the component, such as when the user enters the desired email address and clicks our search icon.

SendLogSearchHelper.js

This file contains our utility functions for the component. In order to maintain code readability and testability, you should keep your client-side controller as lean as possible and include any functions that do complex processing within the helper. For our application, the helper file will process all of our javascript logic, while the client-side controller serves to call the helper file based on events from our component.

SendLogSearch.app

Our application file will simply serve as a container for our component files and tells the system what to execute.

With our necessary files outlined, let’s start building!

Creating The Apex Class

We’ll need to create a custom controller Apex class in order to interact with Marketing Cloud to retrieve our data from the Send Logging data extension. To begin let’s create the basic class structure that will house our functions:

1public with sharing class SendLog {
2
3}

We’ll use the with sharing keyword in our class in order to execute our functions in a user (with security settings enforced) context rather than a system context. This won’t be applicable in our use-case, but is helpful in solutions where access to fields, objects, etc… should be dependent on the user.

With our apex class declared, let’s add a generic function to make a POST request so that we can authenticate into Marketing Cloud a little easier. Let’s also add the @testVisible keyword to this as well in order to make it available for constructing unit tests on this private method in the future.

1public with sharing class SendLog {
2 @testVisible private static String makeJSONPostCall(String endPoint, String restBody, String token){
3 Http h = new Http();
4 HttpRequest r = new HttpRequest();
5 r.setTimeout(60000);
6 r.setEndpoint(endPoint);
7 r.setMethod('POST');
8 r.setHeader('Content-type','application/json');
9 if(!String.isEmpty(token)){
10 r.setHeader('Authorization', 'Bearer ' + token);
11 }
12 r.setBody(restBody);
13 HttpResponse res = h.send(r);
14 return res.getBody();
15 }
16}

Let’s add some global variables for our class that will specify the user credentials and API endpoint for searching our Send Logging data extension:

Remember, this is for demonstration only and any production implementation should never include unencrypted credentials in your class.

1public with sharing class SendLog {
2 private static String MARKETING_CLOUD_AUTH_URL = YOURAUTHURL;
3 private static String ACCESS_TOKEN = 'access_token';
4 private static String ClientID = CLIENTID;
5 private static String ClientSecret = CLIENTSECRET;
6 private static String sendLogURL = 'https://www.exacttargetapis.com/data/v1/customobjectdata/key/SendLog/rowset?$page=1&$pageSize=5&$orderBy=send_date%20DESC&$filter=emailaddr=';
7 @testVisible private static String makeJSONPostCall(String endPoint, String restBody, String token){
8 Http h = new Http();
9 HttpRequest r = new HttpRequest();
10 r.setTimeout(60000);
11 r.setEndpoint(endPoint);
12 r.setMethod('POST');
13 r.setHeader('Content-type','application/json');
14 if(!String.isEmpty(token)){
15 r.setHeader('Authorization', 'Bearer ' + token);
16 }
17 r.setBody(restBody);
18 HttpResponse res = h.send(r);
19 return res.getBody();
20 }
21}

The important item to note here is the structure of the sendLogURL variable. This will be the (again, undocumented) endpoint that we will call to retrieve our data from the Send Logging data extension. For our purposes, we will set the following parameters on the URL:

  • key: SendLog (Our External Key Of Our Send Logging data extension)
  • page: 1 (Return only 1 page of results)
  • pageSize: 5 (We’ll return only 5 results from our data extension)
  • orderBy: send_date%20DESC (We’ll order our results based on the most recent send_date)
  • filter: emailaddr (Filter data extension by an email address)

Now, let’s set up a function to make a request to Marketing Cloud in order to generate the access token we’ll need to call that endpoint.

1public with sharing class SendLog {
2 private static String MARKETING_CLOUD_AUTH_URL = YOURAUTHURL;
3 private static String ACCESS_TOKEN = 'access_token';
4 private static String ClientID = CLIENTID;
5 private static String ClientSecret = CLIENTSECRET;
6 private static String sendLogURL = 'https://www.exacttargetapis.com/data/v1/customobjectdata/key/SendLog/rowset?$page=1&$pageSize=5&$orderBy=send_date&$filter=emailaddr=';
7 @testVisible private static String makeJSONPostCall(String endPoint, String restBody, String token){
8 Http h = new Http();
9 HttpRequest r = new HttpRequest();
10 r.setTimeout(60000);
11 r.setEndpoint(endPoint);
12 r.setMethod('POST');
13 r.setHeader('Content-type','application/json');
14 if(!String.isEmpty(token)){
15 r.setHeader('Authorization', 'Bearer ' + token);
16 }
17 r.setBody(restBody);
18 HttpResponse res = h.send(r);
19 return res.getBody();
20 }
21 @AuraEnabled
22 public static String getMarketingCloudToken(){
23 String responseBody = makeJSONPostCall(
24 MARKETING_CLOUD_AUTH_URL,
25 JSON.serialize( new Map<String, String>{
26 'grant_type': 'client_credentials'
27 'clientId' => ClientID,
28 'clientSecret' => ClientSecret
29 'account_id': YOURMID
30 } ), NULL
31 );
32 return ((Map<String, String>) JSON.deserialize(responseBody, Map<String, String>.class)).get( ACCESS_TOKEN );
33 }
34}

This function makes use of our makeJSONPostCall function to make a POST request to Marketing Cloud with our credentials in order to return an access token if the call is successful.

Finally, let’s write another function that will take a user input for email address and make a GET request to Marketing Cloud in order to return our filtered data set from the Send Logging data extension.

1public with sharing class SendLog {
2 private static String MARKETING_CLOUD_AUTH_URL = YOURAUTHURL;
3 private static String ACCESS_TOKEN = 'access_token';
4 private static String ClientID = CLIENTID;
5 private static String ClientSecret = CLIENTSECRET;
6 private static String sendLogURL = 'https://www.exacttargetapis.com/data/v1/customobjectdata/key/SendLog/rowset?$page=1&$pageSize=5&$orderBy=send_date&$filter=emailaddr=';
7 @testVisible private static String makeJSONPostCall(String endPoint, String restBody, String token){
8 Http h = new Http();
9 HttpRequest r = new HttpRequest();
10 r.setTimeout(60000);
11 r.setEndpoint(endPoint);
12 r.setMethod('POST');
13 r.setHeader('Content-type','application/json');
14 if(!String.isEmpty(token)){
15 r.setHeader('Authorization', 'Bearer ' + token);
16 }
17 r.setBody(restBody);
18 HttpResponse res = h.send(r);
19 return res.getBody();
20 }
21 @AuraEnabled
22 public static String getMarketingCloudToken(){
23 String responseBody = makeJSONPostCall(
24 MARKETING_CLOUD_AUTH_URL,
25 JSON.serialize( new Map<String, String>{
26 'grant_type': 'client_credentials'
27 'clientId' => ClientID,
28 'clientSecret' => ClientSecret
29 'account_id': YOURMID
30 } ), NULL
31 );
32 return ((Map<String, String>) JSON.deserialize(responseBody, Map<String, String>.class)).get( ACCESS_TOKEN );
33 }
34 @AuraEnabled
35 public static String searchSendLog(String Email) {
36 String authToken = getMarketingCloudToken();
37 Http h = new Http();
38 HttpRequest webReq = new HttpRequest();
39 webReq.setMethod('GET');
40 webReq.setHeader('Authorization','Bearer '+ authToken);
41 webReq.setEndpoint(sendLogURL + '"' + Email + '"');
42 HttpResponse res = h.send(webReq);
43 String response = res.getbody();
44 return response;
45 }
46}

That’s all we need in order to configure our Apex class to authenticate and retrieve the necessary data from Marketing Cloud. With that piece of the puzzle in place, let’s take a look at our client-side controller and helper files in order to pull this data into our component.

Creating The Client-Side Controller

Our client-side controller configuration is actually quite simple to implement. Since we are using our helper file to do the heavy-lifting for our component, our controller only needs to provide a function that our front-end can call in order to retrieve the data gathered in our helper. We’ll create a new function that will call our helper function.

1({
2 sendLogSubmit: function (component, event, helper) {
3 helper.getSendLogResults(component, event, helper);
4 }
5 });

 
That’s all we need for our controller, so let’s take a look at our helper file to see how we are retrieving the data from our Apex class.

Creating The Helper File

For our helper file, we’ll need to set up a function that can make a request to our Apex class and then pass the appropriate JSON source to the front-end in order to dynamically display results from our Send Logging data extension:

1({
2 getSendLogResults: function (component, event, helper) {
3 var action = component.get("c.searchSendLog");
4 var sendLogEmail = component.get("v.sendLogEmail");
5 action.setParams({ Email: sendLogEmail });
6 action.setCallback(this, function(response) {
7 var temp = response.getReturnValue();
8 var json = JSON.parse(temp.toString());
9 var primNode = json.items;
10 var sendArray = [];
11 for(var i in primNode) {
12 var arrVals = primNode[i].values;
13 sendArray.push(arrVals);
14 }
15 component.set("v.sendLogResults",sendArray);
16 });
17 $A.enqueueAction(action);
18 }
19});

 
In this function, we’re first identifying the class we want to invoke (component.get("c.searchSendLog")) as well as retrieving the email address input that the user has provided on our front-end of the component (component.get("v.sendLogEmail")). Then we execute the request to our controller and return the JSON response from Marketing Cloud containing the 5 most recent entries for that email address in the Send Logging data extension.

Once we’ve captured that data, we’ll create an array that will contain the nested results we want to display. Then, we’ll assign it to a variable that we’ll use to call this data within our front-end (component.set("v.sendLogResults")).

Creating The Component File

Our application logic has now been setup, but we don’t have a way for our users to interact with our scripts. To do this, we’ll need to create our component file that will serve as the front-end.

To begin, let’s build out the basic structure of our component.

1<aura:component
2 controller="SendLog"
3 implements="flexipage:availableForAllPageTypes"
4 access="global"
5>
6 <aura:attribute name="sendLogEmail" type="String" default="" />
7 <aura:attribute name="sendLogResults" type="String[]" />
8</aura:component>

 
This is the base for our component. We’re letting it know what customer controller Apex class we’ll be using for this as well as the context that we can call/display this component.

In addition to this, we’re going to declare the variables that we made reference to in our helper file, that will allow us to take the user input (sendLogEmail) and to display the array of results returned (sendLogResults).

Now we can add in the markup for our component so that we can take input and display things in a user-friendly way.

1<aura:component
2 controller="SendLog"
3 implements="flexipage:availableForAllPageTypes"
4 access="global"
5>
6 <aura:attribute name="sendLogEmail" type="String" default="" />
7 <aura:attribute name="sendLogResults" type="String[]" />
8 <div class="component">
9 <div class="container">
10 <div class="main">
11 <div class="row">
12 <div class="col-s3 col table-container">
13 <div class="card-container">
14 <div class="card">
15 <div class="card-title">
16 <h6 class="card-subdescription">SEARCH EMAIL</h6>
17 <h3 class="card-description">Send Log</h3>
18 </div>
19 <div class="card-subcontainer">
20 <div class="table-search">
21 <lightning:input
22 type="text"
23 name="email-search"
24 placeholder="Enter An Email Address To Search Sent Emails"
25 value="{!v.sendLogEmail}"
26 />
27 <div class="search-icon" onclick="{!c.sendLogSubmit}">
28 <lightning:icon
29 iconName="utility:search"
30 alternativeText="Search"
31 size="small"
32 /></div>
33 </div>
34 <aura:if isTrue="{!not(empty(v.sendLogResults))}">
35 <div class="table-responsive">
36 <table class="table">
37 <thead>
38 <tr>
39 <th>Email Name</th> <th>Send Date</th
40 ><th>Email Send</th>
41 </tr>
42 </thead>
43 <tbody>
44 <aura:iteration items="{!v.sendLogResults}" var="row">
45 <tr>
46 <td class="email-name">{!row.emailname_}</td>
47 <td>{!row.send_date}</td>
48 <td
49 ><a
50 class="btn preview"
51 href="{!row.view_email_url}"
52 target="_blank"
53 >Preview</a
54 ></td
55 >
56 </tr>
57 </aura:iteration>
58 </tbody>
59 </table>
60 </div>
61 <aura:set attribute="else">
62 <div class="empty-sl"
63 ><div class="empty-header"
64 ><h3>No results listed.</h3></div
65 ><div class="empty-text"
66 ><p
67 >Enter an email address in the search bar in order
68 to view the most recent email sends for a
69 recipient.</p
70 ></div
71 ></div
72 >
73 </aura:set>
74 </aura:if>
75 </div>
76 </div>
77 </div>
78 </div>
79 </div>
80 </div>
81 </div>
82 </div>
83</aura:component>

 
Let’s break down some of this markup in order to see what’s going on outside of basic styling. Here’s a snippet from our component file related to taking user input:

1<lightning:input type="text"
2 name="email-search"
3 placeholder="Enter An Email Address To Search Sent Emails"
4 value="{!v.sendLogEmail}"
5 />
6<div class="search-icon" onclick="{!c.sendLogSubmit}">
7<lightning:icon
8 iconName="utility:search"
9 alternativeText="Search"
10 size="small"
11 />

 
Notice that we’ve set the value parameter on the lightning:input element to equal the variable we defined at the top of our file. This allows us to access and set this value programatically for use in our controllers and helper. Also, you will see that we have attached the sendLogSumbit function from our client-side controller to the onclick action of our search icon. This will execute our client-side controller, and thus helper function, when a user clicks the icon.

Before the user actually clicks the icon to submit their search, or if the search returns no results, we’ll want to display some fallback text to the user. We can wrap this section of the markup with an if/else statement to show our data when we have results and to show a fallback when no results are found:

1<aura:if isTrue="{!not(empty(v.sendLogResults))}">
2
3<aura:set attribute="else">
4
5</aura:set>
6</aura:if>

 
The only piece left is to iterate through the results, retrieved from our helper function, and to display them to the user:

1<aura:iteration items="{!v.sendLogResults}" var="row">
2 <tr>
3 <td class="email-name">{!row.emailname_}</td>
4 <td>{!row.send_date}</td>
5 <td
6 ><a
7 class="btn preview"
8 href="{!row.view_email_url}"
9 target="_blank"
10 >Preview</a
11 ></td
12 >
13 </tr>
14</aura:iteration>

 
This snippet takes our variable sendLogResults and iterates over each row of the data. We use the local row variable as an alias in order to access a given element in each iteration and to display its properties in a table row.

Creating The CSS File

Now, we’ll want to style our elements so that the component is more visually appealing to the user. Here’s the full CSS file we’ll use to style our component:

1/* PRIMARY CONTAINER STYLES */
2.THIS .col-s12 {
3 flex: 0 0 100%;
4 max-width: 100%;
5 display: flex;
6 align-items: stretch;
7 position: relative;
8 width: 100%;
9 min-height: 1px;
10}
11.THIS .container {
12 width: 100%;
13 background-color: #f8f8f8;
14 border-radius: 5px;
15 padding: 1rem 0;
16}
17.THIS .main {
18 width: 92%;
19 margin-left: auto;
20 margin-right: auto;
21 margin-bottom: 0.75em;
22 color: #575a65;
23}
24.THIS .row {
25 display: flex;
26 flex-wrap: wrap;
27 margin-right: -15px;
28 margin-left: -15px;
29 margin-bottom: 2rem;
30}
31/* CARD STYLES */
32.THIS .card {
33 box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
34 transition: 0.3s;
35 background-color: #ffffff;
36 border-radius: 5px;
37 width: 100%;
38}
39.THIS .card:hover {
40 box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
41}
42.THIS .card-container {
43 width: 100%;
44}
45.THIS .card-description {
46 font-size: 1.85em;
47}
48.THIS .card-footer {
49 padding: 15px 15px 10px 20px;
50 display: flex;
51 align-items: center;
52}
53.THIS .table-container .card-container {
54 padding: 0 15px;
55}
56.THIS .card-subcontainer {
57 padding: 2px 16px;
58}
59.THIS .card-title {
60 padding: 25px 20px;
61}
62/* TABLE STYLES */
63.THIS .table {
64 width: 100%;
65 margin-bottom: 1rem;
66 color: #575a65;
67}
68.THIS .table td,
69.THIS .table th {
70 padding: 0.75rem;
71 vertical-align: middle;
72 color: #575a65;
73}
74.THIS td, .THIS th {
75 padding-left: 5px !important;
76}
77.THIS .table thead th {
78 vertical-align: bottom;
79}
80.THIS .table-bordered {
81 border: 1px solid #dee2e6;
82}
83.THIS .table .email-name {
84 color: #222222;
85}
86.THIS .table-striped tbody tr:nth-of-type(odd) {
87 background-color: rgba(0, 0, 0, 0.05);
88}
89.THIS .table-hover tbody tr:hover {
90 color: #575a65;
91 background-color: rgba(0, 0, 0, 0.075);
92}
93.THIS .table .btn {
94 border: none;
95 color: white;
96 padding: 10px 15px;
97 text-align: center;
98 text-decoration: none;
99 display: inline-block;
100 font-size: 12px;
101 margin: 4px 2px;
102 max-width: 100%;
103 border-radius: 5px;
104}
105.THIS .table .preview {
106 background-color: #7ad1dc;
107}
108.THIS tr:not(:last-child) {
109 border-bottom: 2px solid #e9ecef;
110}
111/* SEARCH AND ICON STYLES */
112.THIS button.slds-button.slds-button_icon.border-0.slds-button_icon-border {
113 border: none;
114}
115.THIS .empty-sl {
116 padding: 1rem 2rem 2rem .2rem;
117}
118.THIS .empty-header h3 {
119 font-size: 1.2rem;
120}
121.THIS .empty-text {
122 padding-top: 1rem;
123}
124.THIS .search-icon {
125 display: inline-flex;
126 cursor: pointer;
127}
128.THIS .slds-form-element__label:empty {
129 display: none;
130}
131.THIS .table-search lightning-input {
132 display: inline-block;
133 width: 85%;
134}
135.THIS .table-search lightning-primitive-icon {
136 display: inline-block;
137}
138.THIS .table-search {
139 padding-bottom: 0.75rem;
140}
141.THIS .table-search lightning-primitive-icon {
142 padding-left: 10px;
143}

Creating The App File

We’re now ready to create our application file so that we can utilize this functionality as part of a custom app or as a standalone item in a SF page.

1<aura:application >
2 <c:SendLogSearch />
3</aura:application>

Conclusion

SearchSendLog

That’s it! We’re now able to provide our Sales and Service Cloud users with an easy and efficient way of searching our Send Logging data extension from the core system UI.

With some simple modifications to the above scripting, we could provide the user with more complex filtering criteria or even allow them to dynamically define the data extensions and criteria they would like to use in their search.

To see the source for this post, you can view the repository on github.

More articles from InvokeCreate

Pull Assets To Local Storage With Python

Export assets from Content Builder to local storage using the REST API.

January 5th, 2020 · 4 min read

CloudPage Deep Linking

A dynamic deep linking solution that routes users based on device type

January 1st, 2020 · 3 min read
© 2020 InvokeCreate
Link to $https://github.com/invokecreate/Link to $https://www.linkedin.com/in/jason-hanshaw-developer/Link to $https://salesforce.stackexchange.com/users/50722/jason-hanshaw