Custom profile and subscription center integrated with Sales/Service Cloud

In this tutorial, you will learn how to create a simple, yet fully customizable profile and subscription center integrated with Sales and Service Cloud. If you would like to skip the reading and jump to the final version of the script, click here. Bear in mind, that the script utilizes a couple of standard and custom Sales/Service Cloud fields – the full list can be found here.

What are Profile and Subscription Centers?

Each instance of Salesforce Marketing Cloud comes with a standard, predefined Profile Center and Subscription Center.

The profile center is a webpage where subscribers can enter and maintain the personal information that you keep about them. When you import a list, you can import attribute values for your subscribers that appear when a subscriber visits the profile center. The subscriber can update their information on this page and provide additional information.

A subscription center is a web page where a subscriber can control the messages they receive from your organization. The lists (including publication lists) you identify as public in the application are available for a subscriber to opt in to on the subscription center.

If you’re using Marketing Cloud Connect to integrate with Sales/Service Cloud, you can use the standard Profile Center based on the Marketing Cloud attributes that are mapped to fields in Sales or Service Cloud. Marketing Cloud Connect documentation states, that changes made in the Profile Center update Salesforce contact and lead data – unfortunately I haven’t been able to confirm this with my tests.

Another limitation which is very hard to overcome is the look and feel of the standard Profile and Subscription Center. If you enable Marketing Cloud BrandBuilder, you will be able to customize the color scheme of your Profile and Subscription Center based on the colors of the logo you upload – but you won’t be able to change the layout or the fonts used.

Sooner or later, most Marketing Cloud users switch to custom Profile and Subscription Centers, as the standard one is not enough when it comes to more complex use cases.

Anatomy of a Subscription Center

A Subscription Center is nothing else but an HTML form. The data passed in the form is then processed by a script – in this tutorial, we will use AMPscript. If you’ve never created a form before, you might want to check out this article first: Create a Sales Cloud-integrated lead capture form using AMPscript.

In the form, you can include any fields from any of the relevant Sales/Service Cloud objects, but to make it more simple as we go, for now, we will use three standard fields from the Contact object: FirstName, LastName and Email. Additionally, I have added three read-only checkboxes to the Contact object for subscription management: Newsletter, Offers and Events. [Why are they read-only? In this tutorial, you will learn how to allow subscribers to make changes to their preferences and sync those changes back to Salesforce. The process of managing the subscriptions by a Salesforce user and syncing the changes back to Marketing Cloud is a separate procedure and won’t be addressed in this article.] I also made sure that the Email Opt Out flag is visible on a Contact page layout in Sales Cloud:

Here is a reference of all the fields from the Contact object, which we will use in our script:

Field LabelAPI Field NameTypeLength
Contact IDIdid18
EmailEmailemail80
Email Opt OutHasOptedOutOfEmailboolean
Name FirstNamestring80
Name LastNamestring80
NewsletterNewsletter__cboolean
EventsEvents__cboolean
OffersOffers__cboolean

Let’s now create a simple HTML form which contains all of the above fields:

Since we want the form to be pre-populated with subscriber data from Sales/Service Cloud, we need to add the RetrieveSalesforceObjects function to pull the data, and display the retrieved data as field values:

You will also notice in the above script, that we have added a form action. The RequestParameter('PAGEURL') function reloads the page when the form is submitted, posting the form parameters back to the same page. You can, of course, post the form data to another page and process it there, but for the purpose of this tutorial, let’s keep everything on one page so that it’s easier to copy and paste.

After the form is submitted and posted, the data can be retrieved by using the RequestParameter AMPscript function. We will then update the data in Sales/Service Cloud using the UpdateSingleSalesforceObject function. Let’s add them now:

Congratulations – you just built the first, simple version of your profile and subscription center!

Now let’s analyze the above script. The first thing that you will notice is that all the AMPscript is placed at the beginning of the document, above the form – that’s because the form data first has to be posted before it can be processed, and upon posting the data, the page reloads and starts resolving the script from top-down. If you need more clarification on this concept, click here.

If the form has been submitted, we will update the Sales/Service Cloud contact with the new data that was posted upon form submission. The form data is retrieved using the RequestParameter function, which is used in the @updateRecord variable inside the UpdateSingleSalesforceObject function.

You will also notice, that for each of the checkboxes, I have added the following in-line IF function: Iif(RequestParameter("newsletter") == "on", "true", "false"). That is because the checkbox passed from the HTML form will have a value of either on or off, while to pass it to Sales/Service Cloud, we need to convert it to a boolean value of true or false.

Unsubscribe From All option

To make the functionality of our custom subscription and profile center similar to the standard one, we can add the Unsubscribe From All and Resubscribe options. The Unsubscribe From All option should not only set all the subscription-related flags in Sales Cloud to false, but also set the subscriber’s status to Unsubscribed in Salesforce Marketing Cloud’s All Subscribers list. To achieve this, we need to log an UnsubEvent. In order to do that, we will add an additional button to the form (Unsubscribe From All) and a hidden parameter which will be passed if someone clicks this button (name="unsub" type="hidden" value="true"). After submitting the form, if unsub value equals true, we will log the UnsubEvent in addition to updating the flags in Sales/Service Cloud. The below is a simplified version of logging an UnsubEvent and it will unsubscribe the contact from all BUs – if you would like to modify it to your use case, refer to this article: Unsubscribe and Log an UnsubEvent with a LogUnsubEvent Execute Call. Here’s what we need to add to our script to make this part work:

Since we have the option to Unsubscribe From All, we now also have to add an option to Resubscribe. The Resubscribe option will set all the subscription-related flags in Sales Cloud to true and set the subscriber’s status to Active in Salesforce Marketing Cloud’s All Subscribers list. The Resubscribe button will appear for any contact that has the HasOptedOutOfEmail flag set to true in Sales Cloud. The button also has a hidden parameter that will be passed with the form (name="sub" type="hidden" value="true"). Upon clicking the button, we will invoke the update method on a subscriber object to set their status to Active in Marketing Cloud, as well as update their subscription-related flags in Sales Cloud:

Update subscriber’s data in Marketing Cloud

If you’re using Marketing Cloud Connect, a very important thing to remember when updating subscriber’s email address is to do it in both, Sales/Service Cloud and Marketing Cloud. Here is why:

If an email address for a Lead or Contact Object is updated in Sales Cloud or Service Cloud, the corresponding email address is not updated in the All Subscribers list.

Eliot Harper, THE DATA HANDBOOK – Data Architecture for Salesforce Marketing Cloud

In order to achieve this, we will add one more piece of a script to update the subscriber object. First we will check, if the subscriber’s current email address in Marketing Cloud is different from the one provided in the form, and if it is, we will update it accordingly:

You do not need to include the above if you already have a process in place that synchronizes email address changes from Sales/Service Cloud to All Subscribers list in Salesforce Marketing Cloud. If you’d like to learn more about synching updates between the clouds, read Markus Slabina’s blog post here.

Custom subscription and profile center full script

As a final touch, to improve the experience, let’s add a confirmation message and a button that will reload the page and display the updated data in the form. Here is the final version of the script, with all of the above changes included:

Remember, that you will need to use the CloudPagesURL function to link to the subscription center CloudPage from an email.

In order to see how the above script works, feel free to play around with one of my test contacts in the test version of the subscription and profile center that I set up on a CloudPage: https://pub.s10.exacttarget.com/

Here are some resources if you would like to read further about subscription management best practices:

  • Here you will find an interesting concept of creating Campaigns for each subscription and adding the Contact as a Campaign Member
  • Here you can read how Effective Email Preference Centers Help Keep Subscribers Active and Engaged
  • Solve problems using the subscription-center and preference-center tags on Salesforce Stack Exchange

Questions? Comments?

Leave a comment below or email me at zuzanna@sfmarketing.cloud.

Trigger SMS text messages using Server-Side JavaScript

In order to be able to programmatically trigger text messages, you will need to have MobileConnect enabled in Marketing Cloud’s Mobile Studio. You will also need to be able to create an installed package in your Marketing Cloud account to interact with Salesforce Marketing Cloud APIs. If you have both in place, we can start by creating a new SMS message.

Create a new message in MobileConnect

Go to Mobile Studio > Mobile Connect and click on Create Message. Choose Outbound and click on Next. In Message Setup, choose a Name, Short/Long Code to be used, From Name and choose API Trigger as the Send Method. Click on Next, type the Outbound Message text and choose the Next Keyword if needed. To finalize, click on Activate. Before you confirm, note the API Key displayed in the pop-up:

The message will now be visible in the Overview screen – make sure it’s status is Active/Scheduled.

Trigger the message using API

In order to trigger a text message, we will have to interact with Salesforce Marketing Cloud’s REST API using the /sms/v1/messageContact/{id}/send route, but before we do that, we will need to authenticate.

Authenticate using Server-Side JavaScript

Let’s start by installing a new, or identifying an existing installed package in your Marketing Cloud account. Note the Client Id and Client Secret as we will need them to authenticate our API request. Make sure that SMS is enabled in the scope of the package you are using:

Depending on the type of the package installed (v2 – enhanced functionality or v1 – legacy functionality), use one of the following code snippets to cover the authentication part of the script.

v1: [see code snippet on Github]

v2: [see code snippet on Github]

Make a messageContact API Request

Below is an example messageContact API Request. The phone number passed in the payload must use the correct format for the designated country code. For example, a mobile number from the United States must include the numerical country code 1 and the area code, eg: 13175551212. [see code snippet on Github]

To ensure that the mobile number exists for the contact and that the contact subscribed to the specified keyword on your short code, set the Subscribe and Resubscribe values to true and specify the keyword parameter. If you’re not sure how to work with keywords, check out this help document: Keywords and Codes.

If the request is valid, the API returns a token that can be used to make a follow-up call to check the status of the request: [see code snippet on Github]

Now, let’s combine the first script snippet we used to authenticate with the messageContact payload and make a POST request. Below will work with the v1 legacy package: [see code snippet on Github]

In the above script, you will need to provide your endpoints, ClientId and ClientSecret (all three can be found in Setup > Apps > Installed Packages). You will also need to insert the message Api Key, the keyword and pass the recipient’s phone number.

Last but not least, always remember to put security measures into practice when setting up this kind of functionality on a CloudPage to prevent your ClientId and ClientSecret from being exposed.


Questions? Comments?

Leave a comment below or email me at zuzanna@sfmarketing.cloud.

Loops in AMPscript and Server-Side JavaScript

In programming languages, loops are a basic, yet a very powerful and indispensable concept. They shorten the code and reduce the need to repeat tasks. A loop is a set of instructions to be executed until a certain condition is met. In this article, we will focus on the most fundamental kind of loop, the for loop, and it’s usage in AMPscript and Server-Side JavaScript.

For loops in AMPscript

NOTE: In this article, we will focus on understanding the basic concepts of working with loops in Salesforce Marketing Cloud. For a strictly technical specification, defer to the following article: AMPscript Process Loops.

A for loop, which is actually the only loop available in AMPscript, lets you execute the same script repeatedly until an ending condition is met.

Let’s use the following example: we have a Data Extension with customer IDs and their ordered items. We want to use that dataset to send an email to each customer, listing the items each of them ordered.

Here’s our Data Extension called Orders:

CustomerIdOrderIdOrderItem
0031t000005D98UAAS4632Women’s Marine Hoodie
0031t000005D98UAAS4632Glass Love Bottle – 16.9 oz
0031t000005D98UAAS4632Eco Ballpoint Pen
0031t00000ZnTENAA33686Men’s Marine Hoodie
0031t00000YEM4ZAAX7354Leather Hampton Watch

In our example, the script contained within the loop would do the following: display a bullet point and display OrderItem name, and repeat the same action until all the OrderItems for a relevant Customer were displayed.

The most important element of any loop is the counter. The counter will define how many times the script in the loop should be executed. In order to define the counter, we must first set the criteria to find all the matching results in our Data Extension. We will use the LookupRows function to look up all rows, that match the Id of the Customer, that we want to send the email to. Then, we will use the RowCount function to determine how many results were found. The outcome of the RowCount function will be our counter and will decide how many times the script inside the loop will be repeated. Here’s the first part of our script, where we count how many records match the criteria: [click here to see the code on Github]

Now let’s think through the loop logic. This is the verbal description of the loop that we would like to build:

Start at 1 and repeat the following in a loop until you reach the number defined in the RowCount variable: display the current index and the name of the OrderItem found in the referring row from the results of the LookupRows function. Increase the index by one and repeat the process. Stop looping once the index reaches the number defined in the counter.

Here’s how this looks in AMPscript: [click here to see the code on Github]

You will notice the next keyword at the end of the loop – each time this keyword is reached, the system compares the current index to the value of the counter defined by the RowCount function. If the value is not equal to the end index, the loop will repeat until the end index is reached.

Here’s a full script that we can now use in an email, with added exception handling that will show “No items to display” in case the LookupRows function doesn’t find any matching records for a subscriber in the Orders Data Extension: [click here to see the code on Github]

For loops in Server-Side Javascript

While JavaScript offers at least five different kinds of loops, and all of those can be used in Salesforce Marketing Cloud, in this article we will focus on the most basic one, the for loop.

We will create a similar solution to the one created in the AMPscript example above. We will use the same Data Exteniosn called Orders and we will use a loop to display all the OrderItems for a Customer on a CloudPage.

The first thing we have to do in order to interact with a data extension via server-side JavaScript is to initialize the Data Extension object. Then, we will use the Server-Side JavaScript Rows.Lookup function to find all rows that match the Id of the Customer. For the purpose of this tutorial, we will hardcode the CustomerId into the script: [click here to see the code on Github]

The above script will return an ArrayList, which is a collection of elements. Arrays use numbers to access its elements and the numbering always starts at zero:

Arrays in JavaScript are zero-based. This means that JavaScript starts counting from zero when it indexes an array. In other words, the index value of the first element in the array is “0” and the index value of the second element is “1”, the third element’s index value is “2”, and so on.

https://blog.kevinchisholm.com/javascript/javascript-array-length-always-one-higher/

In AMPscript we used the RowCount function to determine the counter for our loop. In JavaScript, we will use the Array length Property. Inside the loop, we will display the current index (i) and the name of the element (OrderItem) that has this index number in the ArrayList. Remember that we will start counting at “0”, not at “1” like we did in AMPscript.

Then, we will increase the index by one and repeat the process.

In JavaScript, the ++ notation is the increment operator, which means that i++ is exactly the same thing as i = i+1. The script will stop looping once the index reaches the number defined in the counter (rows.length). Here’s the script: [click here to see the code on Github]

Here’s the full script that we can now use on a CloudPage, with added exception handling that will show “No items to display” in case there are no matching records found in the Orders Data Extension: [click here to see the code on Github]

The is how the results will be displayed on a CloudPage:

Additional resources

Here is a list of additional resources to help you understand both the general concept of loops, as well as using loops in AMPscript and Server-Side JavaScript:


Questions? Comments?

Leave a comment below or email me at zuzanna@sfmarketing.cloud.

Update multiple non-sendable Data Extensions to be sendable

In order to programmatically update the settings of an existing Data Extension, we will interact with Salesforce Marketing Cloud’s SOAP Web Services API using WSProxy. Code snippets in this article will show you how to update a Data Extension, so that a non-sendable Data Extension is turned into a sendable Data Extension, but you can modify the script to update other properties of a Data Extension, like retention settings or field properties.

DataExtension object

The DataExtension object represents a data extension within an account. In order to turn a non-sendable Data Extension into a sendable one, we will have to update three of the object’s properties:

  • IsSendable (xsd:boolean) – Indicates whether you can use a data extension as part of an audience for a message send.
  • SendableDataExtensionField (DataExtensionField) – Indicates the field within a sendable data extension to use as an address as part of a send. Possible values include SubscriberID, CustomerKey, or EmailAddress. The application uses this field to establish a data relationship between a value specified by the SendableSubscriberField property and a value within a sendable data extension.
  • SendableSubscriberField (Attribute) – Indicates field to use as sending address. The application uses this field to establish a data relationship between a subscriber field and a value specified by the SendableDataExtensionField property.

To put it in simple words, we need to set the IsSendable value to true and establish which field in the data extension relates to the Subscriber table. If you do it from the UI, you can for example set it to “ContactKey relates to Subscribers on Subscriber Key” or “EmailAddress relates to Subscribers on Subscriber Key”. Here, we will do exactly the same thing, using the following structure:

SendableDataExtensionField relates to subscribers on SendableSubscriberField

Update Data Extension properties via WSProxy

We will use the updateItem WSProxy function to interact with the DataExtension object. Below script will identify a Data Extension by it’s External Key (CustomerKey), set the IsSendable field to true and establish the following send relationship: “email relates to Subscribers on Subscriber Key”, where email is the Data Extension field of type EmailAddress.

The possible values of the SendableSubscriberField include “Subscriber Key” or “Email Address”, depending on whether the Subscriber Key business rule has been turned on. This is the tricky part of this script, as upon retrieving the properties of a sendable Data Extension, the results will return SendableSubscriberField.Name as “_SubscriberKey”, but you actually need to use “Subscriber Key” in the update call.

Here’s the script that will update a single Data Extension:

Update multiple Data Extensions in one call

We have two possible ways to go when it comes to updating multiple Data Extensions in one call.

If you’re working with a set of Data Extensions that have an identical field name and data type assigned to the field used in the send relationship, for example email field of type EmailAddress, you can use a simple loop to iterate through an array of Data Extension External Keys:

If the field names vary across the Data Extensions, it’s best to use the updateBatch WSProxy function and define properties of each Data Extension separately:

Additional resources

If you would like to learn more about using WSProxy and the DataExtension object, I highly recommend reading Gortonington’s article, WSProxy to copy a data extension.

Retrieve tracking data since account inception using WSProxy

Whether you’re building a data warehouse or are dealing with a legal compliance issue, access to historical tracking data from your Salesforce Marketing Cloud account using the out-of-the-box features is limited.

Data Views are powerful, but only allow you to query for up to six months of subscriber and tracking information.

Tracking extracts provide granular tracking data regarding several different aspects of email send jobs, such as clicks, bounces and unsubscribes. They are not time-restricted like Data Views, but if you want to get tracking data from a specific time range, the start and end dates can only be up to 30 days apart.

The third option to access historical data is to reach out to Salesforce support and ask them for a data export for a specific time range, but this service will come at a hefty price.

The method of retrieving tracking data using SOAP API and WSProxy also has some limitations, mostly related to performance when working with big data volumes, but it can be very useful in many cases where using Data Views or Tracking Extracts is not enough.

Retrieve Tracking Data with SOAP API

To retrieve tracking data using the SOAP API, we will call the SentEvent, OpenEvent, ClickEvent, BounceEvent and UnsubEvent objects, which will allow us to create a structure similar to the one we know from Data Views. Each of those objects has a persistent set of properties, which include: BatchID, ClientID, EventDate, SendID, SubscriberKey and TriggeredSendDefinitionObjectID.

Here is an example SOAP envelope that you could use in Postman to retrieve data from any of the tracking event objects:

Interact with SOAP API using WSProxy

To retrieve data from the tracking event objects using WSProxy, we will have to specify the properties to retrieve and perform the retrieve on each of the objects we are interested in. Here’s an example of retrieving data from the SentEvent object:

We can also add a filter to narrow down the results. You can filter the results by JobID, SubscriberKey or any other object property. Here, we are going to filter by EventDate, which will show us all the events that took place in the given timeframe:

If you run the above script in an account that sends large volumes of emails, you will notice that it only pulls a part of the results and displays a status message: MoreDataAvailable. That’s because the SOAP API returns up to 2500 records at a time per retrieve call. To retrieve all available data for a given timeframe, we need to include pagination of retrieves in our script. Let’s also add an HTML table, so that data is displayed in a more accessible way:

You can do the same with the remaining objects, here are the scripts:

Write retrieved data into a Data Extension

Although this will increase the processing time of the call, it will allow you to have the data ready for further processing without any additional preparations. Below script will create a new Data Extension called 01_SentEvent in your main Data Extensions folder and insert all the retrieved data.

Here are the scripts that will do the same for the remaining objects:

Performance of the retrieve calls

The official Marketing Cloud SOAP API documentation states the following:

In most production implementations, data volume in the account requires you to include specific JobIDs in the filter criteria of the request. If requests that don’t specify a JobID time out during processing, add a JobID in the filter. If specifying a JobID is not possible, or if your implementation requires a broad range of JobIDs, use a data extract-based procedure instead.

Above is true if you are sending heavy volumes of emails each month, but you are not limited to filtering by JobID. You can include any of the object properties in filter criteria. You can, for example, retrieve all send and tracking history for a specific subscriber if you use the SubscriberKey in the filter: filter = {Property: "SubscriberKey", SimpleOperator: "equals", Value: "{{SubscriberKey}}"}

If you’re experiencing time outs when working with the script, try narrowing down the amount of retrieved data by using filters.

Security

Last but not least, always remember to put security measures into practice when setting up this kind of functionality on a CloudPage to prevent your data from being exposed in a breach. For the script to run and either return results onscreen or insert them into a Data Extension, you don’t have to actually publish the CloudPage – just press “Publish”, without further saving it. Or, to be completely safe – create a Script Activity in Automation Studio and run it from there.

Retrieve client IP address and geolocation in CloudPages

There are many reasons for checking the client IP address, most common include tracking and personalization. What can you find out about the visitors of a webpage from their IP address? You can identify their ISP, figure out approximately where they’re located and see how often they (or someone else sharing their router) visit your website.

In the context of CloudPages, we most often see IP tracking for personalization purposes. By identifying the visitor’s location, you can automatically display text in their local language and control what kind of content they see.

Identify client IP using AMPscript

The X-Forwarded-For (XFF) HTTP header is a standard header for identifying the originating IP address of a client connecting to a web server. You can easily access this header by using the AMPscript HTTPRequestHeader function, which will return a specified header from an HTTP request. Here’s how to retrieve an IP address on a CloudPage using AMPscript:

Identify client IP using SSJS

There are dedicated Server-Side JavaScript HTTP Properties Functions, that allow you to retrieve various types of HTTP Request object properties and platform application values. The client browser passes this information to the server during an HTTP interaction, so this object contains information regarding the browser and session. One of the available properties to use with the HTTP Request object is ClientIP, which returns the IP address of the requesting client as a string value. Here’s how to retrieve an IP address on a CloudPage using SSJS:

This is the preferred way to retrieve the client IP, as Request.ClientIP() is a dedicated and supported function, while using the XFF HTTP header proved to be unreliable in the past.

HTTP Properties Functions allow you to retrieve other useful information, for example, browser metadata or the URL of the referring web address.

Discover the precise physical location of a given IP address

The functionality of identifying a physical location of a given IP address requires using a third party API service. There are many IP Geolocation API providers and most of them have a free plan available, as well as paid plans for bigger enterprises. My preferred one is ipify.org, which allows you to run up to 1000 queries per month for free. Once you register, you will obtain your personal apiKey, that will be used for making the calls:

The response will contain information about the country, region, city, latitude, longitude, postal code, timezone and GeoNames Id. Additionally, it will also show autonomous system (AS) info if available.

Click here to see this script in action.

As a side-note, remember that under GDPR, IP addresses are considered personal data. Tracking the IPs of your EEA based users without their consent falls under the rules of GDPR.

Send a triggered email using WSProxy

Triggered sends allow you to automatically send personalized and timely messages to your subscribers. They are sent to an individual subscriber in response to a subscriber action. If you would like to find out more about creating a Triggered Email Message Interaction, check out my other article here.

TriggeredSend object

The TriggeredSend object represents a specific instance of a triggered email send. A typical SOAP envelope consists of the Triggered Send CustomerKey (External Key of the Triggered Email Message Interaction), Subscribers associated with the send and optionally, their Attributes. Here’s an example:

Create a TriggeredSend using WSProxy

WSProxy is a new object for Server-Side JavaScript, introduced by Salesforce in 2018. It acts as a proxy between the Marketing Cloud SOAP Web Service and SSJS. The WSProxy object is native to the platform and simpler to use than the SSJS methods, that’s why it reduces overhead and increases the speed of API calls. WSProxy uses JSON to pass object properties instead of SOAP’s native XML, which makes it much easier to read and write.

To create a new TriggeredSend, we will use the createItem WSProxy function, which has three parameters:

  • The first parameter is the object type to perform the action on – here, we will use previously mentioned TriggeredSend object
  • The second parameter is a JavaScript object which represents the fields and values to set on the object when created – in below example, we will call it tsDef and use it to define the CustomerKey, Subscribers and optionally, their Attributes
  • The third parameter is optional and includes any properties to be set using the SOAP CreateOptions object

Here’s the full script:

In the above script, you will need to provide the Triggered Send External Key and pass an Email Address and Subscriber Key.

If you are using personalization strings in your Triggered Email, you can pass them as name and value pairs in the Attributes object. Here’s an example of passing additional attributes in the WSProxy call:

The results of the call contain three properties from the SOAP CreateResult object: Status, RequestID, and Results. Here’s an example response:

To see how this script works in action, visit the CloudPage that I created and submit your email address here.

Here are additional resources to learn more about Triggered Sends and WSProxy:

Find a Data Extension and it’s folder path using SSJS

If you work with a lot of Data Extensions in multiple folders, you know the pain of using the built-in search feature. It only searches the folder that you’re in, with the exclusion of any sub-folders, which is simply impractical.

Below, I would like to show you how to find a Data Extension and it’s path using Server-Side JavaScript: which functions to use and how to iterate through them.

If you’re not interested in the technical part and want to jump straight into building the search app, click here.

SSJS Data Extension and Folder Functions

In order to find a Data Extension, we will use two SSJS Core functions: DataExtension.Retrieve and Folder.Retrieve. The first function will help us identify the Data Extension, either by its name or the External Key. The second function retrieves an array of folders based on the specified criteria. It also retrieves details regarding the parent folder of a given folder if one exists, and that’s what we will use to build the Data Extension path.

In the above script, you will need to define two variables, DEprop and DEval, depending on whether you have the name or the External Key of the Data Extension. You can paste the script on a CloudPage, define the two variables, and once you click on the “Publish” button, the script will be executed and results will be visible on-screen, without the need to actually publish the CloudPage:

Create a simple Data Extension search app

If users of your instance of Salesforce Marketing Cloud often struggle with finding Data Extensions, you can create an app on a CloudPage to help them navigate the folders. By adding a simple form, you can enable the users to perform a search from a CloudPage:

Paste the below code onto a CloudPage and publish it. Anyone with access to the link will be able to search for Data Extensions located in the Business Unit where the CloudPage was created. If the CloudPage has been created in the Parent Business Unit, they will also be able to search the Shared Data Extensions folder.

Last but not least, always remember to put security measures into practice when setting up this kind of functionality on a CloudPage, to prevent your data from being exposed in a breach.

PS. There is a free tool available called SFMC Object Finder. It’s a Chrome extension that lets you search for a variety of objects, like images, data extensions and other assets, in your instance of Salesforce Marketing Cloud. All it requires is that you have an active session of Salesforce Marketing Cloud open in your Chrome browser. However, if you cannot install this extension or need to be able to find Data Extensions programmatically, you can use Server-Side JavaScript to achieve it!

Unsubscribe and Log an UnsubEvent with a LogUnsubEvent Execute Call

The LogUnsubEvent provides a convenient way of handling unsubscribes when you create your own unsubscribe landing page or profile center functionality. This call allows you to unsubscribe a subscriber and log an UnsubEvent that is tracked against a specific Job, which means that you will be able to track from which email they unsubscribed and see the results on the tracking dashboard. You can configure the call to either unsubscribe a subscriber from a specific list, publication list, or all subscribers, which will effectively unsubscribe them from receiving any emails.

What’s more important, if you’re using Marketing Cloud Connect to connect with your Salesforce Sales or Service Cloud org, the unsubscribe will be captured on the subscriber record in Sales/Service Cloud. It will automatically check the Email Opt Out (HasOptedOutOfEmail) flag and will also be visible in the Individual Email Results for the corresponding email send.

The LogUnsubEvent Execute call uses the following parameters:

  • SubscriberID – The Marketing Cloud generated ID that uniquely identifies a subscriber.
  • SubscriberKey – The client supplied ID that uniquely identifies a subscriber.
  • EmailAddress – The email address of the subscriber.
  • JobID – The ID of the Job that sent the message.
  • ListID – The ID of the List that the subscriber belonged to. You can use subscriber or publication lists (not suppression lists).
  • BatchID – The ID of the Batch within the Job.
  • Reason – (Optional) The reason the subscriber is being unsubscribed.

The parameters can be divided into 3 sections:

  1. Subscriber context
  2. Job context
  3. Unsub reason

If you make this call from the parent unit of an Enterprise 2.0 account, ensure that you include the ClientID of the child business account to return information specific to that business unit.

Subscriber Context

The Subscriber Context is defined by the SubscriberID, SubscriberKey and EmailAddress parameters. You must supply at least one of these parameters. If you provide more than one of these parameters, we retrieve the Subscriber using one of the values and validate that the other values match the retrieved Subscriber. If they don’t match, an error returns.

If the SubscriberKey permission is turned on and you supply the EmailAddress parameter, you must supply either the SubscriberID or the SubscriberKey.

Job Context

The Job Context is defined by the JobID, ListID and BatchID parameters. These values are used to determine which Job the UnsubEvent is tracked against. The subscriber is also unsubscribed from the List that the Job was sent to. You don’t need to supply all three values. The system looks up any missing values using the following rules:

  1. If the JobID is supplied, we can lookup a missing ListID and/or BatchID.
  2. If the ListID is supplied, we can lookup a missing JobID and/or BatchID.
    1. If the JobID is missing, we use the most recent JobID that the subscriber was sent to.
    2. This may not be the Job that the Subscriber is acting upon.
  3. If only the BatchID is supplied, we cannot lookup the remaining information and the job context is not defined.

If the job context cannot be established because you did not supply any of these parameters or only supplied the BatchID, the UnsubEvent is not created. The subscriber is also Master Unsubscribed from the system of being unsubscribed from a particular list. Remove the ListID to address the All Subscribers list in an account.

Unsub Reason

This is used to specify the reason the subscriber is being unsubscribed from the system. If the reason is not supplied, the default value is used: Unsubscribed via Log Unsub Event Execute call.

