Manage Contacts and Leads in Marketing Cloud Journeys directly from your Salesforce org

This week Salesforce Labs has released a Lightning Component which, no doubt, will make the life easier for anyone working with Journey Builder and Marketing Cloud Connect.

If you have multiple Journeys set up in your account with different Salesforce Entry Events, you probably know the pain of finding out which Sales/Service Cloud Contacts and Leads are currently in the Journeys. And if you need to eject a Contact/Lead from a Journey immediately? You either end up doing it in POSTMAN or developing your own app on CloudPages just for that purpose.

Marketing Cloud Journeys for Salesforce is a Lightning Component which can be added to the Contact, Lead, Case or Account page and it will display the list of Salesforce Marketing Cloud Journeys that the subscriber is currently in, along with a stop button to allow instant removal of said subscriber from the Journey.

It’s available for free from AppExchange: Marketing Cloud Journeys for Salesforce, and you need to have Admin permissions in both Sales/Service Cloud and in Marketing Cloud to be able to install it.

Here’s the high level overview of the installation process (detailed guide can be found here):

  1. Install the managed package from AppExchange: Marketing Cloud Journeys for Salesforce
  2. Create a Package in Marketing Cloud with the component: API integration > Web App
  3. In your Salesforce org, configure Auth. Provider with type Open ID Connect and paste all the details of the Marketing Cloud API package created in the previous step
  4. In your Salesforce org, configure the Named Credential and test the Authentication Flow on save
  5. Add the Lightning Component to Record Pages by opening any Contact, Lead, Case or Account and clicking on the Setup menu at the top right and choosing Edit Page

One important prerequisite, which is not clearly described in the installation guide, is the requirement to have a “Contact Key” field on the object for which you want to display the component. You do not need to create that field separately – it’s enough that you just point to the field containing the ID used as Subscriber Key in Marketing Cloud, for example Lead Id or Contact Id:

Now the updated page will display the component and list all the Journey names and their current active version, in which the subscriber is present:

It will also give you the option to eject the subscriber from a selected Journey, or from all active Journeys:

Upon clicking on the Stop/Stop All Journeys option, you will be prompted to confirm:

Conslusion

Salesforce Labs is closing a major gap in the cross-cloud functionality with this small, yet powerful and much needed addition. The component has proven to work correctly in the few simple tests I gave it and I would recommend anyone using Salesforce Marketing Cloud’s Journey Builder with Sales/Service data to also give it a go.


Questions? Comments?

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

Add subscribers to a Journey from a CloudPage using Fire Entry Event

Firing an Entry Event is great for injecting contacts into a Salesforce Marketing Cloud journey, especially if you need to be able to inject them from an external system or a website.

It’s also useful when you’re creating a custom form on a CloudPage and would like to replicate the behavior of SmartCapture forms, which allow injecting contacts to a journey upon form submission (real-time).

In order to use the Fire Entry Event on a CloudPage, we will build a simple form to capture the end user’s email address and we will use REST API to post the collected information to /interaction/v1/events route using Server-Side JavaScript. But first, let’s start with creating a new journey in Salesforce Marketing Cloud’s Journey Builder.

API Event Entry Source

When you create the journey for use with a custom form on a CloudPage, the only difference in the setup is the entry source, which in this case will be the API Event.

The API event in Journey Builder connects the journey canvas to an API used to admit contacts into a journey. When the API fires an event, the contacts entering the journey are stored in a Marketing Cloud data extension you choose. You can set a filter using Marketing Cloud data attributes to ensure that only intended customers enter the journey.

When you drag and drop the API Event into your journey’s canvas, click on it and choose to create an event. You will be prompted to choose a Data Extension for use with the journey and you will also see that an Event Definition Key has been created for your journey – copy it, as we will need it later for our script. Activate the journey.

Custom form on a CloudPage

We can now create our form on a CloudPage. For the purpose of this tutorial, it will be a very simple form collecting just the end user’s email address. We will also add some AMPscript to process the data from the form. If you haven’t created a form on a CloudPage yet, you might want to check out this article first: Create a Sales Cloud-integrated lead capture form using AMPscript. Here’s a basic form for our use case:

