Skip to content

A collection of reusable SSJS utility functions for SFMC.

License

Notifications You must be signed in to change notification settings

ttntm/sfmc-utils

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

General Remarks

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.

Usage

  1. Run ./build.sh input_list_file merge_file to build the library
  2. Place the code from the merged file between the usual <script runat="server"> and the closing </script> tags
  3. Initialize the wrapper class, i.e. var util = sfmcUtils()
  4. 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.

VS Code

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.

Functional Documentation

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.

Variables

api

Stores an instance of WSProxy which is used in the following functions:

  • processDataExtRow()
  • getAllRows()
  • logUnsubEvent()
  • setMID()
  • updateAllSubscribersList()

utilMID

Stores the SFMC Business Unit MID once set using the function setMID().

Functions

processDataExtRow()

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.

Params
  • ext: string - Data extensions external key
  • data: object -An object containing the data to write into the table
  • upsert: boolean - Switches between operating modes; upsert == false means insert
Returns

Boolean

Helper function for log row generation.

Params

  • 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 incoming POST requests

Returns

Object

Used to update a record in an SF CRM object.

Params

  • 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

Returns

Object | undefined

Triggers SFMC contact deletion via API.

Docs: REST Reference

Requires valid token data obtained from a getToken() call.

Params

  • tokenData: object - SFMC REST API token
  • contactKeys: string[] - An array of contact keys deletion should be triggered for

Returns

Object | undefined

This function deletes a row in an SFMC data extension.

The target data extension must have a Primary Key column.

Params

  • ext: string - Data extensions external key
  • pkCol: string - Primary Key column name
  • pkVal: string - Primary Key value, used to identify the row to delete

Returns

Boolean

Get all rows from an SFMC data extension.

Use this one for bigg/er tables - regular lookups have a hard 2000 row limit.

Params

  • ext: string - Data extension external key
  • cols: string[] - An array of columns to retrieve from the DE
  • filter: object - Filter definition object (see: ssjsdocs/complex-filters)

Returns

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.

Params

  • ext: string - Data extensions external key
  • fieldNames: string[] - Names of fields used to build the WHERE clause
  • values: string[] - Values used to build the WHERE clause

Returns

Object | undefined

Used to obtain an SFMC REST API token via REST API at /v2/token (more info: official docs).

Params

  • 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 var utilMID if empty

Returns

Object | undefined

This function inserts a row into an SFMC data extension.

Uses the private method processDataExtRow().

Params

  • ext: string - Data extensions external key
  • data: object - An object containing the data to write into the table

Returns

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.

Params

  • subscriberKey: string - An SFMC SubscriberKey
  • email: string - The subscriber's email address
  • asListId: number - List Id for AllSubscribers

Returns

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().

Params

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

Returns

Object | undefined

Wrapper for fieldsToNull calls, using updateSalesforceObject() internally.

They are special UpdateSingleSalesforceObject() calls with a slightly different order of arguments.

Params

  • sfObject: string - SF object, i.e. 'account'
  • sfId: string - SF object id
  • fields: string[] - List of fields to process

Returns

Void

Triggers a response via HTTP using the plaform library function Write().

Params

  • msg: any - Message value

Returns

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().

Params

  • mid: string - SFMC Business Unit MID

Returns

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.

Params

  • tokenData: object - SFMC REST API token
  • eventData: object - Journey entry event as per API specification

Returns

Object | undefined

Used to set a subscriber's status in the All Subscribers List.

Params

  • 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'
    }
  ]
}

Returns

Boolean

Used to update a record in an SF CRM object.

Params

  • type: string - SF CRM object API name, i.e. "Contact", "ns_CustomObject__c"
  • sfObjId: string - SF CRM record id, i.e. 003... for a ContactKey
  • props: object - An object containing the fields to update and their new values

Returns

Object | undefined

Used to insert/update (upsert) a row into an SFMC data extension.

Params

  • ext: string - Data extensions external key
  • data: object - An object containing the row data to write into the table

Returns

Boolean

Wrapper for SFDC Apex REST usage.

Can also be used to interact with the Salesforce standard API endpoints.

Params

  • 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
}

Returns

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.

Params

  • input: object - A flat object
  • requiredFields: string[] - An array of required fields

Returns

Boolean

Verify a Google ReCaptcha payload. See: https://developers.google.com/recaptcha/docs/verify#api-response

Params

  • apiKey: string - Google API key
  • grcToken: string - A ReCaptcha token from the front end

Returns

Boolean

License

MIT; see ./LICENSE

Credits

Large parts of the build script are based on this project: MERGEJS