Here is an example SOAP Request envelope:

We will now look at three different ways to implement this solution on a CloudPage.

LogUnsubEvent using AMPscript

This is probably the most common way to use the LogUnsubEvent call. Below script will retrieve the SubscriberKey, JobId, ListId and BatchId if you link to the unsubscribe page from your email using the CloudPagesURL function. Depending on whether a list/publication list was selected for the send, it will unsubscribe a subscriber from that particular list, or it will unsubscribe the subscriber from all emails if you used All Subscribers.

LogUnsubEvent using Server-Side JavaScript

The implementation of the LogUnsubEvent call in SSJS will be almost identical to the AMPscript solution, as the methods for accessing SOAP object data with SSJS are primarily wrappers around AMPScript functions.

Like in the previous example, the script will retrieve the SubscriberKey, JobId, ListId and BatchId if you link to the unsubscribe page from your email using the CloudPagesURL function and will unsubscribe a subscriber either from a list or All Subscribers, depending on which one you use at send time.

LogUnsubEvent using WSProxy

WSProxy is a new object for Server-Side JavaScript, introduced by Salesforce in 2018. It acts as a proxy between the Marketing Cloud SOAP Web Service and SSJS. The WSProxy object is native to the platform and simpler to use than the SSJS methods. The object reduces overhead and increases the speed of your API calls.

Therefore, the below script is the most simple, and what’s more important, the fastest way to execute the LogUnsubEvent API call. In a speed test ran using the Chrome DevTools, it proved to be the fastest one to load on a CloudPage, with AMPscript just slightly slower and SSJS the slowest one, taking twice as much time to load.

Just like in the previous examples, the script will retrieve the SubscriberKey, JobId, ListId and BatchId if you link to the unsubscribe page from your email using the CloudPagesURL function and will unsubscribe a subscriber either from a list or All Subscribers, depending on which one you use at send time.

If you would like to find out more about logging an UnsubEvent or WSProxy, check out the following articles:

Salesforce Marketing Cloud API Authentication using Server-Side JavaScript

In order to interact with Salesforce Marketing Cloud APIs you need to create an installed package in your Marketing Cloud account first. Marketing Cloud uses installed packages to help authenticate users and API requests. To create and install packages you must have the Administrator or Marketing Cloud Administrator role assigned to your profile.

Marketing Cloud has two types of installed packages: packages with enhanced functionality (v2) and packages with legacy functionality (v1). If you’re not sure which package has been installed in your account, check the “Details” tab of your installed package – all legacy packages have a banner at the top indicating that it’s a legacy package and a Licenses tab. Enhanced packages have an Access tab.

Note the Authentication Base URI , Client Id and Client Secret as you will need them to authenticate. Below code examples are meant for Server-to-Server Integrations with Client Credentials Grant Type.

Request access token for a Legacy Package

The following script will allow you to authenticate if you’re using the Legacy Package. As of August 1, 2019, Marketing Cloud has removed the ability to create legacy packages, but you can still use legacy authentication and API requests with existing legacy packages.

You will need to insert the Client Id and Client Secret and your tenant-specific authentication endpoint (Authentication Base URI). Bare in mind, that it is not a good idea to publish Client credentials on a CloudPage.

The access token will be valid for 60 minutes and it is issued with the scopes specified on the API integration in Installed Packages. With Legacy Packages, the access token can only be used in the context of the business unit that created the integration.

Request access token for Enhanced Packages

For this package, you will need to insert the Client Id and Client Secret, your tenant-specific authentication endpoint (Authentication Base URI) and define grant_type as "client_credentials" for server-to-server integrations. You can also specify two optional parameters, scope and account_id. If you don’t include the scope parameter in the request, the token is issued with the scopes specified on the API integration in Installed Packages. For a full list of permissions click here. Account ID is the MID of the target business unit. Use this parameter to switch between business units. If you don’t specify account_id, the returned access token is in the context of the business unit that created the integration. Again, bare in mind, that it is not a good idea to publish Client credentials on a CloudPage.

The access token has a lifetime of 20 minutes. In the response you will also see the scope, rest_instance_url (your tenant’s REST base URL for making REST API calls) and soap_instance_url (your tenant’s SOAP base URL for making SOAP API calls).

Token type will always be “Bearer”, regardless of the package you are using.

To learn more about Marketing Cloud APIs, visit the Trailhead module Marketing Cloud APIs and the official documentation: Intro to Marketing Cloud APIs.