Install Guide

HTTPRequestHeader

Enables the AMP function HTTPRequestHeader in SSJS

This function returns a specified header from an HTTP request. This function is only available in landing pages, microsites and CloudPages. It cannot be used in other Marketing Cloud applications.

NOTE: Only headers that are available in the page request return a value. For example, if a user pastes a URL into a web browser instead of clicking on a page hyperlink (from another web page), the Referer header value will be empty.

new HTTPRequestHeader(key: string)
Parameters
key (string) An HTTP header as defined in RFC 7231
Related
HTTPRequestHeader

UpdateSingleSalesforceObject

Enables the AMP function UpdateSingleSalesforceObject in SSJS

This function updates a record in a Sales or Service Cloud standard or custom object. The function returns 1 if the record is updated successfully or 0if it fails.

NOTE: Additional API field name and value pairs can be appended as arguments.

NOTE: Certain Salesforce objects enforce record-locking when a record is modified, to ensure the referential integrity of data. This applies to records that have a relationship to lookup records in a different object. If the function is used to asynchronously update multiple records (for example, the function is included in an email) and the object has lock contention, the records may fail to update.

new UpdateSingleSalesforceObject(sfObject: string, id: string, parameters: array)
Parameters
sfObject (string) API name of the Salesforce object.
id (string) Record identifier to update
parameters (array) Array of name-valiue pair to update
Related
UpdateSingleSalesforceObject

RetrieveSalesforceObjects

Enables the AMP function RetrieveSalesforceObjects in SSJS

This function retrieves fields from a record in a Sales or Service Cloud standard or custom object. The function returns a row set of fields.

NOTE: Additional API field name, comparison operator and value sets can be appended as arguments. However the function joins these additional sets using AND clauses.

NOTE: This function should only be used in applications that do not require a high volume of requests or return a large number of records; for example, an email send to a small audience, a Triggered Send, or the retrieval of a single record on a landing page.

NOTE: The function may take several seconds to execute, impacting email send performance and may result in a timeout if the request volume is high for example; using a process loop to execute the function multiple times or returning a large number of rows. Unlike other AMPscript functions that return a row set — for example, LookupRows which limits the number of rows to 2000 — there is not the same type of limitation on the number of rows returned by this function.

new RetrieveSalesforceObjects(sfObject: string, fieldNames: array, parameters: array): object
Parameters
sfObject (string) API name of the Salesforce object.
fieldNames (array) Comma-separated array of API field names to retrieve
parameters (array) Set of arrays where each array is one set of filter
1: API field name to match record
2: Comparison operator for matching records. Valid operators include:
= equal to
< less than
> greater than
!= not equal to
<= less than or equal to
>= greater than or equal to
3: Value to match record using comparison operator in 2
Returns
object: The result of the request
Related
RetrieveSalesforceObjects

CloudPagesURL

Enables the AMP function CloudPagesURL in SSJS

Provides a way for users to reference a CloudPages URL in an account from an email message. Use this function in an email to pass information via a URL in an encrypted query string. For example, you could share a single unsubscription or profile center page for use in any sent email message. This method passes information in an encrypted query string without passing subscriber information or values in clear text.

new CloudPagesURL(pid: integer, parameters: object): string
Parameters
pid (integer) Page ID for the landing page reference in the URL. Locate this value on the appropriate CloudPage content details page. Page ID can be from the enterprise (EID) or the business unit (MID) where the function is used.
parameters (object) Name-Value pair for additional parameters included in encrypted query string
Returns
string: A full URL

SHA1

Enables the AMP function SHA1 in SSJS

This function converts the specified string into a SHA1 hex value hash.

new SHA1(string: string, encoding: string): string
Parameters
string (string) String to convert
encoding (string = UTF-8) Character set to use for character-encoding. Valid values are UTF-8 (default) and UTF-16
Returns
string: The string as a SHA1 hex value hashed

SHA256

Enables the AMP function SHA256 in SSJS

This function converts the specified string into a SHA256 hex value hash.

new SHA256(string: string, encoding: string): string
Parameters
string (string) String to convert
encoding (string = UTF-8) Character set to use for character-encoding. Valid values are UTF-8 (default) and UTF-16
Returns
string: The string as a SHA256 hex value hashed

SHA512

Enables the AMP function SHA512 in SSJS

