Forked from wvpv/sfmc-update-salesforce-objects-with-ssjs.html
Last active
May 27, 2020 11:10
-
-
Save katydorjee/0d5f752110257520d02351296930383e to your computer and use it in GitHub Desktop.
Update Salesforce Objects with Server-Side JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript" runat="server"> | |
Platform.Load("core", "1"); | |
var debug = 1; | |
if (Request.Method == "POST") { | |
// retrieve the input values from the form payload | |
var subscriberKey = Request.GetFormField("subscriberKey"); | |
var email = Request.GetFormField("email"); | |
var firstName = Request.GetFormField("firstName"); | |
var lastName = Request.GetFormField("lastName"); | |
// ensure the subscriberKey has a value | |
if (!isEmpty(subscriberKey)) { | |
try { | |
// update the SF object indicated by the subscriberKey | |
var updateSFResults = updateSF(subscriberKey,0,email,firstName,lastName); | |
if (debug) { | |
Write("<br>updateSFResults: " + updateSFResults); | |
} | |
} catch (e1) { | |
if (debug) { | |
Write("<br>e1: " + Stringify(e1)); | |
} | |
} // of catch | |
} // of sk check | |
} // of post | |
function isEmpty(str) { | |
return (!str || 0 === str.length); | |
} | |
function updateSF(subscriberKey, HasOptedOutOfEmail, Email, FirstName, LastName) { | |
var results = 0; | |
var SFIDPattern = new RegExp("^[a-zA-Z0-9]{18}"); | |
if (SFIDPattern.test(subscriberKey) == true) { | |
var fieldArr = []; | |
fieldArr.push('HasOptedOutOfEmail'); | |
fieldArr.push(HasOptedOutOfEmail); | |
fieldArr.push('Email'); | |
fieldArr.push(Email); | |
if (!isEmpty(FirstName)) { | |
fieldArr.push('FirstName'); | |
fieldArr.push(FirstName); | |
} | |
if (!isEmpty(LastName)) { | |
fieldArr.push('LastName'); | |
fieldArr.push(LastName); | |
} | |
// detect Contact or Lead | |
var sfObj = subscriberKey.substring(0,3) == "003" ? "Contact" : "Lead"; | |
var updateSFObject = ""; | |
updateSFObject += "\%\%[ "; | |
updateSFObject += "set @SFUpdateResults = UpdateSingleSalesforceObject('" + sfObj + "',"; | |
updateSFObject += "'" + subscriberKey + "','"+ fieldArr.join("','") + "'"; | |
updateSFObject += ") "; | |
updateSFObject += "output(concat(@SFUpdateResults)) "; | |
updateSFObject += "]\%\%"; | |
try { | |
results = Platform.Function.TreatAsContent(updateSFObject); | |
} catch (e2) { | |
if (debug) { | |
Write("<br>e2: " + Stringify(e2)); | |
} | |
} | |
} | |
return results | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment