Cloud Pages:CloudPages in Salesforce Marketing Cloud are web pages hosted on Salesforce's servers for creating custom content and interactive experiences. Marketers use them for campaigns, data collection forms, and personalized content delivery. Integrated with SFMC features, CloudPages streamline customer engagement and drive results.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Unsubscribe Confirmation</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f9f9f9;
margin: 0;
padding: 0;
}
.container {
max-width: 600px;
margin: 50px auto;
padding: 20px;
background-color: #ffffff;
border-radius: 8px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
}
h1 {
color: #333333;
margin-top: 0;
}
p {
color: #666666;
line-height: 1.6;
}
.logo {
width: 150px;
margin: 20px auto;
}
.footer {
margin-top: 30px;
color: #999999;
font-size: 0.8em;
}
</style>
%%[
/*
This code snippet is responsible for updating the status of a Subscriber object.
It requires the following parameters to be passed:
- subscriberKey: The unique identifier for the subscriber.
- status: The status of the subscriber (e.g., Active, Unsubscribed, Held).
Please ensure that both subscriberKey and status are provided for proper execution.
*/
/* Assign subscriberkey from the query parameter */
SET @subscriberKey = AttributeValue("_subscriberkey")
SET @emailAddress = AttributeValue("emailaddr")
SET @status = "Unsubscribed"
/* Get the Business Unit (BU) MID (Member ID) */
SET @BU_MID = AuthenticatedMemberID()
/* Create a Subscriber object */
SET @subscriber = CreateObject("Subscriber")
SetObjectProperty(@subscriber, "SubscriberKey", @subscriberKey) /* Ensure subscriberKey is provided */
SetObjectProperty(@subscriber, "Status", @status) /* Ensure status is provided */
/* Create a ClientID object and associate it with the Subscriber */
SET @cid = CreateObject("ClientID")
SetObjectProperty(@cid, "ID", @BU_MID)
SetObjectProperty(@cid, "IDSpecified", "true")
SetObjectProperty(@subscriber, "Client", @cid)
/* Set up options for updating the Subscriber */
Set @options = CreateObject("UpdateOptions")
Set @save = CreateObject("SaveOption")
SetObjectProperty(@save, "SaveAction", "UpdateAdd")
SetObjectProperty(@save, "PropertyName", "*")
AddObjectArrayItem(@options, "SaveOptions", @save)
/* Update the Subscriber object with the new status */
/* The updated status, @update_sub_status, and any error code, @update_sub_errorcode, are captured */
Set @subscribersStatus = InvokeUpdate(@subscriber, @update_sub_status, @update_sub_errorcode, @options)
]%%
</head>
<body>
<div class="container">
<img src="https://www.salesforce.com/news/wp-content/uploads/sites/3/2021/05/Salesforce-logo.jpg" alt="Your Company Logo" class="logo">
<h1>Unsubscribe Successful</h1>
<p>You have been successfully unsubscribed from our newsletter. You will no longer receive emails from us.</p>
<p>If you have any questions or concerns, please contact us at <a href="mailto:info@example.com">info@example.com</a>.</p>
</div>
<div class="footer">
© 2024 Your Company. All rights reserved.
</div>
</body>
</html>
Note: Pass "SubscriberKey" value as a parameter in your CloudPagesURL
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Unsubscribe</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #ecf0f3;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
max-width: 400px;
background-color: #fff;
padding: 30px;
border-radius: 8px;
box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.1);
text-align: center;
}
h1 {
color: #333;
}
p {
color: #666;
margin-top: 20px;
}
form {
margin-top: 20px;
}
button {
padding: 10px 20px;
background-color: #3498db;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #2980b9;
}
.success-message {
color: #27ae60;
margin-top: 20px;
}
.logo {
max-width: 150px;
margin-bottom: 20px;
}
</style>
%%[
/*
This code snippet is responsible for updating the status of a Subscriber object.
It requires the following parameters to be passed:
- subscriberKey: The unique identifier for the subscriber.
- status: The status of the subscriber (e.g., Active, Unsubscribed, Held).
Please ensure that both subscriberKey and status are provided for proper execution.
*/
/* Assign subscriberkey from the query parameter */
SET @subscriberKey = "TEST1234" /*RequestParameter("SubscriberKey") */
SET @submitted = IIF(RequestParameter("Submitted") == "True" , "True", "False")
SET @display="none"
IF @submitted=="True" THEN
SET @status = "Unsubscribed"
/* Get the Business Unit (BU) MID (Member ID) */
SET @BU_MID = AuthenticatedMemberID()
/* Create a Subscriber object */
SET @subscriber = CreateObject("Subscriber")
SetObjectProperty(@subscriber, "SubscriberKey", @subscriberKey) /* Ensure subscriberKey is provided */
SetObjectProperty(@subscriber, "Status", @status) /* Ensure status is provided */
/* Create a ClientID object and associate it with the Subscriber */
SET @cid = CreateObject("ClientID")
SetObjectProperty(@cid, "ID", @BU_MID)
SetObjectProperty(@cid, "IDSpecified", "true")
SetObjectProperty(@subscriber, "Client", @cid)
/* Set up options for updating the Subscriber */
SET @options = CreateObject("UpdateOptions")
SET @save = CreateObject("SaveOption")
SetObjectProperty(@save, "SaveAction", "UpdateAdd")
SetObjectProperty(@save, "PropertyName", "*")
AddObjectArrayItem(@options, "SaveOptions", @save)
/* Update the Subscriber object with the new status */
/* The updated status, @update_sub_status, and any error code, @update_sub_errorcode, are captured */
SET @subscribersStatus = InvokeUpdate(@subscriber, @update_sub_status, @update_sub_errorcode, @options)
SET @display=""
ENDIF
]%%
</head>
<body>
<div class="container">
<img src="https://www.salesforce.com/news/wp-content/uploads/sites/3/2021/05/Salesforce-logo.jpg" alt="Your Logo" class="logo">
<h1>Unsubscribe</h1>
<p>Click the button below to unsubscribe from our newsletter.</p>
<form id="unsubscribeForm" method="post" action="%%=RequestParameter('PAGEURL')=%%">
<input type="hidden" name="SubscriberKey" id="SubscriberKey" value="%%=v(@SubscriberKey)=%%">
<input type="hidden" name="Submitted" id="Submitted" value="True">
<button type="submit">Unsubscribe</button>
</form>
<div style="display:%%=v(@display)=%%">
<p class="success-message" id="successMessage" >You have been successfully unsubscribed.</p>
</div>
</div>
</body>
</html>
Note: For testing purpose, we have used GUID as the subscriber key definitions
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lead Capture Form</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f9f9f9;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.container {
max-width: 400px;
background-color: #fff;
padding: 30px;
border-radius: 8px;
box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
color: #333;
}
form {
margin-top: 20px;
}
label {
display: block;
margin-bottom: 5px;
color: #666;
}
input[type="text"],
input[type="email"] {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
margin-bottom: 10px;
}
button {
width: 100%;
padding: 10px;
background-color: #3498db;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #2980b9;
}
.logo {
display: block;
margin: 0 auto 20px;
max-width: 200px;
}
.success-message {
text-align: center;
color: #27ae60;
margin-top: 20px;
}
</style>
<script runat="server">
Platform.Load('core', '1');
var method=Platform.Request.Method;
Variable.SetValue("@method", method);
try{
</script>
%%[
SET @display = "none"
/* Check if the method is "POST" */
IF @method == "POST" THEN
/* Assign subscriberkey from the query parameter */
SET @subscriberKey = GUID()
SET @firstName = RequestParameter("firstName")
SET @lastName = RequestParameter("lastName")
SET @email = RequestParameter("email")
SET @consent = IIF(RequestParameter("consent") == "True", "True", "False")
SET @display = "none"
SET @status = IIF(@consent == "True", "Active", "Unsubscribed")
/* Get the Business Unit (BU) MID (Member ID) */
SET @BU_MID = AuthenticatedMemberID()
/* Create a Subscriber object */
SET @subscriber = CreateObject("Subscriber")
SetObjectProperty(@subscriber, "SubscriberKey", @subscriberKey) /* Ensure subscriberKey is provided */
SetObjectProperty(@subscriber, "EmailAddress", @email)
SetObjectProperty(@subscriber, "Status", @status) /* Ensure status is provided */
/* Create a ClientID object and associate it with the Subscriber */
SET @cid = CreateObject("ClientID")
SetObjectProperty(@cid, "ID", @BU_MID)
SetObjectProperty(@cid, "IDSpecified", "true")
SetObjectProperty(@subscriber, "Client", @cid)
/* Set up options for updating the Subscriber */
SET @options = CreateObject("UpdateOptions")
SET @save = CreateObject("SaveOption")
SetObjectProperty(@save, "SaveAction", "UpdateAdd")
SetObjectProperty(@save, "PropertyName", "*")
AddObjectArrayItem(@options, "SaveOptions", @save)
/* Update the Subscriber object with the new status */
/* The updated status, @update_sub_status, and any error code, @update_sub_errorcode, are captured */
SET @subscribersStatus = InvokeUpdate(@subscriber, @update_sub_status, @update_sub_errorcode, @options)
SET @upsert =UpsertData("Subscribers", 1,
"SubscriberKey", @subscriberKey,
"Email", @email,
"FirstName",@firstName,
"LastName", @lastName,
"EmailConsent", @consent)
SET @display = " "
ENDIF
]%%
<script runat="server">
}
catch(ex)
{
Platform.Load('core', '1');
Write(Stringify(ex));
}
</script>
</head>
<body>
<div class="container">
<img src="https://www.salesforce.com/news/wp-content/uploads/sites/3/2021/05/Salesforce-logo.jpg" alt="Your Logo" class="logo">
<h2>Sign Up for Updates</h2>
<form id="leadCaptureForm" method="post" action="%%=RequestParameter('PAGEURL')=%%">
<label for="firstName">First Name</label>
<input type="text" id="firstName" name="firstName" placeholder="Enter your first name" required>
<label for="lastName">Last Name</label>
<input type="text" id="lastName" name="lastName" placeholder="Enter your last name" required>
<label for="email">Email Address</label>
<input type="email" id="email" name="email" placeholder="Enter your email address" required>
<label for="consent">
<input type="checkbox" id="consent" name="consent" value="True">
I agree to receive marketing communications.
</label>
<button type="submit">Sign Up</button>
</form>
<div style="display:%%=v(@display)=%%">
<p class="success-message" id="successMessage">Thank you for signing up!</p>
</div>
</div>
</body>
</html>
Allow subscribers to manage their preferences, opt-ins, and opt-outs, ensuring compliance with data privacy regulations like GDPR and CCPA.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Subscription Centers</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f9f9f9;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.container {
width: 90%;
max-width: 600px;
background-color: #fff;
padding: 30px;
border-radius: 8px;
box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;
color: #333;
}
form {
margin-top: 20px;
}
label {
display: inline-block;
width: 30%;
margin-bottom: 5px;
color: #666;
}
input[type="text"],
input[type="email"] {
width: 65%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
margin-bottom: 10px;
}
.preferences label {
display: block;
margin-bottom: 5px;
color: #666;
}
.preferences input[type="checkbox"] {
display: inline-block;
margin-right: 5px;
}
button {
width: 100%;
padding: 10px;
background-color: #3498db;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #2980b9;
}
.logo {
display: block;
margin: 0 auto 10px;
max-width: 100px;
}
.success-message {
text-align: center;
color: #27ae60;
margin-top: 20px;
}
</style>
%%[
var @display,@chkNewsletter,@chkPromotions
SET @display="none"
]%%
<script runat="server">
Platform.Load("core", "1.1");
try {
// Retrieve the HTTP method
var method = Platform.Request.Method;
// Handle GET request
if (method == "GET") {
// Retrieve attributes from context
var email = Attribute.GetValue("emailaddr");
var subscriberKey = Attribute.GetValue("_subscriberkey");
var firstName = Attribute.GetValue("First Name");
var lastName = Attribute.GetValue("Last Name");
}
// Handle POST request
if (method == "POST") {
// Retrieve form field values from the POST request
var email = Platform.Request.GetFormField("email");
var subscriberKey = Platform.Request.GetFormField("subscriberKey");
var firstName = Platform.Request.GetFormField("firstName");
var lastName = Platform.Request.GetFormField("lastName");
var newsletter = Platform.Request.GetFormField("newsletter");
// Determine status based on newsletter subscription
if (newsletter && newsletter == "True") {
var status = "Active";
var chkNewsletter="checked";
} else {
var status = "Unsubscribed";
}
// Create subscriber object for newsletter subscription
var subscriberNewsletter = {
"EmailAddress": email,
"SubscriberKey": subscriberKey,
"Lists": [{
"ID": 14552,
"Status": status,
"Action": "Upsert"
}]
};
// Perform Upsert operation for newsletter subscription
var subObjNewsletter = Subscriber.Init(subscriberKey);
var statusNewsletter = subObjNewsletter.Upsert(subscriberNewsletter);
// Retrieve promotions form field value
var promotions = Platform.Request.GetFormField("promotions");
// Determine status based on promotions subscription
if (promotions && promotions == "True") {
var status = "Active";
var chkPromotions="checked";
} else {
var status = "Unsubscribed";
}
// Create subscriber object for promotions subscription
var subscriberPromotions = {
"EmailAddress": email,
"SubscriberKey": subscriberKey,
"Lists": [{
"ID": 14553,
"Status": status,
"Action": "Upsert"
}]
};
// Perform Upsert operation for promotions subscription
var subObjPromotions = Subscriber.Init(subscriberKey);
var statusPromotions = subObjPromotions.Upsert(subscriberPromotions);
Variable.SetValue("@display", "");
}
// Set variables for status of newsletter and promotions
Variable.SetValue("@statusPromotions", statusPromotions);
Variable.SetValue("@statusNewsletter", statusNewsletter);
Variable.SetValue("@email", email);
Variable.SetValue("@subscriberKey", subscriberKey);
Variable.SetValue("@firstName", firstName);
Variable.SetValue("@lastName", lastName);
Variable.SetValue("@chkNewsletter", chkNewsletter);
Variable.SetValue("@chkPromotions", chkPromotions);
} catch (e) {
// Handle exceptions
Write("Exception: " + e.message + "<br>");
Write("Description: " + e.description + "<br>");
}
</script>
</head>
<body>
<div class="container">
<img src="https://www.salesforce.com/news/wp-content/uploads/sites/3/2021/05/Salesforce-logo.jpg"
alt="Your Logo" class="logo">
<h1>Subscription Centers</h1>
<div style="display:%%=v(@display)=%%">
<p class="success-message" id="successMessage">Your preferences have been updated successfully.</p>
</div>
<!-- Subscription Form -->
<form action="#" method="post">
<label for="firstName">First Name:</label>
<input type="text" id="firstName" name="firstName" value="%%=v(@firstName)=%%"><br>
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" name="lastName" value="%%=v(@lastName)=%%"><br>
<input type="hidden" id="subscriberKey" name="subscriberKey" value="%%=v(@subscriberKey)=%%">
<label for="email">Email:</label>
<input type="email" id="email" name="email" value="%%=v(@email)=%%"><br><br>
<!-- Preferences -->
<p>Preferences:</p>
<div class="preferences">
<label><input type="checkbox" name="newsletter" value="True" %%=v(@chkNewsletter)=%%> Newsletter</label><br>
<label><input type="checkbox" name="promotions" value="True" %%=v(@chkPromotions)=%%> Promotions</label><br><br>
</div>
<input type="hidden" name="submitted" value="True">
<button type="submit">Submit</button>
</form>
</div>
</body>
</html>
Allow subscribers to manage their preferences, like language and timezone
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Preference Center</title>
<style>
/* Professional CSS for styling */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f9f9f9;
color: #333;
line-height: 1.6;
}
.container {
max-width: 500px;
margin: 20px auto;
padding: 30px;
background-color: #fff;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
h1 {
text-align: center;
margin-bottom: 30px;
color: #007bff;
}
form {
margin-top: 20px;
}
label {
display: block;
margin-bottom: 10px;
font-weight: bold;
}
input[type="email"],
select {
width: 100%;
padding: 10px;
margin-bottom: 20px;
border: 1px solid #ccc;
border-radius: 5px;
box-sizing: border-box;
font-size: 16px;
}
.email-preferences label {
display: block;
margin-bottom: 10px;
font-weight: normal;
position: relative;
padding-left: 30px;
cursor: pointer;
line-height: 1.6;
}
.email-preferences input[type="checkbox"] {
position: absolute;
opacity: 0;
cursor: pointer;
}
.checkmark {
position: absolute;
top: 0;
left: 0;
height: 20px;
width: 20px;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 3px;
}
.email-preferences input[type="checkbox"]:checked + .checkmark:after {
content: '';
position: absolute;
display: block;
left: 5px;
top: 5px;
width: 8px;
height: 8px;
border: solid #007bff;
border-width: 0 2px 2px 0;
transform: rotate(45deg);
}
input[type="submit"] {
background-color: #007bff;
color: #fff;
border: none;
padding: 15px 20px;
border-radius: 5px;
cursor: pointer;
display: block;
width: 100%;
font-size: 16px;
transition: background-color 0.3s ease;
}
input[type="submit"]:hover {
background-color: #0056b3;
}
.success-message {
text-align: center;
color: #27ae60;
margin-top: 20px;
}
</style>
%%[
var @display,@chkNewsletter,@chkPromotions
SET @display="none"
]%%
<script runat="server">
// Load the required core library
Platform.Load("core", "1");
try {
// Retrieve the HTTP method (GET or POST)
var method = Platform.Request.Method;
// Handle GET request
if (method == "GET") {
// Retrieve attributes from context
var email = Attribute.GetValue("emailaddr");
var subscriberKey = Attribute.GetValue("_subscriberkey");
}
// Handle POST request
if (method == "POST") {
// Retrieve form field values from the POST request
var email = Platform.Request.GetFormField("email");
var subscriberKey = Platform.Request.GetFormField("subscriberKey");
var promotional = Platform.Request.GetFormField("promotional");
var updates = Platform.Request.GetFormField("updates");
var newsletter = Platform.Request.GetFormField("newsletter");
var language = Platform.Request.GetFormField("language");
var timezone = Platform.Request.GetFormField("timezone");
// Convert promotional, updates, and newsletter values to "True" or "False" strings
if (promotional)
promotional = "True";
else
promotional = "False";
if (updates)
updates = "True";
else
updates = "False";
if (newsletter)
newsletter = "True";
else
newsletter = "False";
// Initialize the Data Extension
var updateDE = DataExtension.Init('Customer_Preference');
// Update the rows in the Data Extension
var status = updateDE.Rows.Update({
"subscriberKey": subscriberKey,
"email": email,
"promotional": promotional,
"updates": updates,
"newsletter": newsletter,
"language": language,
"timezone": timezone
}, ["subscriberKey"], [subscriberKey]);
if(status==0){
// Insert the rows in the Data Extension
var status = updateDE.Rows.Add({
"subscriberKey": subscriberKey,
"email": email,
"promotional": promotional,
"updates": updates,
"newsletter": newsletter,
"language": language,
"timezone": timezone
});
}
Variable.SetValue("@display", "");
}
// Set variables for status of newsletter and promotions
Variable.SetValue("@email", email);
Variable.SetValue("@subscriberKey", subscriberKey);
} catch (e) {
// Handle exceptions
Write("Exception: " + e.message + "<br>");
Write("Description: " + e.description + "<br>");
}
</script>
</head>
<body>
<div class="container">
<h1>Preference Center</h1>
<div style="display:%%=v(@display)=%%">
<p class="success-message" id="successMessage">Your preferences have been updated successfully.</p>
</div>
<form action="%%=RequestParameter('PAGEURL')=%%" method="post">
<label for="email">Email Address:</label>
<input type="email" id="email" name="email" placeholder="Your email address" value="%%=v(@email)=%%" required>
<input type="hidden" id="subscriberKey" name="subscriberKey" value="%%=v(@subscriberKey)=%%">
<div class="email-preferences">
<label><input type="checkbox" name="promotional" checked> <span class="checkmark"></span> Receive Promotional Offers</label>
<label><input type="checkbox" name="updates" checked> <span class="checkmark"></span> Receive Product Updates</label>
<label><input type="checkbox" name="newsletter" checked> <span class="checkmark"></span> Subscribe to Newsletter</label>
</div>
<label for="language">Preferred Language:</label>
<select id="language" name="language">
<option value="en">English</option>
<option value="fr">French</option>
<option value="es">Spanish</option>
<!-- Add more options as needed -->
</select>
<label for="timezone">Preferred Timezone:</label>
<select id="timezone" name="timezone">
<option value="gmt-8">GMT-8 (Pacific Time)</option>
<option value="gmt-5">GMT-5 (Eastern Time)</option>
<option value="gmt+1">GMT+1 (Central European Time)</option>
<!-- Add more options as needed -->
</select>
<input type="submit" value="Update Preferences">
</form>
</div>
</body>
</html>
Allow subscribers to manage their preferences for all the objects
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Preference Center</title>
<style>
/* Add your CSS styles here */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
text-align: center;
/* Center align the content */
}
.form-container {
max-width: 400px;
margin: 20px auto;
background-color: #f9f9f9;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
text-align: left;
/* Align form contents to the left */
}
label {
display: block;
margin-bottom: 10px;
}
input[type="text"],
input[type="email"] {
width: 100%;
padding: 8px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type="checkbox"] {
margin-right: 5px;
}
button {
background-color: #007bff;
color: #fff;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
</style>
<script runat="server">
// Load necessary platform libraries
Platform.Load('core', '1');
// Get the HTTP request method
var method=Platform.Request.Method;
// Set a SSJS variable with the request method
Variable.SetValue("@method", method);
try{
</script>
%%[
/* Define variables */
VAR @display, @objectType
/* Initialize display variable */
SET @display = "none"
/* Check if the method is "POST" */
IF @method == "POST" THEN
/* Retrieve POST parameters */
SET @subscriberkey = RequestParameter("subscriberkey")
SET @email = RequestParameter("email")
SET @firstName = RequestParameter("firstName")
SET @lastName = RequestParameter("lastName")
SET @status = IIF(RequestParameter("status") == "Active", "Active", "Unsubscribed")
SET @objectType = RequestParameter("objectType")
/* Check if the object type is SFMC */
IF @objectType == "SFMC" THEN
/* Get the Business Unit (BU) MID (Member ID) */
SET @BU_MID = AuthenticatedMemberID()
/* Create a Subscriber object */
SET @subscriber = CreateObject("Subscriber")
SetObjectProperty(@subscriber, "SubscriberKey", @subscriberKey) /* Ensure subscriberKey is provided */
SetObjectProperty(@subscriber, "Status", @status) /* Ensure status is provided */
/* Create a ClientID object and associate it with the Subscriber */
SET @cid = CreateObject("ClientID")
SetObjectProperty(@cid, "ID", @BU_MID)
SetObjectProperty(@cid, "IDSpecified", "true")
SetObjectProperty(@subscriber, "Client", @cid)
/* Set up options for updating the Subscriber */
SET @options = CreateObject("UpdateOptions")
SET @save = CreateObject("SaveOption")
SetObjectProperty(@save, "SaveAction", "UpdateAdd")
SetObjectProperty(@save, "PropertyName", "*")
AddObjectArrayItem(@options, "SaveOptions", @save)
/* Update the Subscriber object with the new status */
/* The updated status, @update_sub_status, and any error code, @update_sub_errorcode, are captured */
SET @subscribersStatus = InvokeUpdate(@subscriber, @update_sub_status, @update_sub_errorcode, @options)
SET @display = ""
ELSE
/* If object type is not SFMC, update Salesforce object */
SET @status = IIF(RequestParameter("Status") == "Active", "True", "False")
SET @updateRecord = UpdateSingleSalesforceObject(
@objectType, @subscriberkey,
"FirstName", @firstName,
"LastName", @lastName,
"Email", @email,
"HasOptedOutOfEmail", @status
)
SET @display = ""
ENDIF
ENDIF
/* Check if the method is "GET" */
IF @method == "GET" THEN
/* Retrieve GET parameters */
SET @subscriberkey = AttributeValue("_subscriberkey")
SET @email = AttributeValue("emailaddr")
SET @firstName = AttributeValue("First Name")
SET @lastName = AttributeValue("Last Name")
SET @status = Lookup("ENT._Subscribers", "Status", "SubscriberKey", @subscriberkey)
SET @objectType = "SFMC"
IF Length(@subscriberkey) == 18 THEN
/* Fetching data from Sales Cloud to show in the form */
SET @subscriberRows = RetrieveSalesforceObjects(
"Lead",
"Id,FirstName,LastName,Email,HasOptedOutOfEmail",
"Id",
"=",
@subscriberkey
)
SET @objectType = "Lead"
IF RowCount(@subscriberRows) == 0 THEN
SET @subscriberRows = RetrieveSalesforceObjects(
"Contact",
"Id,FirstName,LastName,Email,HasOptedOutOfEmail",
"Id",
"=",
@subscriberkey
)
SET @objectType = "Contact"
ENDIF
IF RowCount(@subscriberRows) == 0 THEN
SET @subscriberRows = RetrieveSalesforceObjects(
"Account",
"Id,FirstName,LastName,Email,HasOptedOutOfEmail",
"Id",
"=",
@subscriberkey
)
SET @objectType = "Account"
ENDIF
IF RowCount(@subscriberRows) == 0 THEN
SET @subscriberRows = RetrieveSalesforceObjects(
"Opportunity",
"Id,FirstName,LastName,Email,HasOptedOutOfEmail",
"Id",
"=",
@subscriberkey
)
SET @objectType = "Opportunity"
ENDIF
/* Check if subscriber rows are retrieved */
IF RowCount(@subscriberRows) > 0 THEN
SET @row = Row(@subscriberRows, 1)
SET @firstName = Field(@row, "FirstName")
SET @lastName = Field(@row, "LastName")
SET @email = Field(@row, "Email")
SET @status = Field(@row, "HasOptedOutOfEmail")
/* Checking if the subscriber has opted out of emails */
SET @status = IIF(@status == "True", "Unsubscribed", "Active")
ENDIF
ENDIF
SET @chkStatus = IIF(@status == "Active", "checked", "")
ENDIF
]%%
<script runat="server">
}
catch(ex)
{
// Catch and handle any exceptions
Platform.Load('core', '1');
Write(Stringify(ex));
}
</script>
</head>
<body>
<h1>Preference Center</h1>
<div style="display:%%=v(@display)=%%">
<p class="success-message" id="successMessage">Your preferences have been updated successfully.</p>
</div>
<!-- Form for Account preferences -->
<div class="form-container" id="preferencesForm">
<h2>User Preferences</h2>
<form action="%%=RequestParameter('PAGEURL')=%%" method="post">
<input type="hidden" name="subscriberkey" value="%%=v(@subscriberkey)=%%">
<input type="hidden" name="objectType" value="%%=v(@objectType)=%%">
<label>
First Name:
<input type="text" name="firstName" value="%%=v(@firstName)=%%" required>
</label>
<label>
Last Name:
<input type="text" name="lastName" value="%%=v(@lastName)=%%" required>
</label>
<label>
Email:
<input type="email" name="email" value="%%=v(@email)=%%" required>
</label>
<label>
<input type="checkbox" name="status" value="%%=v(@status)=%%" %%=v(@chkStatus)=%%> Subscribe to Newsletter
</label>
<button type="submit">Update Preferences</button>
</form>
</div>
</body>
</html>
Once the user registers, trigger an email for successful registration
Note: Pre-requisite a.Trigger send definition b. Json Code Resource to trigger an email
Cloud Page : Update Line 171 with your code resource URL
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta tags -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Title -->
<title>Event Name | Landing Page</title>
<!-- CSS styles -->
<style>
/* Add your CSS styles here */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f2f2f2;
}
.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.header {
text-align: center;
margin-bottom: 30px;
}
.event-image {
width: 100%;
border-radius: 10px;
margin-bottom: 20px;
}
.cta-button {
display: inline-block;
padding: 10px 20px;
background-color: #007bff;
color: #fff;
text-decoration: none;
border-radius: 5px;
font-size: 16px;
transition: background-color 0.3s;
cursor: pointer;
}
.cta-button:hover {
background-color: #0056b3;
}
.registration-form {
display: none;
margin-top: 20px;
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
display: block;
font-weight: bold;
}
.form-group input[type="text"],
.form-group input[type="email"] {
width: 100%;
padding: 10px;
font-size: 16px;
border-radius: 5px;
border: 1px solid #ccc;
}
.form-group input[type="submit"] {
background-color: #007bff;
color: #fff;
border: none;
padding: 10px 20px;
font-size: 16px;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
}
.form-group input[type="submit"]:hover {
background-color: #0056b3;
}
.logo {
width: 150px;
margin: 20px auto;
}
.success-message {
color: #27ae60;
margin-top: 20px;
display: none;
}
</style>
%%[
/* Assign subscriberkey from the query parameter */
SET @subscriberKey = AttributeValue("_subscriberkey")
SET @email = AttributeValue("emailaddr")
SET @fullName = Concat(AttributeValue("First Name")," ",AttributeValue("Last Name"))
]%%
</head>
<body>
<!-- Page content -->
<div class="container">
<!-- Header -->
<div class="header">
<h1>Event Name</h1>
<p>Join us for an unforgettable experience!</p>
</div>
<!-- Logo -->
<img src="https://www.salesforce.com/news/wp-content/uploads/sites/3/2021/05/Salesforce-logo.jpg"
alt="Your Company Logo" class="logo">
<!-- Event details -->
<p><strong>Date:</strong> March 20, 2024</p>
<p><strong>Time:</strong> 10:00 AM - 5:00 PM</p>
<p><strong>Location:</strong> Venue Name, City</p>
<p><strong>About:</strong> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus in odio eu ante
sodales placerat.</p>
<!-- Register button -->
<button class="cta-button" id="registerButton">Register Now</button>
<!-- Registration form -->
<div class="registration-form" id="registrationForm">
<form>
<div class="form-group">
<label for="fullName">Full Name</label>
<input type="text" id="fullName" name="fullName" value ="%%=v(@fullName)=%%" required>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" name="email" value ="%%=v(@email)=%%" required>
</div>
<!-- Hidden fields -->
<input type="hidden" id="subscriberKey" name="subscriberKey" value="%%=v(@subscriberKey)=%%">
<input type="hidden" id="tsExKey" name="tsExKey" value="Event_Registration">
<div class="form-group">
<input type="submit" value="Submit">
</div>
</form>
</div>
<!-- Success message -->
<div>
<p class="success-message" id="successMessage">You have been successfully registered.</p>
</div>
</div>
<!-- JavaScript -->
<script>
// JavaScript to toggle the visibility of the registration form and the "Register Now" button
document.getElementById("registerButton").addEventListener("click", function () {
document.getElementById("registrationForm").style.display = "block";
document.getElementById("registerButton").style.display = "none";
});
// JavaScript to handle form submission
document.querySelector("form").addEventListener("submit", function (event) {
event.preventDefault(); // Prevent form submission
// Form submission logic
try {
var formData = new FormData(document.querySelector("form")); // Get form data
var xhr = new XMLHttpRequest(); // Create XMLHttpRequest object
// Open connection: update you JSON code resource published URL
xhr.open('POST', 'https://<<Your_JSON_CodeResourceURL>>', true);
xhr.onload = () => {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
console.log(xhr.response); // Log response data
document.getElementById('successMessage').style.display = 'block'; // Display success message
setTimeout(hideSuccessMessage, 10000); // Hide the success message after 10 seconds
}
}
};
xhr.onerror = function () {
console.log("** An error occurred during the submission"); // Log error message
document.getElementById('errorMessage').style.display = 'block'; // Display error message
};
xhr.send(formData); // Send form data
} catch (ex) {
alert(ex.message); // Alert user if an exception occurs
}
document.getElementById("registerButton").style.display = "inline-block"; // Display register button
document.getElementById("registrationForm").style.display = "none"; // Hide registration form
});
// Function to hide success message
function hideSuccessMessage() {
document.getElementById('successMessage').style.display = 'none'; // Hide success message
}
</script>
</body>
</html>
JSON Code Resource
<script runat="server">
// Load necessary libraries
Platform.Load("core", "1");
var prox = new Script.Util.WSProxy();
// Get form field values
var email = Platform.Request.GetFormField("email");
var subscriberKey = Platform.Request.GetFormField("subscriberKey");
var fullName = Platform.Request.GetFormField("fullName");
var tsExKey = Platform.Request.GetFormField("tsExKey");
try {
// Define Triggered Send Definition
var tsDef = {
TriggeredSendDefinition: {
CustomerKey: tsExKey
},
Subscribers: [
{
EmailAddress: email,
SubscriberKey: subscriberKey,
Attributes: [
{
Name: 'fullName',
Value: fullName
}
]
}
]
};
// Create Triggered Send
var response = prox.createItem('TriggeredSend', tsDef);
// Extract response data
var Status = response.Status;
var result = Stringify(response.Results);
var jsonResult = Platform.Function.ParseJSON(result);
var ErrorCode = jsonResult[0].ErrorCode;
var StatusMessage = jsonResult[0].StatusMessage;
// Set variables for response data
Variable.SetValue("@status", Status);
Variable.SetValue("@ErrorCode", ErrorCode);
Variable.SetValue("@StatusMessage", StatusMessage);
} catch(e) {
// Error handling
Variable.SetValue("@status", "error");
Variable.SetValue("@ErrorCode", "0000");
Variable.SetValue("@StatusMessage", e.message);
}
</script>
{
"status": "%%=v(@status)=%%",
"ErrorCode": "%%=v(@ErrorCode)=%%",
"StatusMessage": "%%=v(@StatusMessage)=%%"
}
Once the user request for an OTP, trigger a transactional Journey to sent the OTP
Note: Pre-requisite a.Transactional Messaging Journey setup b. Json Code Resource to call Transactional Messaging API
Cloud Page : Update ClientID, Secrect and tentant endpoint subdomain with your code resource URL
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OTP Request</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
}
.container {
max-width: 400px;
margin: 50px auto;
padding: 20px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
margin-bottom: 20px;
}
input[type="submit"] {
width: 100%;
padding: 10px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease;
}
input[type="submit"]:hover {
background-color: #0056b3;
}
.success-message {
color: #27ae60;
margin-top: 20px;
display: none;
}
</style>
%%[
/* Assign subscriberkey from the query parameter */
SET @subscriberKey = AttributeValue("_subscriberkey")
SET @email = AttributeValue("emailaddr")
]%%
</head>
<body>
<div class="container">
<h2>Request OTP</h2>
<form action="%%=RequestParameter('PAGEURL')=%%" method="post">
<input type="hidden" id="subscriberKey" name="subscriberKey" value="%%=v(@subscriberKey)=%%">
<input type="hidden" id="email" name="email" value ="%%=v(@email)=%%" >
<input type="submit" value="Request OTP">
</form>
<!-- Success message -->
<div>
<p class="success-message" id="successMessage">OTP has been sent!</p>
</div>
</div>
<!-- JavaScript -->
<script>
// JavaScript to handle form submission
document.querySelector("form").addEventListener("submit", function (event) {
event.preventDefault(); // Prevent form submission
// Form submission logic
try {
var formData = new FormData(document.querySelector("form")); // Get form data
var xhr = new XMLHttpRequest(); // Create XMLHttpRequest object
// Open connection: update you JSON code resource published URL
xhr.open('POST', '{{your_JSON_CodeResource_URl}}', true);
xhr.onload = () => {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
console.log(xhr.response); // Log response data
document.getElementById('successMessage').style.display = 'block'; // Display success message
setTimeout(hideSuccessMessage, 10000); // Hide the success message after 10 seconds
}
}
};
xhr.onerror = function () {
console.log("** An error occurred during the submission"); // Log error message
document.getElementById('errorMessage').style.display = 'block'; // Display error message
};
xhr.send(formData); // Send form data
} catch (ex) {
alert(ex.message); // Alert user if an exception occurs
}
document.getElementById("registerButton").style.display = "inline-block"; // Display register button
document.getElementById("registrationForm").style.display = "none"; // Hide registration form
});
// Function to hide success message
function hideSuccessMessage() {
document.getElementById('successMessage').style.display = 'none'; // Hide success message
}
</script>
</body>
</html>
JSON Code Resource
<script runat="server">
// Load the Marketing Cloud Core library
Platform.Load("core", "1");
// Function to obtain an access token using client credentials
function getAccessToken() {
var clientId = '{{et_clientId}}'; // Replace with your client ID
var clientSecret = '{{et_clientSecret}}'; // Replace with your client secret
var url = 'https://{{et_subdomain}}.auth.marketingcloudapis.com/v2/token';// Replace your tenant endpoint
var contentType = 'application/json';
// Create a payload for the access token request
var payload = {
"client_id": clientId,
"client_secret": clientSecret,
"grant_type": "client_credentials"
};
try {
// Send an HTTP POST request to obtain the access token
var accessTokenResult = HTTP.Post(url, contentType, Stringify(payload));
var response = accessTokenResult["Response"][0];
var accessToken = Platform.Function.ParseJSON(response).access_token;
// Return the access token for use in the main script
return accessToken;
} catch (e) {
// Handle any errors that may occur during the access token request
throw e;
}
}
try {
// Get form field values
var email = Platform.Request.GetFormField("email");
var subscriberKey = Platform.Request.GetFormField("subscriberKey");
// Get the access token by calling the 'getAccessToken' function
var accessToken = 'Bearer ' + getAccessToken();
// Define the URL for creating an interaction (journey)
// Replace your tenant endpoint = {{et_subdomain}}
var setupURL = 'https://{{et_subdomain}}.rest.marketingcloudapis.com/messaging/v1/email/messages/' + Platform.Function.GUID();
// Define the headers for the HTTP request
var headerNames = ["Authorization"];
var headerValues = [accessToken];
var contentType = "application/json";
var random = "123456";
var payload = {
"definitionKey": "Customer_OTP_Demo",
"recipient": {
"contactKey": subscriberKey,
"to": email,
"attributes": {
"OTP": random
}
}
};
// Send an HTTP POST request to create the interaction (journey)
var httpResponse = HTTP.Post(setupURL, contentType, Stringify(payload), headerNames, headerValues);
var statusCode = httpResponse["StatusCode"];
var response = Platform.Function.ParseJSON(httpResponse["Response"][0]);
// Set variables for response data
Variable.SetValue("@status", statusCode);
Variable.SetValue("@ErrorCode", response.errorcode);
Variable.SetValue("@StatusMessage", response.requestId);
} catch (e) {
// Handle any errors that may occur during the main script execution
Variable.SetValue("@status", "error");
Variable.SetValue("@ErrorCode", "0000");
Variable.SetValue("@StatusMessage", Stringify(e));
}
</script>
{
"status": "%%=v(@status)=%%",
"ErrorCode": "%%=v(@ErrorCode)=%%",
"RequestID": "%%=v(@StatusMessage)=%%"
}
AMPScript Block : Update your stack-key
Cloud Page : Update code resource URL
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Distributed Marketing Data Extension
</title>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/lightning-design-system/2.14.4/styles/salesforce-lightning-design-system.min.css">
<style>
body {
font-family: 'Arial', sans-serif;
background-color: #f4f6f9;
}
.container {
max-width: 500px;
margin: 50px auto;
padding: 20px;
border-radius: 10px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
background-color: #ffffff;
position: relative;
/* Required for logo positioning */
}
.title {
text-align: center;
font-size: 24px;
margin-bottom: 20px;
color: #333333;
}
.form-group {
margin-bottom: 20px;
}
label {
font-weight: bold;
display: block;
margin-bottom: 5px;
color: #666666;
}
input[type="text"],
select {
width: calc(100% - 12px);
padding: 10px;
border: 1px solid #cccccc;
border-radius: 5px;
box-sizing: border-box;
font-size: 16px;
}
select {
cursor: pointer;
}
input[type="submit"] {
background-color: #0070d2;
color: #ffffff;
padding: 12px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s;
width: 100%;
display: block;
}
input[type="submit"]:hover {
background-color: #005fb2;
}
.logo {
position: absolute;
top: 10px;
left: 10px;
width: 150px;
height: auto;
}
.success-message {
background-color: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
border-radius: 5px;
padding: 10px;
margin-top: 20px;
display: none;
}
</style>
<script runat="server">
Platform.Load('core', '1');
var method=Platform.Request.Method;
Variable.SetValue("@method", method);
</script>
%%[
/* Check if the method is "GET" */
IF @method == "GET" THEN
/* Define variables */
SET @origin = HTTPRequestHeader("Referer") /* Extract the referer from the HTTP header */
SET @pattern = "https://mc\.{Stackkey}\.exacttarget\.com/cloud/" Define the regex pattern to match the allowed referer */
SET @match = RegExMatch(@origin, @pattern, 0, "IgnoreCase") /* Attempt to match the referer with the defined pattern */
/* Check if a match is found */
IF Length(@match) > 0 THEN
/* If a match is found, do nothing */
ELSE
/* If no match is found, redirect to a default URL */
Redirect("https://mc.{Stackkey}.exacttarget.com/")
ENDIF
ENDIF
]%%
</head>
<body>
<div class="container">
<img class="logo" src="https://www.salesforce.com/news/wp-content/uploads/sites/3/2021/05/Salesforce-logo.jpg"
alt="Salesforce Logo">
<h2 class="title">Create Distributed Marketing Data Extension
</h2>
<form id="data-extension-form" action="%%=RequestParameter('PAGEURL')=%%" method="post">
<div class="form-group">
<label for="dataExtensionName">Data Extension Name</label>
<input type="text" id="dataExtensionName" name="dataExtensionName" required>
</div>
<div class="form-group">
<label for="folderName">Folder Name</label>
<input type="text" id="folderName" name="folderName" required>
</div>
<div class="form-group">
<input type="submit" value="Create Data Extension">
</div>
</form>
<div class="success-message" id="success-message">
Data Extension created successfully!
</div>
</div>
<script>
document.getElementById('data-extension-form').addEventListener('submit',consentSubmit);
function consentSubmit(e){
try{
e.preventDefault();
var formData=new FormData(document.getElementById('data-extension-form'));
var xhr = new XMLHttpRequest();
xhr.open('POST', '{{Your Code Resource URl}}', true);
xhr.onload = () => {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
// Check against the numeric status code
console.log(xhr.response);
console.log(xhr.responseText);
// Reset the form fields after successful submission
document.getElementById('data-extension-form').reset();
document.getElementById('success-message').style.display = 'block';
// Hide the success message after 3 seconds (3000 milliseconds)
setTimeout(hideSuccessMessage, 3000);
}
}
};
xhr.onerror = function(){
console.log("** An error occurred during the submission");
}
xhr.send(formData);
}
catch(ex)
{
alert(ex.message);
}
}
function hideSuccessMessage() {
document.getElementById('success-message').style.display = 'none';
}
</script>
</body>
</html>
JSON Code Resource
<script runat="server">
// Load necessary libraries
Platform.Load("core", "1");
try {
// Instantiate WSProxy object
var api = new Script.Util.WSProxy();
// Get folder and data extension names
var folderName = Platform.Request.GetFormField("folderName");
var dataExtensionName = Platform.Request.GetFormField("dataExtensionName");
// Retrieve folder ID or create a new one if not found
var folderId = RetrieveFolderID(folderName);
var result;
if (!folderId) {
result = createDataExtensionFolder(api, folderName);
folderId = RetrieveFolderID(folderName);
result = createDataExtension(api, dataExtensionName, folderId);
} else {
result = createDataExtension(api, dataExtensionName, folderId);
}
Variable.SetValue("@status",result.Status);
Variable.SetValue("@ErrorCode","000");
Variable.SetValue("@StatusMessage","Success");
} catch (ex) {
// Catch and log any errors that occur
var APIExceptionDE = DataExtension.Init("APIException");
APIExceptionDE.Rows.Add({
Message: ex.message,
Description: ex.description,
InnerException: ex.jintException,
FunctionName: "DataExtensionRowsRetrieve"
});
Variable.SetValue("@status","Error");
Variable.SetValue("@ErrorCode","000");
Variable.SetValue("@StatusMessage",ex.message);
}
// Function to retrieve folder ID by name
function RetrieveFolderID(folderName) {
var filter = {
Property: "Name",
SimpleOperator: "equals",
Value: folderName
};
var results = Folder.Retrieve(filter);
return results[0].ID; // Return the ID of the first folder found
}
// Function to create a Data Extension
function createDataExtension(api, dataExtensionName, folderId) {
// Set the client ID
api.setClientId({ "ID": Platform.Function.AuthenticatedMemberID() });
// Define Data Extension configuration
var config = {
"CustomerKey": dataExtensionName,
"Name": dataExtensionName,
"CategoryID": folderId,
"Fields": [
// Define Data Extension fields
{ "Name": "greeting", "FieldType": "Text", "MaxLength": 255 },
{ "Name": "id", "FieldType": "Text", "MaxLength": 254, "IsRequired": true },
{ "Name": "email", "FieldType": "EmailAddress", "IsRequired": true },
{ "Name": "sfCampaignId", "FieldType": "Text", "MaxLength": 255 },
{ "Name": "sfCampaignMemberId", "FieldType": "Text", "MaxLength": 255 },
{ "Name": "sfQuickSendId", "FieldType": "Text", "MaxLength": 255 },
{ "Name": "sendFromName", "FieldType": "Text", "MaxLength": 255 },
{ "Name": "sendFromEmail", "FieldType": "Text", "MaxLength": 255 },
{ "Name": "firstName", "FieldType": "Text", "MaxLength": 50 },
{ "Name": "lastName", "FieldType": "Text", "MaxLength": 50 },
{ "Name": "sfUserId", "FieldType": "Text", "MaxLength": 255, "IsRequired": true },
{ "Name": "mobilePhone", "FieldType": "Phone" },
{ "Name": "journeyID", "FieldType": "Text", "MaxLength": 50, "IsRequired": true },
{ "Name": "sfOrgId", "FieldType": "Text", "MaxLength": 50, "IsRequired": true },
{ "Name": "smsValue", "FieldType": "Text", "MaxLength": 160 },
{ "Name": "EntryObjectId", "FieldType": "Text", "MaxLength": 255 }
],
// Data retention settings
"DataRetentionPeriodLength": 105,
"RowBasedRetention": false,
"ResetRetentionPeriodOnImport": true,
"DeleteAtEndOfRetentionPeriod": false,
"DataRetentionPeriod": "Weeks",
"SendableDataExtensionField": {
"Name": "id",
"FieldType": "Text"
},
"SendableSubscriberField": {
"Name": "Subscriber Key"
},
"IsSendable": true,
"IsTestable": true
};
// Create the Data Extension and return the result
var result = api.createItem("DataExtension", config);
return result;
};
// Function to retrieve Data Extension by external key
function RetrieveDataExtension(externalKey) {
var api = new Script.Util.WSProxy();
var req = api.retrieve("DataExtension", ["ObjectID"], {
Property: "DataExtension.CustomerKey",
SimpleOperator: "equals",
Value: externalKey
});
return req.Results[0].ObjectID;
}
// Function to create a Data Extension folder
function createDataExtensionFolder(api, folderName) {
// Retrieve parent folder ID
var req = api.retrieve("DataFolder", ["ID"], {
Property: "Name",
SimpleOperator: "equals",
Value: "Data Extensions"
});
var parentFolderId = req.Results[0].ID;
// Define folder configuration
var config = {
"Name": folderName,
"Description": "API Created Folder",
"ParentFolder": {
ID: parentFolderId,
IDSpecified: true
},
"IsActive": true,
"IsEditable": true,
"AllowChildren": true,
"ContentType": "dataextension"
};
// Create the folder and return the result
var result = api.createItem("DataFolder", config);
return result;
}
</script>
{
"status": "%%=v(@status)=%%",
"ErrorCode": "%%=v(@ErrorCode)=%%",
"StatusMessage": "%%=v(@StatusMessage)=%%"
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lead Capture Form</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f9f9f9;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.container {
max-width: 400px;
background-color: #fff;
padding: 30px;
border-radius: 8px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
color: #333;
}
form {
margin-top: 20px;
}
label {
display: block;
margin-bottom: 5px;
color: #666;
}
input[type="text"],
input[type="email"] {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
margin-bottom: 10px;
}
button {
width: 100%;
padding: 10px;
background-color: #3498db;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #2980b9;
}
.logo {
display: block;
margin: 0 auto 20px;
max-width: 200px;
}
.success-message {
color: #27ae60;
margin-top: 20px;
display: none;
}
</style>
</head>
<body>
<div class="container">
<img src="https://www.salesforce.com/news/wp-content/uploads/sites/3/2021/05/Salesforce-logo.jpg" alt="Your Logo" class="logo">
<h2>Sign Up for Updates</h2>
<form id="leadCaptureForm">
<label for="firstName">First Name</label>
<input type="text" id="firstName" name="firstName" placeholder="Enter your first name" required>
<label for="lastName">Last Name</label>
<input type="text" id="lastName" name="lastName" placeholder="Enter your last name" required>
<label for="email">Email Address</label>
<input type="email" id="email" name="email" placeholder="Enter your email address" required>
<label for="consent">
<input type="checkbox" id="consent" name="consent" value="True" required>
I agree to receive marketing communications.
</label>
<button type="submit">Sign Up</button>
<p class="success-message" id="successMessage">Thank you for signing up!</p>
</form>
</div>
<script>
document.getElementById("leadCaptureForm").addEventListener("submit", function(event) {
event.preventDefault();
var formData = new FormData(this);
var jsonData = {};
formData.forEach(function(value, key) {
jsonData[key] = value;
});
var xhr = new XMLHttpRequest();
xhr.open("POST", "{{your_JSON_CodeResource_URl}}", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.response);
document.getElementById("successMessage").style.display = "block";
setTimeout(function() {
document.getElementById("successMessage").style.display = "none";
}, 10000);
} else {
console.error("An error occurred during the submission");
}
};
xhr.onerror = function() {
console.error("An error occurred during the submission");
};
xhr.send(JSON.stringify(jsonData));
});
</script>
</body>
</html>
JSON Code Resource
<script runat="server">
// Load the Marketing Cloud Core library
Platform.Load("core", "1");
// Define your authentication credentials and URLs
var clientId = '{{et_clientId}}'; // Replace with your client ID
var clientSecret = '{{et_clientSecret}}'; // Replace with your client secret
var authUrl = 'https://{{et_subdomain}}.auth.marketingcloudapis.com/v2/token'; // Replace your tenant endpoint
var fireEntryEventAPI = 'https://{{et_subdomain}}.rest.marketingcloudapis.com/interaction/v1/events';
var eventDefinitionKey = '{{eventDefinitionKey}}';
// Initialize access token variable
var accessToken;
// Function to obtain an access token using client credentials
function getAccessToken(clientId,clientSecret,authUrl) {
// Create a payload for the access token request
var payload = {
"client_id": clientId,
"client_secret": clientSecret,
"grant_type": "client_credentials"
};
try {
var accessTokenResult = HTTP.Post(authUrl, contentType, Stringify(payload));
var response = accessTokenResult["Response"][0];
accessToken = Platform.Function.ParseJSON(response).token_type + ' ' + Platform.Function.ParseJSON(response).access_token;
} catch (e) {
throw new Error('Failed to obtain access token: ' + Stringify(e));
}
return accessToken;
}
try {
// Get form field values from the post data
var postData = Platform.Request.GetPostData();
var formData = Platform.Function.ParseJSON(postData);
var subscriberKey = Platform.Function.GUID();
var email = formData.email;
var firstName = formData.firstName;
var lastName = formData.lastName;
var consent = formData.consent;
var payload = {
"ContactKey": subscriberKey,
"EventDefinitionKey": eventDefinitionKey,
"Data": {
"subscriberKey":subscriberKey,
"email":email,
"firstName":firstName,
"lastName":lastName,
"consent":consent
}
};
// Get the access token by calling the 'getAccessToken' function
var accessToken = getAccessToken(clientId,clientSecret,authUrl);
// Define the headers for the HTTP request
var headerNames = ["Authorization"];
var headerValues = [accessToken];
var contentType = "application/json";
// Send an HTTP POST request to create the interaction (journey)
var httpResponse = HTTP.Post(fireEntryEventAPI, contentType, Stringify(payload), headerNames, headerValues);
var statusCode = httpResponse["StatusCode"];
var response = Platform.Function.ParseJSON(httpResponse["Response"][0]);
// Set variables for response data
Variable.SetValue("@status", statusCode);
Variable.SetValue("@ErrorCode", response.errorcode);
Variable.SetValue("@StatusMessage", response.requestId);
} catch (e) {
// Handle any errors that may occur during the main script execution
Variable.SetValue("@status", "error");
Variable.SetValue("@ErrorCode", "0000");
Variable.SetValue("@StatusMessage", Stringify(e));
}
</script>
{
"status": "%%=v(@status)=%%",
"ErrorCode": "%%=v(@ErrorCode)=%%",
"RequestID": "%%=v(@StatusMessage)=%%"
}
Comments
Post a Comment