This function converts the specified string into a SHA512 hex value hash.

new SHA512(string: string, encoding: string): string
Parameters
string (string) String to convert
encoding (string = UTF-8) Character set to use for character-encoding. Valid values are UTF-8 (default) and UTF-16
Returns
string: The string as a SHA512 hex value hashed

DataExtensionRowCount

Enables the AMP function DataExtensionRowCount in SSJS

This function returns the number of rows in the specified Data Extension.

NOTE: This function will not return row counts from the System Data Views.

new DataExtensionRowCount(dataExtensionName: string)
Parameters
dataExtensionName (string) Name of the Data Extension from which to retrieve a row count
Related
DataExtensionRowCount

cloudpage

Copyright: email360
Author: Sascha Huwald
Since: 2020
Version: 1.0.0
License: MIT

Collection of wrapper functions for the usage of Cloudpages.

cloudpage(auth: (string | object)?, setting: object?)
Parameters
auth ((string | object)?) Defines if the cloudpage should be protected Possible values "jwt", "login".
setting (object?) Used to update the settings object with a custom setting object
Example
// initialise a new cloudpage instance
var cp = new cloudpage();

// initialise a new cloudpage instance with a login requirement
var cp = new cloudpage('login');

// initialise a new cloudpage instance with a jwt token requirement
var cp = new cloudpage('jwt');
Instance Members
payload
authToken()
authLogin()
expireCookie(cookieName)
logout(redirectUrl?)
setCookie(cookieName, value, expire?)
isPayload(data, isRequired?)
newToken(pid, expire?, payload?, access?)
readToken(token)
isTokenValid(token)
redirectError(payload?)

logError

Log an error to a DataExtension

Centralised version of error logging in SSJS script. Not recommended in batch Emails - use AMP error log for this purpose instead. On error, a record will be written to the error log DE.

This function requires a DataExtension defined in settings.de.logError

logError(o: object): string
Parameters
o (object) Holds the data for the error log.
Name Description
o.method string The method calling the error.
o.message string The error message for better understanding of the error.
o.source string A detailed name of the error origin. E.g. [Email] Survey.
o.subscriberKey string? If given, the subscriberKey triggering the error
o.jobid number? The JobId if the error is caused from an email sent.
o.listid number? The ListId if the error is caused from an email sent.
o.batchid number? The BatchId if the error is caused from an email sent.
o.sourceType string? The SourceType. e.g. Email, Web, CRM.
o.raiseError boolean? Indicates whether an error should be raised to stop an email from sending out. Only works in Email Studio. A value of true skips the send for current Subscriber and moves to next Subscriber A value of false stops the send and returns an error.
Returns
string: The eventId for the error.

logWarning

Log a warning to a DataExtension.

This function requires a DataExtension defined in settings.de.logWarning.

logWarning(o: object): string
Parameters
o (object) Holds the data for the warning log.
Name Description
o.method string The method calling the warning.
o.message string The warning message for better understanding of the warning.
o.source string A detailed name of the warning origin. E.g. [Email] Survey.
o.subscriberKey string? If given, the subscriberKey triggering the warning
o.jobid number? The JobId if the warning is caused from an email sent.
o.listid number? The ListId if the warning is caused from an email sent.
o.batchid number? The BatchId if the warning is caused from an email sent.
o.sourceType string? The SourceType. e.g. Email, Web, CRM.
Returns
string: The eventId for the warning.

isObject

Check if value is an object.

isObject(value: any): boolean
Parameters
value (any) The value to check.
Returns
boolean:

dateAdd

Add units to a datetime

dateAdd(dt: date, number: number, unit: string): date
Parameters
dt (date) The original date
number (number) Numbers to add to the dt
unit (string = Hours) Units to add ['Seconds','Minutes','Hours','Days','Months','Years'] .
Returns
date: The new date

dateSubtract

Subtract units to a datetime

dateSubtract(dt: date, number: number, unit: any, units: string): date
Parameters
dt (date) The original date
number (number) Number to subtract from the dt
unit (any)
units (string = Hours) Units to subtract ['Seconds','Minutes','Hours','Days','Months','Years'] .
Returns
date: The new date

getDateFromDateTime

Remove time from given DateTime

getDateFromDateTime(dt: date): date
Parameters
dt (date) The datetime
Returns
date: Date

getDateUTC

Get the current UTC Date

getDateUTC(): date
Returns
date: UTC Date

getUnixTimestamp

Get the current UnixTimestamp

getUnixTimestamp(): number
Returns
number: The current UnixTimestamp in UTC

dateDiffInHours

Get the difference in hours between two datetimes

dateDiffInHours(d1: date, d2: date): number
Parameters
d1 (date) Date 1
d2 (date) Date 2
Returns
number: hours difference

dateDiffInDays

Get the difference in days between two datetimes

dateDiffInDays(d1: date, d2: date): number
Parameters
d1 (date) Date 1
d2 (date) Date 2
Returns
number: days difference

timeConvert

Convert minutes into a human readable form

timeConvert(m: number): string
Parameters
m (number) Miniutes given
Returns
string:

groupBy

Group an array of object by one property

groupBy(data: array, key: string): array
Parameters
data (array) An array of objects
key (string) The property or accessor
Returns
array: the grouped array
Related
StackOverflow RobMathers Git

inObject

Check if a string is in the object

inObject(needle: string, haystack: object): boolean
Parameters
needle (string) The string to find in the object.
haystack (object) The object to search.
Returns
boolean:

inObjectRecursive

Check if a string is in the object) recursively.

inObjectRecursive(needle: string, haystack: object): boolean
Parameters
needle (string) The string to find in the object.
haystack (object) The object to search.
Returns
boolean:

shuffle

Shuffles an array.

shuffle(a: array): array
Parameters
a (array) Array containing the items.
Returns
array: The suffeled array

deleteArrayItem

Delete item in array.

deleteArrayItem(array: array, item: string): array
Parameters
array (array) Array containing the item.
item (string) The item to be deleted
Returns
array: The new array

createAmpVariables

Create AMP variables from an object

createAmpVariables(value: object)
Parameters
value (object) A name and value object.
Example
// creates 3 AMP variables
createAmpVariables({
     email: 'info@email360.io',
     source: 'Email360',
     url: 'http://www.email360.io'
});

console_log

SSJS wrorkaround to use console server side

console_log()

debug

Display the message appropriate to the Debugging Mode

debug(message: string)
Parameters
message (string) The message to be displayed.

wait

Wait for n Miliseconds

wait(ms: number)
Parameters
ms (number) Miliseconds to sleep

isContentBlockByKey

Validates if the contentBlock with the given key exists

isContentBlockByKey(customerKey: string): boolean
Parameters
customerKey (string) The ContentBlockKey
Returns
boolean:

getPageUrl

Returns the current page URL optional with parameters

getPageUrl(withParam: boolean): string
Parameters
withParam (boolean = false) Keep parameters from the url
Returns
string:

isCustomerKey

Verify if the given string is a possible SFMC default CustomerKey

isCustomerKey(str: string): boolean
Parameters
str (string) The string to be tested
Returns
boolean:

httpRequest

Perform an HTTP request allowing the usage of API methods.

httpRequest(method: string, url: string, contentType: string?, payload: object?, header: object?): object
Parameters
method (string) The method to use e.g: POST, GET, PUT, PATCH, and DELETE
url (string) The url to send the request to
contentType (string?) The contentType to use e.g: application/json
payload (object?) A payload for the request body
header (object?) Header values as key value pair
Returns
object: Result of the request

getRandomData

Generate a random string for the given fieldType

Allowed types: Decimal,EmailAddress,Boolean,Number Date, Phone, Locale, Text.

getRandomData(fieldType: string): string
Parameters
fieldType (string) Defines the data to be generated.
Returns
string: The generated data string

sfmcapi

Copyright: email360
Author: Sascha Huwald
Since: 2020
Version: 1.0.0
License: MIT

Collection of wrapper functions for the usage of the Salesforce Marketing Cloud REST API.