Fire an Entry Event using API

In order to inject a contact from our form into a journey, we will use Salesforce Marketing Cloud’s REST API, specifically the /interaction/v1/events route. Here’s an example request:

And an example response, which would indicate that the request has been processed correctly:

Like with any other API call, we will need to start with authentication. If you are not familiar with the concept, check out my other article, Salesforce Marketing Cloud API Authentication using Server-Side JavaScript.

As a security measure, it’s best to store your Client Id and Secret as encoded values in a Data Extension to avoid exposing them in your script. My preferred way is to use the EncryptSymmetric and DecryptSymmetric AMPscript functions for encryption, and a simple lookup to get their values from a Data Extension.

Here’s how the authentication part could look like:

Once we obtain the access_token and the rest_instance_url, we can move on to our actual call. We will pass the access_token in the authentication header, and in the payload, we will pass the data collected through the form and our journey’s event definition key. To get the form data, we will use an undocumented Server-Side JavaScript function, Request.GetQueryStringParameter(). Remember to include all the values passed in the payload in your target Data Extension, which you chose earlier upon creating the journey. Here we have just one such field, called email_field:

The full script

If you put all the above together, you should end up with something like this:


If you would like to see this script in action, enter your email address on a demo CloudPage I set up: https://pub.s10.exacttarget.com/hkphfaftk4b


Questions? Comments?

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

Create a CloudPages form with an image/file upload option

The HTML <input> tag specifies an input field where the user can enter data. An input field can vary in many ways, depending on the type attribute. The <input> elements with type="file" let the user choose one or more files from their device storage. The file can then be manipulated using JavaScript in order to process it further.

In this article, we will focus on creating a CloudPages form with an image input field, and uploading that image into Marketing Cloud’s Content Builder. The high-level outline of this process, which can be found in this Stack Exchange post, is: once the file has been uploaded via the form, it needs to be Base64 encoded, and then passed in a REST API call to the /asset/v1/content/assets route in order to create the image in Content Builder.

We will need to create two separate CloudPages: the first one will run client-side JavaScript in order to encode the file into a Base64 string and it will then pass it to the second CloudPage, which will run server-side JavaScript to make an API call to create a new asset in Content Builder.

I will break it down into smaller parts to make it easier to understand the different steps along the way.

Create an input field

