This is collection of reusable SSJS utility functions for SFMC.
The code should cover most of the use cases that will eventually come up in almost every marketing cloud project.
Questions?
Please use GitHub Discussions.
- Run
./build.sh input_list_file merge_file
to build the library - Place the code from the merged file between the usual
<script runat="server">
and the closing</script>
tags - Initialize the wrapper class, i.e.
var util = sfmcUtils()
- Use the utility you need in your CloudPage, Code Resource or Script Activity
The default include.txt
files contains 100% of the utility functions; it can be built using the following command:
./build.sh include.txt util_full.js
You can change the files pulled in from include.txt
at any time, but it's probably better to just create a new file if/when you want to build a smaller version of the library.
When creating a new Code Resource: code-resource.template.js
, a boilerplate file for HTTP POST
triggered endpoints, can be found in the root directory.
A (project/workspace) scoped snippet based on code-resource.template.js
can be found in the ./.vscode/
folder. IntelliSense should be able to work with it in JS/TS files.
This section lists all provided untility functions and offers a brief description for each one of them.
This files contains private variables and methods that are not exposed in the object that the initialization call returns.
Stores an instance of WSProxy which is used in the following functions:
processDataExtRow()
getAllRows()
logUnsubEvent()
setMID()
updateAllSubscribersList()
Stores the SFMC Business Unit MID once set using the function setMID()
.
Private method used to insert/upsert a value into an SFMC data extension.
Uses API.updateItem()
for upsert operations and API.createItem()
for insert operations.
ext
: string - Data extensions external keydata
: object -An object containing the data to write into the tableupsert
: boolean - Switches between operating modes;upsert
==false
means insert
Boolean
Helper function for log row generation.
env
: string - Environment marker, i.e. "dev", "prod" etc.data
: object - Any kind of input data, i.e. an object received by the endpoint via incomingPOST
requests
Object
Used to update a record in an SF CRM object.
type
: string - SF CRM object API name, i.e. "Contact", "ns_CustomObject__c"props
: object - An object containing the new record's fields and values
Object | undefined
Triggers SFMC contact deletion via API.
Docs: REST Reference
Requires valid token data obtained from a getToken() call.
tokenData
: object - SFMC REST API tokencontactKeys
: string[] - An array of contact keys deletion should be triggered for
Object | undefined
This function deletes a row in an SFMC data extension.
The target data extension must have a Primary Key column.
ext
: string - Data extensions external keypkCol
: string - Primary Key column namepkVal
: string - Primary Key value, used to identify the row to delete
Boolean
Get all rows from an SFMC data extension.
Use this one for bigg/er tables - regular lookups have a hard 2000 row limit.
ext
: string - Data extension external keycols
: string[] - An array of columns to retrieve from the DEfilter
: object - Filter definition object (see: ssjsdocs/complex-filters)
Object[]
A function to query row data from an SFMC data extension. Wraps the DE Lookup()
function.
NB: This function is hard-coded to return only one result. Use getAllRows() if you want to retrieve multiple rows.
ext
: string - Data extensions external keyfieldNames
: string[] - Names of fields used to build theWHERE
clausevalues
: string[] - Values used to build theWHERE
clause
Object | undefined
Used to obtain an SFMC REST API token via REST API at /v2/token
(more info: official docs).
auth
: object - Client id/secret to use for the token request; expects an object of the following type:{ client_id: string, client_secret: string }
- Recommendation: retrieve the credentials from a DE, do not hard-code them in the SSJS code
mid
: string | null - Business unit MID; only included in the token request if available; falls back to private varutilMID
if empty
Object | undefined
This function inserts a row into an SFMC data extension.
Uses the private method processDataExtRow()
.
ext
: string - Data extensions external keydata
: object - An object containing the data to write into the table
Boolean
This function logs an unsubscribe event in SFMC.
It uses API.execute()
and falls back to Subscriber.Unsubscribe()
if the WSProxy call didn't succeed.
subscriberKey
: string - An SFMC SubscriberKeyemail
: string - The subscriber's email addressasListId
: number - List Id for AllSubscribers
Boolean
Retrieves the specified fields from a Salesforce object based on a specific field value (i.e. PersonContactId
).
Wraps the AMPScript function RetrieveSalesforceObjects()
and calls it using Platform.Function.TreatAsContent()
.
objectName
: string - Salesforce object, i.e. 'Account'
targetFields
: string[] - SF API names of the fields to retrieve
lookupField
: string - Field to use for the lookup, i.e. 'Id'
lookupValue
: string - Value to check in lookupField
Object | undefined
Wrapper for fieldsToNull
calls, using updateSalesforceObject() internally.
They are special UpdateSingleSalesforceObject()
calls with a slightly different order of arguments.
sfObject
: string - SF object, i.e. 'account'sfId
: string - SF object idfields
: string[] - List of fields to process
Void
Triggers a response via HTTP using the plaform library function Write()
.
msg
: any - Message value
HTTP response body; content-type
depends on which kind on Code Resource was used.
Sets a Business Unit MID for the private instance of Script.Util.WSProxy()
.
mid
: string - SFMC Business Unit MID
Void
Triggers a Journey Builder entry event using SFMC's REST API at /interaction/v1/events
(more info: official docs).
Requires valid token data obtained from a getToken() call.
tokenData
: object - SFMC REST API tokeneventData
: object - Journey entry event as per API specification
Object | undefined
Used to set a subscriber's status in the All Subscribers List.
listData
: object - Object containing the data to update the list with
listData
example:
{
SubscriberKey: 'abc_myKey',
EmailAddress: '[email protected]',
Status: 'Active',
Lists: [
{
ID: '123',
Status: 'Active'
}
]
}
Boolean
Used to update a record in an SF CRM object.
type
: string - SF CRM object API name, i.e. "Contact", "ns_CustomObject__c"sfObjId
: string - SF CRM record id, i.e. 003... for a ContactKeyprops
: object - An object containing the fields to update and their new values
Object | undefined
Used to insert/update (upsert) a row into an SFMC data extension.
ext
: string - Data extensions external keydata
: object - An object containing the row data to write into the table
Boolean
Wrapper for SFDC Apex REST usage.
Can also be used to interact with the Salesforce standard API endpoints.
config
: object - SFDC configuration object;payload
must be an object
{
auth: {
client_id: string
client_secret: string
username: string
password: string
},
endpoint: string
payload: object
}
SFDC API result; depends on the endpoint; object, any[], etc.
{
apx_status: 'Success' | 'Error'
apx_data: object | null
apx_message: string | null
}
Checks and object for existence and value.length > 1 of the specified keys.
input
: object - A flat objectrequiredFields
: string[] - An array of required fields
Boolean
Verify a Google ReCaptcha payload. See: https://developers.google.com/recaptcha/docs/verify#api-response
apiKey
: string - Google API keygrcToken
: string - A ReCaptcha token from the front end
Boolean
MIT; see ./LICENSE
Large parts of the build script are based on this project: MERGEJS