sfmcapi(setting: object?)
Parameters
setting (object?) Used to update the settings object with a custom setting object
Example
// initialise a new sfmcApi instance
var rest = new sfmcApi();
Instance Members
getToken()
isValidToken()
triggerJourneyEvent(contactKey, eventDefinitionKey, data)
uploadImage(imageBase64, imageName, imageType, folderId, description)
retrieveSendDefinitions(filter?, retrieveAll)
emailPreview(url)
emailPreviewSusbcriber(emailId, contactId)
emailPreviewList(emailId, listId)
emailPreviewListSubscriberId(emailId, listId, subscriberId)
emailPreviewListSubscriberKey(emailId, listId, subscriberKey)
emailPreviewDataExtensionSubscriberId(emailId, dataExtensionId, subscriberId)
emailPreviewDataExtensionSubscriberKey(emailId, dataExtensionId, subscriberKey)
emailPreviewDataExtensionRow(emailId, dataExtensionId, dataExtensionRow)
sendTestEmail(emailId, recipients, dataSource, sendClassificationId, deliveryProfileId?, senderProfileId?, prefix)
triggerSMSMessage(messageId, phoneNumbers, keyword?, params?)
retrieveSMSMessageStatus(messageId, tokenId)
createScriptActivity(name, script, folderId?, description?)
retrieveScriptActivity(id)
retrieveScriptActivities(filter?, retrieveAll)
retrieveScriptActivityId(name)
retrieveScriptActivitiesInFolder(folderId)
retrieveScriptActivityFolderId(id)
retrieveScriptActivityCustomerKey(id)
retrieveScriptActivityDescription(id)
retrieveScriptActivityScript(id)
retrieveScriptActivityStatus(id)
retrieveScriptActivityCreatedDate(id)
retrieveScriptActivityModifiedDate(id)
validateScript(script)
updateScriptActivity(id, payload)
updateScriptActivityName(id, name)
updateScriptActivityDescription(id, description)
updateScriptActivityScript(id, script)
updateScriptActivityCustomerKey(id, customerKey)
moveScriptActivity(id, folderId)
triggerScriptActivity(id)
deleteScriptActivity(id)

wsproxy

Copyright: email360
Author: Sascha Huwald
Since: 2020
Version: 1.0.0
License: MIT

Collection of wrapper functions for the usage of WSProxy.

WSProxy functions library in server-side Javascript for
Salesforce Marketing Cloud (SFMC).

Note: WSProxy can only be used in non sending enviroment.

wsproxy(mid: number?, setting: object?)
Parameters
mid (number?) The BuisnessUnit MID for enterprise integrations. In order to access other business units, the library must be added to the master Business Unit.
setting (object?) Used to update the settings object with a custom setting object
Example
// initialise a new wsproxy instance
var prox = new wsproxy();
Instance Members
api
retrievableCols(objectType)
retrievableColsValues(cols, req)
createDataExtension(name, fields, folderId)
createDataExtensionDemo(name, num, folderId)
retrieveDataExtension(id)
retrieveDataExtensions(filter?, retrieveAll)
retrieveDataExtensionProperty(id, property)
retrieveDataExtensionCustomerKey(id)
retrieveDataExtensionName(id)
retrieveDataExtensionObjectID(id)
retrieveDataExtensionCategoryID(id)
retrieveDataExtensionModifiedDate(id)
retrieveDataExtensionNames(filter?, retrieveAll)
retrieveDataExtensionCustomerKeys(filter?, retrieveAll)
retrieveDataExtensionWithNoFolder()
retrieveDataExtensionFolderPath(id)
isDataExtension(id)
isDataExtensionFolder(folderId, id)
moveDataExtension(id, folderId)
deleteDataExtension(id)
copyDataExtension(id, newName?, withRecords, newFolderId)
clearDataExtension(id)
renameDataExtension(id, newName)
updateDataExtension(id, properties)
retrieveDataExtentionTemplate(id)
retrieveDataExtentionTemplates(filter?, retrieveAll)
retrieveDataExtentionTemplateProperty(id, property)
retrieveDataExtentionTemplateCustomerKey(id)
retrieveDataExtentionTemplateName(id)
retrieveDataExtentionTemplateObjectID(id)
retrieveDataExtentionTemplateCategoryID(id)
retrieveDataExtentionTemplateModifiedDate(id)
retrieveDataExtentionTemplateNames(filter?, retrieveAll)
isDataExtentionTemplate(id)
deleteDataExtentionTemplate(id)
createDataExtensionRecords(id, data)
retrieveDataExtensionRecords(id, filter, retrieveAll)
upsertDataExtensionRecords(id, data)
deleteDataExtensionRecords(id, data)
createDataExtensionFields(id, fields)
retrieveDataExtensionFields(id)
retrieveDataExtensionFieldNames(id)
retrieveDataExtensionFieldProperty(id, fieldName, property)
retrieveDataExtensionFieldCustomerKey(id, fieldName)
retrieveDataExtensionFieldObjectID(id, fieldName)
deleteDataExtensionField()
updateDataExtensionField()
createDataFolder(name, description, parentFolderId)
retrieveDataFolder(id)
retrieveDataFolders(filter?, opts?, props?, retrieveAll)
retrieveDataFolderPath(customerKey, objectType)
retrieveDataFolderProperty(id, property)
retrieveDataFolderID(name)
retrieveDataFolderName(id)
retrieveDataFolderObjectID(id)
retrieveDataFolderContentType(id)
retrieveDataFolderCustomerKey(id)
deleteDataFolder(id)
isDataFolder(id)
isDataFolderEmpty(id)
renameDataFolder(id, newName)
moveDataFolder()
retrieveSubscribers(filter, retrieveAll)
upsertSubscriberRecords(records)
deleteSubscriberRecords(records)
retrieveTrackingEvent(trackingEvent, filter?, retrieveAll)
retrieveOpenEvent(filter?, retrieveAll)
retrieveClickEvent(filter?, retrieveAll)
retrieveBounceEvent(filter?, retrieveAll)
retrieveUnsubEvent(filter?, retrieveAll)
retrieveAutomation(id)
retrieveAutomations(filter?, retrieveAll)
triggerAutomation(id)
triggerAutomationWait(id, repeat, sleep)
createAutomation()
createQueryDefinition(queryName, queryText, updateType, targetId, folderId)
retrieveQueryDefinition(id)
retrieveQueryDefinitions(filter?, retrieveAll)
retrieveQueryDefinitionProperty(id, property)
retrieveQueryDefinitionCustomerKey(id)
retrieveQueryDefinitionName(id)
retrieveQueryDefinitionObjectID(id)
retrieveQueryDefinitionCategoryID(id)
retrieveQueryDefinitionNames(retrieveAll)
deleteQueryDefinition(id)
performQueryDefinition(id)
retrieveQueryDefinitionStatus(taskId)
isQueryDefinitionComplete(taskId)
retrieveAsset(id)
createAssetScriptContentBlock(name, content, folderId?, customerKey?, description?)
createAssetImage(imageBase64, imageName, imageType, folderId?, description?)
logUnsubEvent(subscriberKey, emailAddress, jobId, listId, btachId, unsubReason?)
createEmailSendDefinition()
sendTestEmail()
retrieveTriggeredSendDefinition(id)
retrieveTriggeredSendDefinitions(filter?, retrieveAll)
retrieveTriggeredSendDefinitionProperty(id, property)
retrieveTriggeredSendDefinitionCustomerKey(id)
retrieveTriggeredSendDefinitionName(id)
retrieveTriggeredSendDefinitionObjectID(id)
retrieveTriggeredSendDefinitionCategoryID(id)
retrieveTriggeredSendDefinitionStatus(id)
retrieveTriggeredSendDefinitionNames(retrieveAll)
retrieveActiveTriggeredSendDefinitions(retrieveAll)
retrieveTriggeredSendSummary(customerKey)
retrieveTriggeredSendSummaryBounces(customerKey)
retrieveTriggeredSendSummaryClicks(customerKey)
retrieveTriggeredSendSummaryConversions(customerKey)
retrieveTriggeredSendSummaryInProcess(customerKey)
retrieveTriggeredSendSummaryCreatedDate(customerKey)
retrieveTriggeredSendSummaryModifiedDate(customerKey)
retrieveTriggeredSendSummaryNotSentDueToError(customerKey)
retrieveTriggeredSendSummaryNotSentDueToOptOut(customerKey)
retrieveTriggeredSendSummaryNotSentDueToUndeliverable(customerKey)
retrieveTriggeredSendSummaryObjectID(customerKey)
retrieveTriggeredSendSummaryOpens(customerKey)
retrieveTriggeredSendSummaryOptOuts(customerKey)
retrieveTriggeredSendSummaryQueued(customerKey)
retrieveTriggeredSendSummarySent(customerKey)
retrieveTriggeredSendSummaryUniqueClicks(customerKey)
retrieveTriggeredSendSummaryUniqueConversion(customerKey)
retrieveTriggeredSendSummaryUniqueOpens(customerKey)
sendTriggeredSend(customerKey, recipients)