Let’s start with creating an <input> field on a CloudPage. The input needs to be of the type="file" in order to allow the end-user to choose a file for upload from their local machine. We will also add an accept attribute, which specifies a filter for what file types the user can pick from the file input dialogue box. For our use case, it will be image/*: [see code snippet]

We also need to include an id attribute in order to be able to reference the input field in JavaScript.

Encode the image using Base64

Base64 is a group of binary-to-text encoding schemes which enable storing and transferring data over media that are designed to deal with ASCII (text) only. In order to encode the image, we will use the FileReader.readAsDataURL() method to securely read the contents of a file stored on the user’s computer and return a result attribute containing a data: URL representing the file’s data. We will use the addEventListener() method to attach a click event to the Upload button, which will trigger the encoding function: [see code snippet]

The format of the returned result is the following:

data:[<mediatype>][;base64],<data>

The mediatype is a MIME type string, such as ‘image/jpeg’ for a JPEG image file and <data> is the Base64 encoded string representing the uploaded file.

Fetch the data to processing page

We now need to pass the data onto our second CloudPage for further processing. The reason why we are using two pages instead of one is that client-side JavaScript is run after the server-side is complete, which makes it impossible to run them in reverse order on the same page.

In order to pass the data between our CloudPages, we will use the fetch() method. But first, let’s prepare the data that we will need for our API call: [see code snippet]

  • base64enc is the encoded string which represents the image
  • fullFileName is the full name of the file uploaded by the user (eg. “astro.png”)
  • fileName is the first part of the file name, before the filename extension (eg. “astro”)
  • assetName is the filename extension (eg. “png”)

Once we have the above, we can POST it in JSON format to the processing page that will contain the server-side script. Our request will look like this: [see code snippet]

where the method is POST, headers specify that the content-type is JSON and in the JSON body we will have three attribute-value pairs, base64enc, fileName and assetName.

The fetch() method argument is the path to the CloudPage containing our server-side script, so, for now, you can create an empty CloudPage just to obtain the link.

The fetch() method returns a promise that resolves to a response to that request, whether it is successful or not: .then(function(res) / .catch(function(err).

The full client-side script

Let’s now put all of the above elements together to create our first CloudPage. The complete code will look like this: [see code snippet]

Now we can move on and prepare the second part of the script.

Retrieve the posted data

In order to retrieve the data posted from our first CloudPage, we will use the getPostData() server-side JavaScript method, which sadly is not documented in the official Server-Side JavaScript Syntax Guide, but you can read about it in this post on Salesforce Stack Exchange. Once we access the body of our request, we can parse the data using the ParseJSON() function: [see code snippet]

Prepare the data for API call

Now we can prepare the data for our API call. Let’s take a look at an example JSON body of a create asset request: [see code snippet]

In the above, the first name represents the name of the file. The second parameter assetType, consists of a name which represents the file extension and an id of the asset type. Asset types are the file or content types supported by Content Builder and the full list can be found here: List of Asset Types.

Let’s prepare the data and match the asset type based on the name of the file extension: [see code snippet]

If you’re only going to upload images, you don’t need to include the whole list of asset types – the ones that start with “2” will be sufficient.

Create an asset using REST API

In order to make an API call using the /asset/v1/content/assets route, we first need to authenticate. You will need the Installed Package for API integration, the Client Id and Cient Secret. If you’re not sure how to authenticate programmatically in Salesforce Marketing Cloud, refer to my article, Salesforce Marketing Cloud API Authentication using Server-Side JavaScript.

As a security measure, it’s best to store your Client Id and Secret as encoded values in a Data Extension to avoid exposing them in your script. My preferred way is to use the EncryptSymmetric and DecryptSymmetric AMPscript functions for encryption, and a simple lookup to get their values from a Data Extension.

Here’s the code snippet for the authentication part:

Once we obtain the accessToken, we will need to include it in our final API call, along with the rest_instance_url: [see code snippet]

The above call will create an image in Content Builder’s main folder and return the following response: [see code snippet]

The full server-side script

Here is the full script for our second CloudPage: [see code snippet]

You can now go back to your first CloudPage and start uploading!

To see this script in action, visit my CloudPage.


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.

Subscribe to Automation Studio notifications via SOAP API

If you have used Automation Studio to build workflows on autopilot, you are certainly aware of the importance of monitoring. Checking manually the execution status of every automation in your account is tedious and exhausting. Sometimes, you need to be notified in real time so you can fix eventual issues. That is why having email notifications enabled on your automations is necessary.

There are two types of notifications to which you can subscribe on automation settings:

  • Error or skipped run: you will receive an email if the automation’s execution fails or is skipped
  • Run Completion: you will receive an email once the automation’s run completes.

Keep in mind that at this moment, the only official way of interacting with Automation Studio via API is through SOAP. I’m saying “official” because there are actually some undocumented, but very limited, REST endpoints that can be used to play with Automation Studio. Let me know in the comments if you are interested.

Therefore, if we check the official SOAP documentation, we will see that creating an automation along with activities and email notifications in its settings is pretty easy and straightforward. However, if we look closer, we will find a comment on the notification tag saying: DOES NOT WORK. But we are not going to accept this for an answer, aren’t we?

This is the SOAP request sample from the documentation to create an automation: [see code snippet on Github]

To find the source of the problem, we should get into the tags responsible for adding email notifications to the settings. In this example, they are using a wrong value for the NotificationType tag in addition to a missing ChannelType tag.

NotificationType should be either “Complete” OR “Error” and definitely not “-1”. And ChannelType should be equal to 1.

The correct SOAP request to create an automation along with a “Complete” notification email should look like this: [see code snippet on Github]

For the curious ones, you may be asking how I found the working values. I invite you to go to Automation Studio, open the Chrome Developer Tools (F12) and click on the Network tab.

Open an automation, add your email to the settings and click done. Now go check out the Network tab. There is a REST call to the endpoint below.

Given the fact that we can only interact with Automation Studio using SOAP calls for now, we can understand why the endpoint is beta and not officially documented:

https://mc.s50.exacttarget.com/rest/beta/automations/notifications/AUTOMATION_ID/

Now let us look at the request payload:

We can see that the values used for NotificationType and ChannelType are as described above. That was worth a try and it worked: [see code snippet on Github]

I invite you to check the network tab every time you need to interact with Salesforce Marketing Cloud APIs. It can be very interesting and full of undocumented information.

If you know someone that can correct this on the official documentation, please get in touch through the comments or send me a message on LinkedIn.


About the author

Rachid Mamai is a SFMC geek and a Digital Marketing enthusiast living in France. To get in touch with Rachid, visit his LinkedIn.

Get Journey history by filtering the Definition ID via API

In today’s article, we will be going through a non-documented way of getting journey’s history through the API. The majority of this information is available on the UI. However, having a second way of getting this data in raw format can be helpful in some use cases. You can use free software like POSTMAN to interact with Marketing Cloud’s API and follow the steps in this article.

Let’s start by setting the correct scopes in Salesforce Marketing Cloud.

Set scope on Contacts and Journeys

When requesting our access token, we need to provide scopes used by our API calls. Do not forget to enable the Journeys & List and Subscribers scopes on the Installed package. We will be using these two scopes to get our journey’s history. Check out “Introduction to SFMC APIs” article for in-depth information about Installed packages setup and Salesforce Marketing Cloud APIs.

We need to set the scopes on the payload to get our access token: [see code snippet on Github]

Get Journey’s Definition ID

In this step, we will be getting information about a specific journey. The undocumented endpoint “interaction” provides access to a range of data, including the DefinitionID. Before getting into it, let me explain the differences between the three different identifiers of a journey:

  • Id: A unique id of the journey assigned by the journey’s API during its creation
  • Key: A unique id of the journey within the MID. Can be generated by the developer
  • DefinitionId: A unique UUID provided by Salesforce Marketing Cloud. Each version of a journey has a unique DefinitionID while the Id and Key remain the same.

Since the journey’s history is version dependent, we will be using DefinitionID to get history of a specific version.

Let us start by making a call to the below endpoint using name=JOURNEY_NAME as a URL parameter. By default, mostRecentVersionOnly parameter is set to true, therefore, the call will return information of the most recent version of the journey. Use VersionNumber=VERSION_NUMBER and mostRecentVersionOnly=false to get information about a specific version. Note that more parameters are available but not covered in this article since irrelevant: [see code snippet on Github]

The DefinitonID is located in a nested array called items, something like: [see code snippet on Github]

Get Journey’s history by filtering via Definition ID

We are finally there. In this step, we will call the endpoint below: [see code snippet on Github]

The payload should be something like below. Do not forget to set the Content-type as application/json on the call’s parameters: [see code snippet on Github]

You can apply multiple filters by setting different variables in the payload. In this example, we are selecting history data for our journey starting from October 23, 2019 to now. The journey is identified by the DefinitionID in the DefinitionIds array parameter in the payload. Other filters are:

  • Page and PageSize: For results pagination. The page starts from one.
  • Extras: represents a list of additional data to fetch. Available values are all, activities, outcomes and stats.
  • OrderBy: You can order by CreatedDate
  • MostRecentVersionOnly: To get information about the most recent versio of the journey. Accepts a true or false value.

This call will return something like below depending on the payload: [see code snippet on Github]


About the author

Rachid Mamai is a SFMC geek and a Digital Marketing enthusiast living in France. To get in touch with Rachid, visit his LinkedIn.

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: