Unlock the Power of AMPscript: A Treasure Trove of Code Snippets and Examples
Write an AMPScript code block to perform TriggeredSend
<script runat="server">
Platform.Load('core', '1');
var method = Platform.Request.Method;
Variable.SetValue("@method", method);
</script>
%%[
/*
AMPscript to trigger a transactional email send using a specified
Triggered Send Definition with personalization attributes and log the subscriber.
*/
/* Variable Declarations */
var @emailAddress, @fullName, @subscriberKey, @CompanyName, @Industry, @CompanySize, @triggeredSend, @triggeredSendDefinition, @subscriber, @statusCode, @statusMessage, @errorCode, @logDataExtensionName, @logStatus, @redirectURL
/*
Assign values for personalization and email address from request parameters.
*/
SET @emailAddress = RequestParameter("email")
SET @fullName = RequestParameter("name")
SET @CompanyName = RequestParameter("company")
SET @Industry = RequestParameter("industry")
SET @CompanySize = RequestParameter("size")
SET @subscriberKey = GUID() /* Generate a unique SubscriberKey */
/* Check if the request method is "POST" */
IF @method == "POST" THEN
/*
Create Triggered Send Objects:
- @triggeredSend: TriggeredSend object to handle the triggered email send.
- @triggeredSendDefinition: TriggeredSendDefinition object to specify the email definition.
*/
SET @triggeredSend = CreateObject("TriggeredSend")
SET @triggeredSendDefinition = CreateObject("TriggeredSendDefinition")
/*
Specify the CustomerKey for the Triggered Send Definition.
This should match the CustomerKey in the Marketing Cloud setup.
*/
SET @tsCustomerKey = "SMB_Sign_Up_Confirmation"
SetObjectProperty(@triggeredSendDefinition, "CustomerKey", @tsCustomerKey)
/*
Associate the TriggeredSendDefinition object with the TriggeredSend object.
*/
SetObjectProperty(@triggeredSend, "TriggeredSendDefinition", @triggeredSendDefinition)
/*
Create and configure the Subscriber object with the email address and personalization attributes.
*/
SET @subscriber = CreateObject("Subscriber")
SetObjectProperty(@subscriber, "EmailAddress", @emailAddress)
SetObjectProperty(@subscriber, "SubscriberKey", @subscriberKey)
/*
Add custom attributes to the Subscriber object.
For example, adding FullName and other attributes.
*/
/* FullName Attribute */
SET @attr = CreateObject("Attribute")
SetObjectProperty(@attr, "Name", "FullName")
SetObjectProperty(@attr, "Value", @fullName)
AddObjectArrayItem(@subscriber, "Attributes", @attr)
/*
Add the configured Subscriber object to the TriggeredSend's subscriber list.
*/
AddObjectArrayItem(@triggeredSend, "Subscribers", @subscriber)
/*
Invoke the TriggeredSend to send the email, and capture the status and any errors.
*/
SET @statusCode = InvokeCreate(@triggeredSend, @statusMessage, @errorCode)
/*
Log the subscriber details and the status of the send operation.
*/
SET @logDataExtensionName = "SMB_Subscribers" /* Replace with your logging data extension name */
SET @logStatus = InsertData(@logDataExtensionName, "EmailAddress", @emailAddress, "SubscriberKey", @subscriberKey, "FullName", @fullName, "CompanyName", @CompanyName, "Industry", @Industry, "CompanySize", @CompanySize)
/*
Error Handling:
- If the TriggeredSend did not return a status code of "OK", raise an error.
- This helps in identifying and troubleshooting issues during the send process.
*/
IF @statusCode == "OK" THEN
/* Set the redirect URL if the send is successful */
Redirect("confirmation_cloudpage_url")
ELSE
Redirect("errorpage_cloudpage_url")
ENDIF
ENDIF
/*
End of AMPscript.
*/
]%%
Write AMPscript block to retrieve Salesforce Object and Update Salesforce Object
%%[
SET @subscriberRows = RetrieveSalesforceObjects(
"Account",
"Id,FirstName,LastName,SA_Email_2__c",
"PersonContactId", "=", @subscriberkey)
SET @createConsent = CreateSalesforceObject(
"Multichannel_Consent_vod__c", 7,
"Account_vod__c", @account_id,
"Consent_Type_vod__c", @consent_type,
"Channel_Value_vod__c", @email,
"Opt_Type_vod__c", @opt_type,
"RecordTypeId", @record_type,
"Capture_Datetime_vod__c", @getDate,
"Signature_Datetime_vod__c", @getDate)
]%%
Write AMPscript code block to Unsubscribe a subscriber
%%[
/* Assign values for SubscriberKey and EmailAddress */
SET @subscriberKey = AttributeValue("_subscriberkey")
SET @emailAddress = AttributeValue("emailaddr")
/* Create a new Subscriber object */
SET @subscriberObject = CreateObject("Subscriber")
SetObjectProperty(@subscriberObject, "EmailAddress", @emailAddress)
SetObjectProperty(@subscriberObject, "SubscriberKey", @subscriberKey)
/* Set the status of the subscriber to Unsubscribed */
SetObjectProperty(@subscriberObject, "Status", "Unsubscribed")
/* Create a new ClientID object (if needed) */
SET @clientIdObject = CreateObject("ClientID")
SetObjectProperty(@clientIdObject, "ID", "1123XXXXXXX") /* Replace with your Client ID */
SetObjectProperty(@clientIdObject, "IDSpecified", "true")
/* Associate the ClientID object with the Subscriber */
SetObjectProperty(@subscriberObject, "Client", @clientIdObject)
/* Define Update Options */
SET @updateOptions = CreateObject("UpdateOptions")
SET @saveOption = CreateObject("SaveOption")
SetObjectProperty(@saveOption, "SaveAction", "UpdateAdd")
SetObjectProperty(@saveOption, "PropertyName", "*")
AddObjectArrayItem(@updateOptions, "SaveOptions", @saveOption)
/* Update the Subscriber object */
SET @updateStatus = InvokeUpdate(@subscriberObject, @updateStatusMessage, @updateErrorCode, @updateOptions)
/* Log the subscriber details and status of the update operation */
SET @logDataExtensionName = "InvokeUpdate" /* Replace with your logging data extension name */
SET @logStatus = InsertData(
@logDataExtensionName,
"updateStatus", @updateStatus,
"updateStatusMessage", @updateStatusMessage,
"updateErrorCode", @updateErrorCode,
"subscriberKey", @subscriberKey,
"emailAddress", @emailAddress
)
]%%
Write AMPscript code block to design dynamic sender profile
%%[
VAR @Cloud, @FromName, @FromEmail
SET @Cloud = AttributeValue('Sender')
IF @Cloud == 'Sales' THEN
SET @FromName = 'Sales Cloud'
SET @FromEmail = 'salescloud@salesforce.com'
ELSEIF @Cloud == 'Service' THEN
SET @FromName = 'ServiceCloud'
SET @FromEmail = 'servicecloud@salesforce.com'
ELSEIF @Cloud == 'Marketing' THEN
SET @FromName = 'Marketing Cloud'
SET @FromEmail = 'marketingcloud@salesforce.com'
ELSEIF @Cloud == 'Trailhead' THEN
SET @FromName = 'Trailhead'
SET @FromEmail = 'trailhead@salesforce.com'
ELSEIF @Cloud == 'Experience' THEN
SET @FromName = 'Experience Cloud'
SET @FromEmail = 'experiencecloud@salesforce.com'
ELSE
SET @FromName = 'Salesforce'
SET @FromEmail = 'salesforce@salesforce.com'
ENDIF
]%%
%%=v(@FromName)=%%
Write AMPscript code block to trigger Journey API Event
%%[
/* Variable Declarations */
SET @clientId = "YOUR_CLIENT_ID"
SET @clientSecret = "YOUR_CLIENT_SECRET"
SET @authEndpoint = "https://YOUR_SUBDOMAIN.auth.marketingcloudapis.com/v2/token"
SET @journeyEndpoint = "https://YOUR_SUBDOMAIN.rest.marketingcloudapis.com/interaction/v1/events"
/* Subscriber Information */
SET @SubscriberKey = "YOUR_SUBSCRIBER_KEY"
SET @FullName = "FULL NAME"
SET @EmailAddress = "SUBSCRIBER_EMAIL"
SET @Subject = "SUBJECT"
SET @Message="Hello, How are you"
/* Journey Information */
SET @Journey_API_Key = "YOUR_JOURNEY_API_KEY"
SET @EstablishContactKey = "True"
/* Define the payload for authentication */
SET @payload = Concat(
'{
"client_id": "', @clientId, '",
"client_secret": "', @clientSecret, '",
"grant_type": "client_credentials"
}'
)
/* Make API call to get an access token */
HTTPPost2(@authEndpoint, "application/json", @payload, true, @response, @callstatus)
/* Parse the response to extract the access token */
SET @rowset = BuildRowsetFromJson(@response, '$.*', 1)
SET @row = Row(@rowset, 1)
SET @accessToken = FIELD(@row, 'Value')
SET @row = Row(@rowset, 2)
SET @tokentype = FIELD(@row, 'Value')
SET @authorization = Concat(@tokentype, ' ', @accessToken)
/* Construct the JSON Payload for the Journey API */
SET @content = CONCAT(
'{
"ContactKey": "', @SubscriberKey, '",
"EventDefinitionKey": "', @Journey_API_Key, '",
"EstablishContactKey": "', @EstablishContactKey, '",
"Data": {
"SubscriberKey": "', @SubscriberKey, '",
"EmailAddress": "', @EmailAddress, '",
"FullName": "', @FullName, '",
"Message": "', @Message, '",
"Subject": "', @Subject, '"
}
}'
)
/* Make API Call to Trigger the Journey */
SET @returnValid = HTTPPost2(@journeyEndpoint, "application/json; charset=UTF-8", @content, False, @output, @respheader, "Authorization", @authorization)
]%%
Write AMPscript code block to retrieve Access Token via AUTH API
%%[
/* Variable Declarations */
SET @clientId = "YOUR_CLIENT_ID"
SET @clientSecret = "YOUR_CLIENT_SECRET"
SET @authEndpoint = "https://YOUR_SUBDOMAIN.auth.marketingcloudapis.com/v2/token"
/* define the payload*/
SET @payload = Concat(
'{
"client_id": "',@clientId,'",
"client_secret": "',@clientSecret,'",
"grant_type": "client_credentials"
}'
)
HTTPPost2(@authEndpoint, "application/json", @payload, true, @response,@callstatus)
SET @rowset=BuildRowsetFromJson(@response, '$.*',1)
SET @row=Row(@rowset,1)
SET @accessToken=FIELD(@row,'Value')
SET @row=Row(@rowset,2)
SET @tokentype=FIELD(@row,'Value')
SET @authorization=Concat(@tokentype,' ',@accessToken)
]%%
%%=v(@authorization)=%%
Write AMPscript code block to render dynamic conent
//Example1
%%[
SET @lang_detail = LookupRows('translation','Language',@Lang)
SET @rowCount = RowCount(@lang_detail)
IF @rowCount > 0 THEN
SET @row = row(@lang_detail,1)
SET @flbl = field(@row,"First_Name")
SET @llbl = field(@row,"Last_Name")
SET @emaillbl = field(@row,"Email_Address")
ENDIF
]%%
//Example2
%%[/*select new product based on interest*/
VAR @firstname, @rs, @row, @prodname, @productdesc, @productprice, @productimage
SET @firstname = ProperCase([First_Name])
IF EMPTY (@firstname) THEN SET @firstname = "Shashi's Rockstar" ENDIF
SET @rs = LookupRows('Shashi New Products', 'season', 'Winter')
]%%
Greetings, %%=v(@firstname)=%%!
As a loyalty member who likes %%interest%%, we want to give you a sneak peek into a new product you might be interested in.
%%[
IF RowCount(@rs) > 0 THEN
FOR @i = 1 TO RowCount(@rs) DO
SET @row = Row(@rs, @i)
SET @productInterest = Field(@row, 'interest')
IF [Interest] == @productInterest THEN
SET @prodname = Field(@row,'name')
SET @productdesc = Field(@row,'description')
SET @productprice = Field(@row,'price')
SET @productimage = Field(@row,'imageUrl')
ENDIF
NEXT @i
ENDIF
IF EMPTY(@prodName) THEN
/* Set Default Content*/
SET @prodname = 'Best Ampscript books'
SET @productdesc = 'These are our top seller for 5 years running!'
SET @productprice = '$10.00'
SET @productimage = 'https://images.shashi.product.com/23048134901238402938opisd'
ENDIF
]%%
%%=v(@prodname)=%%
%%=v(@productprice)=%%
%%=@productdesc=%%
Shop Now!
Write AMPscript code block to parse XML via BuildRowSETFromXML
%%[
SET @rows = LookupRows("DataExtensionName","ProcessedFlag", 'False')
SET @rowCountnew = rowcount(@rows)
IF @rowCountnew > 0 THEN
FOR @y = 1 to @rowCountnew DO
SET @row = row(@rows, @y)
SET @SearchField = field(@row,"Field1")
SET @xmlDetails = Lookup("DataExtensionName",
"Field2",
"SearchField",
@SearchField)
IF indexOf(@xmlDetails,"") > 0 THEN
SET @nodes = BuildRowSETFromXML(@xmlDetails,
"/node1/node1Childs",
0)
SET @rowCount = rowcount(@nodes)
SET @data = @rowCount
FOR @i = 1 to @rowCount DO
VAR @id
VAR @Email
SET @nodepath = concat("//node1/node1Childs[",@i,"]/")
IF rowcount(BuildRowSETFromXML(@xmlDetails,
concat(@nodepath,
"id"))) > 0 THEN
SET @id = Field(Row(BuildRowSETFromXML(@xmlDetails,
concat(@nodepath,"id")
,0),1),'Value')
ENDIF
IF rowcount(BuildRowSETFromXML(@xmlDetails,
concat(@nodepath,
"email"))) > 0 THEN
SET @email = Field(Row(BuildRowSETFromXML(@xmlDetails,
concat(@nodepath,
"email"),0),1),'Value')
ENDIF
SET @upsertCount = upsertData("UpdateDataExtension",1,
"ID", @id,"Email")
NEXT @i
ENDIF
NEXT @y
ENDIF
]%%
Write an AMPScript block to add custom attributes to Send Log data extension
%%[
SET @utm_campaign = __AdditionalEmailAttribute1
SET @utm_source = __AdditionalEmailAttribute2
SET @SubscriberKey = _subscriberkey
SET @EventDate = GetSendTime()
SET @ViewLink = view_email_url
SET @EmailId = _emailid
SET @EmailName = emailname_
SET @Email = emailaddr
]%%
Write an AMPScript block that creates a rowset from a character string by splitting the string at the specified delimiter.
//Example 1
%%[
VAR @FULLNAME,@ROWS,@ROWCOUNT,@i,@ROW,@NAME
SET @FULLNAME = "salesFORce marketing cloud"
SET @ROWS = BuildRowSETFromString(@FULLNAME," ")
SET @ROWCOUNT = rowCount(@ROWS)
IF @rowCount > 1 THEN
FOR @i = 1 TO @ROWCOUNT DO
VAR @NAME
SET @ROW = row(@ROWS, @i) /* get row based on counter */
SET @x = field(@ROW,1)
OutputLine(concat('Name',@i,' is:',@x, '
'))
NEXT @i
ENDIF
]%%
//Example 2
%%[
VAR @fullname, @rows, @getrowcount, @i, @row, @name
SET @fullname = 'Sumit Kumar is trying TO learn ampscript'
SET @rows = BuildRowSETFromString(@fullname," ")
SET @getrowcount = rowcount(@rows)
IF @getrowcount > 0 THEN
FOR @i = 1 TO @getrowCount DO
SET @row = row(@rows, @i)
SET @name = field(@row,1)
]%%
Name %%=v(@i)=%%: %%=v(@name)=%%
%%[
NEXT @i ]%%
%%[ ELSE ]%%
No rows found
%%[ ENDIF ]%%
Write an AMPScript block with "Text Capitalization Rules"
%%[
/*Assign Name*/
SET @fullName="mcdonald"
/*"Mac donald" ,"Smith-jones" "DeFazio" "McDonald" "MCDONALD" "mcdonald" "Macdonald"*/
IF not empty(@fullName) THEN
/*Rule 1 First letter after an apostrophe*/
SET @validateRule1=IndexOf(@fullName,"'")
IF @validateRule1>0 THEN
SET @fullName=ProperCase(@fullName)
SET @fullName=Replace(
@fullName,
Substring(
@fullName,
Add(@validateRule1,1),1),
Uppercase(
Substring(
@fullName,Add(@validateRule1,1),1)))
SET @fullName=Replace(
@fullName,
Substring(
@fullName,
Subtract(
Length(@fullName),1),2),
Lowercase(
Substring(
@fullName,
Subtract(Length(@fullName),1),2)))
ENDIF
/*Rule 2 First letter after a space*/
SET @validateRule1=IndexOf(@fullName," ")
IF @validateRule1>0 THEN
SET @fullName=ProperCase(@fullName)
ENDIF
/*Rule 3 First letter after a hyphen*/
SET @validateRule1=IndexOf(@fullName,"-")
IF @validateRule1>0 THEN
SET @fullName=ProperCase(@fullName)
SET @fullName=Replace(
@fullName,
Substring(
@fullName,
Add(@validateRule1,1),1),
Uppercase(
Substring(@fullName,Add(@validateRule1,1),1)))
ENDIF
/*Rule 4 First letter after “Mc” if the entire name is lowercase or uppercase*/
SET @validateRule1=IndexOf(@fullName,"Mc")
IF @validateRule1>0 THEN
SET @fullName=ProperCase(@fullName)
SET @fullName=Replace(
@fullName,
Substring(
@fullName,
Add(@validateRule1,2),1),
Uppercase(
Substring(@fullName,Add(@validateRule1,2),1)))
SET @fullName=Replace(
@fullName,
Substring(
@fullName,
Subtract(Length(@fullName),1),2),
Lowercase(
Substring(
@fullName,
Subtract(Length(@fullName),1),2)))
ENDIF
/*Rule 5 First letter after "Mac" if it is capitalized
and all subsequent letters are lowercase*/
SET @validateRule1=IndexOf(@fullName,"Mac")
IF @validateRule1>0 THEN
SET @fullName=ProperCase(@fullName)
SET @fullName=Replace(
@fullName,
Substring(
@fullName,
Add(@validateRule1,3),1),
Uppercase(
Substring(
@fullName,Add(@validateRule1,3),1)))
SET @fullName=Replace(
@fullName,
Substring(
@fullName,
Subtract(Length(@fullName),1),2),
Lowercase(
Substring(@fullName,
Subtract(Length(@fullName),1),2)))
ENDIF
ENDIF
]%%
%%=v(@fullName)=%%
//Example2
%%[
/* Get data from sending DE and set as variables */
VAR @firstName, @birthDate
SET @firstName = [FirstName]
/*validate firstname is not empty else assign a default value*/
IF Empty(@firstName) THEN SET @firstName = "Trailblazer RisingStars" ENDIF
SET @birthDate = [DOB]
/* SET voucher variables */
SET @promoVoucher = "abcd-efgh-ijkl-mnop-qrst"
SET @expDate = "12/31/2022"
]%%
Happy Birthday, %%=ProperCase(@firstName)=%%!
To celebrate your birthday on %%=FormatDate(@birthDate, "MMM DD")=%%, we are giving you %%=v(@promoVoucher)=%%
for Salesforce Associate Certification.
Prepare and enroll soon! This voucher will expire on %%=v(@expDate)=%%.
//Example3
%%[
/*Initialize the variables*/
set @fullName='Shashi Prasad'
/*get the index of space between first name and last name */
set @index=IndexOf(@fullName,' ')
/*get the index of the last character for first name */
set @offsetStart=Subtract(@index,1)
/*get the index of the first character for last name */
set @offsetEnd=Add(@index,1)
/*Extract the first name with substring starting with 0 and navigating to the last character of the first name */
set @firstName=Substring(@fullName,0,@offsetStart)
/*get the length of the full name */
set @length=Length(@fullName)
/*Extract the last name with substring starting with first char of last name and navigating to the last character of the last name */
set @lastName=Substring(@fullName,@offsetEnd,@length)
]%%
Details :
First Name : %%=v(@firstName)=%%
Last Name : %%=v(@lastName)=%%
Write an AMPScript block to delete products where Gender='Women' and Season='Winter' when email is send
%%[
SET @subscriberkey=_subscriberkey
SET @email=emailaddr
SET @season='winter' /*Summer*/
SET @firstName='Madhu'
SET @lastName='Prasad'
SET @productId=1
SET @gender='women'
SET @rows=DeleteDE('PRODUCTS',
'GENDER',PROPERCASE(@gender),
'SEASON',PROPERCASE(@season)
)
]%%
%%=v(Concat('No of Rows Deleted : ',@rows))=%%
Write an AMPScript block to update the Subscriber status to "Active"
%%[
/* Assign values for SubscriberKey and EmailAddress */
SET @subscriberKey = AttributeValue("_subscriberkey")
SET @emailAddress = AttributeValue("emailaddr")
/* Create a new Subscriber object */
SET @subscriberObject = CreateObject("Subscriber")
SetObjectProperty(@subscriberObject, "EmailAddress", @emailAddress)
SetObjectProperty(@subscriberObject, "SubscriberKey", @subscriberKey)
/* Set the status of the subscriber to Unsubscribed */
SetObjectProperty(@subscriberObject, "Status", "Active")
/* Create a new ClientID object */
SET @clientIdObject = CreateObject("ClientID")
SetObjectProperty(@clientIdObject, "ID", "1123XXXXXXX")
SetObjectProperty(@clientIdObject, "IDSpecified", "true")
/* Associate the ClientID object with the Subscriber */
SetObjectProperty(@subscriberObject, "Client", @clientIdObject)
/* Define Update Options */
SET @updateOptions = CreateObject("UpdateOptions")
SET @saveOption = CreateObject("SaveOption")
SetObjectProperty(@saveOption, "SaveAction", "UpdateAdd")
SetObjectProperty(@saveOption, "PropertyName", "*")
AddObjectArrayItem(@updateOptions, "SaveOptions", @saveOption)
/* Update the Subscriber object */
SET @updateStatus = InvokeUpdate(@subscriberObject, @updateStatusMessage, @updateErrorCode, @updateOptions)
/* Log the subscriber details and status of the update operation */
SET @logDataExtensionName = "InvokeUpdate" /* Replace with your logging data extension name */
SET @logStatus = InsertData(
@logDataExtensionName,
"updateStatus", @updateStatus,
"updateStatusMessage", @updateStatusMessage,
"updateErrorCode", @updateErrorCode,
"subscriberKey", @subscriberKey,
"emailAddress", @emailAddress
)
]%%
Write an AMPScript block to retrieve Subscribers
%%[
/* Create the RetrieveRequest object to retrieve the Subscriber by EmailAddress */
SET @subscriberRetrieveRequest = CreateObject("RetrieveRequest")
SetObjectProperty(@subscriberRetrieveRequest, "ObjectType", "Subscriber")
AddObjectArrayItem(@subscriberRetrieveRequest, "Properties", "EmailAddress")
AddObjectArrayItem(@subscriberRetrieveRequest, "Properties", "SubscriberKey")
/* Create and configure the filter for the RetrieveRequest */
SET @emailFilter = CreateObject("SimpleFilterPart")
SetObjectProperty(@emailFilter, "Property", "EmailAddress")
SetObjectProperty(@emailFilter, "SimpleOperator", "equals")
AddObjectArrayItem(@emailFilter, "Value", "b2.shashi@gmail.com")
SetObjectProperty(@subscriberRetrieveRequest, "Filter", @emailFilter)
/* Invoke the RetrieveRequest to get the Subscriber object */
SET @subscriberResponse = InvokeRetrieve(@subscriberRetrieveRequest, @retrieveStatus, @retrieveRequestID)
/* Iterate over the retrieved subscriber rows */
FOR @rowIndex = 1 TO RowCount(@subscriberResponse) DO
SET @subscriberRow = Row(@subscriberResponse, @rowIndex)
SET @retrievedSubscriberKey = Field(@subscriberRow, "SubscriberKey")
/* Output the SubscriberKey */
OutputLine(Concat("Retrieved SubscriberKey: ", @retrievedSubscriberKey))
NEXT @rowIndex
]%%
Write an AMPScript block to accessToken via BUILDROWSETFROMJSON
%%[
VAR @endpoint,@payload, @callstatus, @response, @clientId, @clientSecret
VAR @DataExtensionName,@numberOfRows,@property,@value,@dataset,@i
/* ===================== variables assignment =======================*/
SET @contentType='application/json; charset=utf-8'
SET @DataExtensionName='InstallPackages'
SET @numberOfRows=1
SET @property='APIConfig'
SET @value='TransactionalAPI'
/* call LookupOrderedRows to Retrieve API Config details*/
SET @rowset=LookupOrderedRows(
@DataExtensionName,
@numberOfRows,
"ClientID desc,ClientSecret desc",
@property,
@value)
/* ===================================================================*/
IF RowCount(@rowset) > 0 THEN
FOR @i=1 TO RowCount(@rowset) DO
SET @row=Row(@rowset,@i)
SET @AuthAPI=FIELD(@row,'AuthAPI')
SET @clientId=FIELD(@row,'ClientID')
SET @clientSecret=FIELD(@row,'ClientSecret')
NEXT @i
ENDIF
/* ===================== variables assignment =======================*/
SET @DataExtensionName='APIMethods'
SET @numberOfRows=1
SET @property='MethodName'
SET @value='Request SFMC Token'
/* call LookupOrderedRows to Retrieve Method URL details*/
SET @rowset=LookupOrderedRows(@DataExtensionName,
@numberOfRows,
"MethodURL desc",
@property,
@value)
/* ===================================================================*/
IF RowCount(@rowset) > 0 THEN
FOR @i=1 to RowCount(@rowset) DO
SET @row=Row(@rowset,@i)
SET @MethodURL=FIELD(@row,'MethodURL')
NEXT @i
ENDIF
/* ===================== variables assignment =======================*/
SET @endpoint = Concat(@AuthAPI,@MethodURL)
/* define the payload*/
SET @payload = Concat(
'{
"client_id": "',@clientId,'",
"client_secret": "',@clientSecret,'",
"grant_type": "client_credentials"
}'
)
/* Invoke HTTPPOST */
HTTPPost2(@endpoint, @contentType, @payload,true,@response, @callstatus)
SET @rowset=BuildRowsetFromJson(@response, '$.*',1)
SET @row=Row(@rowset,1)
SET @accessToken=FIELD(@row,'Value')
SET @row=Row(@rowset,2)
SET @tokentype=FIELD(@row,'Value')
SET @authorization=Concat(@tokentype,' ',@accessToken)
]%%
%%=v(@authorization)=%%
Write an AMPScript block to update mobile number in Mobile Connect Demographics
%%[
SET @rows = LookupOrderedRows("PhoneNumber_Update",DataExtensionRowCount("PhoneNumber_Update"),"NewMobileNumber desc","IsUpdated", 0)
SET @rowCount = RowCount(@rows)
IF @rowCount > 0 THEN
FOR @i = 1 TO @rowCount DO
SET @row = ROW(@rows, @i)
SET @ContactID = field(@row,"ContactID")
SET @NewMobileNumber = field(@row,"NewMobileNumber")
UpdateData('_MobileAddress',1,'_ContactID',@ContactID,'_MobileNumber',@NewMobileNumber)
UpdateData('PhoneNumber_Update',1,'ContactID',@ContactID,'IsUpdated',1)
NEXT @i
ENDIF
]%%
Write an AMPScript block to retrieve data extension
%%[
/* Set the CustomerKey of the Data Extension you want to retrieve */
SET @targetCustomerKey = "B242D507-D37D-45E4-ABCB-FC9403433686"
/* Create the RetrieveRequest object */
SET @retrieveRequest = CreateObject("RetrieveRequest")
/* Specify the object type and properties to retrieve */
SetObjectProperty(@retrieveRequest, "ObjectType", "DataExtension")
AddObjectArrayItem(@retrieveRequest, "Properties", "Name")
AddObjectArrayItem(@retrieveRequest, "Properties", "CustomerKey")
AddObjectArrayItem(@retrieveRequest, "Properties", "IsSendable")
/* Create and configure the filter for the RetrieveRequest */
SET @filterPart = CreateObject("SimpleFilterPart")
SetObjectProperty(@filterPart, "Property", "CustomerKey")
SetObjectProperty(@filterPart, "SimpleOperator", "equals")
AddObjectArrayItem(@filterPart, "Value", @targetCustomerKey)
SetObjectProperty(@retrieveRequest, "Filter", @filterPart)
/* Invoke the RetrieveRequest */
SET @retrieveResponse = InvokeRetrieve(@retrieveRequest, @statusMessage, @requestId)
/* Retrieve and validate the response */
SET @responseRow = Row(@retrieveResponse, 1) /* Retrieve the first row from the response */
SET @retrievedCustomerKey = Field(@responseRow, "CustomerKey")
SET @dataExtensionName = Field(@responseRow, "Name")
SET @isSendable = Field(@responseRow, "IsSendable")
/* Output the name of the Data Extension with a user-friendly message */
OutputLine(Concat("Data Extension Name: ", @dataExtensionName))
/* Output the IsSendable flag with a user-friendly message */
OutputLine(Concat("Data Extension is: ", @isSendable))
]%%
Write an AMPScript block to run an automation
%%[
/* Set the Automation Name to retrieve */
SET @automationName = "SOAP_API_Automation"
/* Create the RetrieveRequest object */
SET @retrieveRequest = CreateObject("RetrieveRequest")
/* Specify the object type and properties to retrieve */
SetObjectProperty(@retrieveRequest, "ObjectType", "Automation")
AddObjectArrayItem(@retrieveRequest, "Properties", "Name")
AddObjectArrayItem(@retrieveRequest, "Properties", "CustomerKey")
/* Create and configure the filter for the RetrieveRequest */
SET @filterPart = CreateObject("SimpleFilterPart")
SetObjectProperty(@filterPart, "Property", "Name")
SetObjectProperty(@filterPart, "SimpleOperator", "equals")
AddObjectArrayItem(@filterPart, "Value", @automationName)
SetObjectProperty(@retrieveRequest, "Filter", @filterPart)
/* Invoke the RetrieveRequest */
SET @retrieveResponse = InvokeRetrieve(@retrieveRequest, @statusMessage, @requestId)
/* Retrieve and validate the response */
IF RowCount(@retrieveResponse) > 0 THEN
SET @responseRow = Row(@retrieveResponse, 1) /* Retrieve the first row from the response */
SET @retrievedCustomerKey = Field(@responseRow, "CustomerKey")
SET @name = Field(@responseRow, "Name")
/* Output the name and CustomerKey with user-friendly messages */
OutputLine(Concat("Automation Name: ", @name))
OutputLine(Concat("CustomerKey: ", @retrievedCustomerKey))
/* Create Automation object to start the automation */
SET @automation = CreateObject("Automation")
SET @clientId=CreateObject("ClientID")
SetObjectProperty(@clientId, "ID", AuthenticatedMemberID())
SetObjectProperty(@clientId, "UserID", AuthenticatedEmployeeID())
SetObjectProperty(@automation, "CustomerKey", @retrievedCustomerKey)
SetObjectProperty(@automation, "Client", @clientId)
/* Invoke the 'start' operation on the automation */
SET @statusCode = InvokePerform(@automation, "start", @statusMessage)
/* Handle the status message of the start operation */
IF @statusCode != "OK" THEN
OutputLine(Concat("Failed to start automation. Status Message: ", @statusMessage))
ELSE
OutputLine(@statusMessage)
ENDIF
ELSE
OutputLine("No automation found with the specified name.")
ENDIF
]%%
Write an AMPScript block to invoke log unsub event
%%[
/* Retrieve the SubscriberKey and JobID from the query parameters */
SET @subscriberKey = AttributeValue("_subscriberkey") /* Subscriber key */
SET @jobId = AttributeValue("jobid") /* Job ID */
/* Define the reason for unsubscribing */
SET @unsubscribeReason = "Profile Center Unsubscribe" /* Unsubscribe reason */
/* Create a SOAP API ExecuteRequest object for the LogUnsubEvent utility function */
SET @executeRequest = CreateObject("ExecuteRequest") /* SOAP API request */
/* Set the name of the utility function to LogUnsubEvent */
SetObjectProperty(@executeRequest, "Name", "LogUnsubEvent") /* Name of the SOAP method */
/* Create and configure a SOAP API Property object for SubscriberKey */
SET @subscriberKeyProperty = CreateObject("APIProperty") /* Property object for SubscriberKey */
SetObjectProperty(@subscriberKeyProperty, "Name", "SubscriberKey") /* Name: SubscriberKey */
SetObjectProperty(@subscriberKeyProperty, "Value", @subscriberKey) /* Value: retrieved SubscriberKey */
/* Add the SubscriberKey property to the Parameters array in the SOAP request */
AddObjectArrayItem(@executeRequest, "Parameters", @subscriberKeyProperty)
/* Create and configure a SOAP API Property object for JobID */
SET @jobIdProperty = CreateObject("APIProperty") /* Property object for JobID */
SetObjectProperty(@jobIdProperty, "Name", "JobID") /* Name: JobID */
SetObjectProperty(@jobIdProperty, "Value", @jobId) /* Value: retrieved JobID */
/* Add the JobID property to the Parameters array in the SOAP request */
AddObjectArrayItem(@executeRequest, "Parameters", @jobIdProperty)
/* Create and configure a SOAP API Property object for the Unsubscribe Reason */
SET @reasonProperty = CreateObject("APIProperty") /* Property object for Unsubscribe Reason */
SetObjectProperty(@reasonProperty, "Name", "Reason") /* Name: Reason */
SetObjectProperty(@reasonProperty, "Value", @unsubscribeReason) /* Value: predefined reason */
/* Add the Reason property to the Parameters array in the SOAP request */
AddObjectArrayItem(@executeRequest, "Parameters", @reasonProperty)
/* Invoke the SOAP API function to log the unsubscribe event */
SET @executionStatus = InvokeExecute(@executeRequest, @overallStatus, @requestId) /* Execute the request */
/* Retrieve the first row from the execution status response */
SET @responseRow = Row(@executionStatus, 1) /* Get the first response row */
/* Retrieve status message and error code from the response */
SET @statusMessage = Field(@responseRow, "StatusMessage") /* Status message from response */
SET @errorCode = Field(@responseRow, "ErrorCode") /* Error code from response */
/* Log the details of the unsubscribe operation in a Data Extension */
SET @logDataExtensionName = "ExecuteRequest" /* Replace with your actual Data Extension name */
SET @logStatus = InsertData(
@logDataExtensionName,
"StatusMessage", @statusMessage,
"ErrorCode", @errorCode,
"overallStatus", @overallStatus,
"SubscriberKey", @subscriberKey,
"requestId", @requestId
) /* Log the details in the specified Data Extension */
]%%
Write an AMPScript block for email hyper personalization
%%[
/* Retrieve the CustomerID passed to the email */
SET @customerID = AttributeValue("CustomerID")
/* Declare variables to store Data Extension values */
SET @firstName = ""
SET @lastName = ""
SET @membershipLevel = ""
SET @promotionText = "Check out our latest deals and offers!"
SET @purchaseRows = ""
SET @errorMessage = ""
/* Look up customer details */
SET @customerRow = LookupRows("CustomerDetails", "CustomerID", @customerID)
IF RowCount(@customerRow) > 0 THEN
SET @firstName = Field(Row(@customerRow, 1), "FirstName")
SET @lastName = Field(Row(@customerRow, 1), "LastName")
SET @membershipLevel = Field(Row(@customerRow, 1), "MembershipLevel")
ELSE
SET @errorMessage = "We couldn't retrieve your details at this time."
ENDIF
/* Fetch the promotion for the customer's membership level if no error */
IF EMPTY(@errorMessage) THEN
SET @promotionRow = LookupRows("Promotions", "MembershipLevel", @membershipLevel)
IF RowCount(@promotionRow) > 0 THEN
SET @promotionText = Field(Row(@promotionRow, 1), "PromotionText")
ELSE
SET @promotionText = "Enjoy our general offers and discounts!"
ENDIF
ENDIF
/* Fetch the last 3 purchases of the customer if no error */
IF EMPTY(@errorMessage) THEN
SET @purchaseRows = LookupOrderedRows("PurchaseHistory", 3, "PurchaseDate DESC", "CustomerID", @customerID)
IF RowCount(@purchaseRows) == 0 THEN
SET @errorMessage = "We couldn't find your purchase history."
ENDIF
ENDIF
/* If an error occurred, provide fallback content */
IF NOT EMPTY(@errorMessage) THEN
SET @firstName = "Valued Customer"
SET @lastName = ""
SET @promotionText = "Explore our latest products and offers!"
ENDIF
]%%
Write an AMPScript block for to retrieve all subsriberkeys associated with an email address
%%[
/* Create the RetrieveRequest object to retrieve the Subscriber by EmailAddress */
SET @subscriberRetrieveRequest = CreateObject("RetrieveRequest")
SetObjectProperty(@subscriberRetrieveRequest, "ObjectType", "Subscriber")
AddObjectArrayItem(@subscriberRetrieveRequest, "Properties", "EmailAddress")
AddObjectArrayItem(@subscriberRetrieveRequest, "Properties", "SubscriberKey")
/* Create and configure the filter for the RetrieveRequest */
SET @emailFilter = CreateObject("SimpleFilterPart")
SetObjectProperty(@emailFilter, "Property", "EmailAddress")
SetObjectProperty(@emailFilter, "SimpleOperator", "equals")
AddObjectArrayItem(@emailFilter, "Value", "b2.shashi@gmail.com") /* Replace with the email address you are searching for */
SetObjectProperty(@subscriberRetrieveRequest, "Filter", @emailFilter)
/* Invoke the RetrieveRequest to get the Subscriber object */
SET @subscriberResponse = InvokeRetrieve(@subscriberRetrieveRequest, @retrieveStatus, @retrieveRequestID)
/* Iterate over the retrieved subscriber rows */
FOR @rowIndex = 1 TO RowCount(@subscriberResponse) DO
SET @subscriberRow = Row(@subscriberResponse, @rowIndex)
SET @retrievedSubscriberKey = Field(@subscriberRow, "SubscriberKey")
/* Output the SubscriberKey */
OutputLine(Concat("Retrieved SubscriberKey: ", @retrievedSubscriberKey))
NEXT @rowIndex
]%%
Write an AMPScript block for to retrieve all subsribers associated with Business Unit
%%[
/* Specify the MID (Client ID) */
SET @clientID = "123456789"
/* Create RetrieveRequest object for Subscriber */
SET @subscriberRetrieveRequest = CreateObject("RetrieveRequest")
SetObjectProperty(@subscriberRetrieveRequest, "ObjectType", "Subscriber")
/* Specify properties to retrieve */
AddObjectArrayItem(@subscriberRetrieveRequest, "Properties", "SubscriberKey")
AddObjectArrayItem(@subscriberRetrieveRequest, "Properties", "EmailAddress")
AddObjectArrayItem(@subscriberRetrieveRequest, "Properties", "Status")
AddObjectArrayItem(@subscriberRetrieveRequest, "Properties", "CreatedDate")
AddObjectArrayItem(@subscriberRetrieveRequest, "Properties", "Client.ID") /* MID filter */
/* Create and apply filter for Client.ID */
SET @clientIDFilter = CreateObject("SimpleFilterPart")
SetObjectProperty(@clientIDFilter, "Property", "Client.ID")
SetObjectProperty(@clientIDFilter, "SimpleOperator", "equals")
AddObjectArrayItem(@clientIDFilter, "Value", @clientID)
/* Assign the filter to the RetrieveRequest */
SetObjectProperty(@subscriberRetrieveRequest, "Filter", @clientIDFilter)
/* Perform the retrieve operation */
SET @subscriberResponse = InvokeRetrieve(@subscriberRetrieveRequest, @retrieveStatus, @retrieveRequestID)
/* Output retrieved results if found */
IF RowCount(@subscriberResponse) > 0 THEN
FOR @rowIndex = 1 TO RowCount(@subscriberResponse) DO
SET @subscriberRow = Row(@subscriberResponse, @rowIndex)
SET @retrievedSubscriberKey = Field(@subscriberRow, "SubscriberKey")
SET @retrievedEmail = Field(@subscriberRow, "EmailAddress")
SET @retrievedStatus = Field(@subscriberRow, "Status")
SET @retrievedDate = Field(@subscriberRow, "CreatedDate")
/* Output subscriber details */
OutputLine(Concat("SubscriberKey: ", @retrievedSubscriberKey))
OutputLine(Concat("EmailAddress: ", @retrievedEmail))
OutputLine(Concat("Status: ", @retrievedStatus))
OutputLine(Concat("CreatedDate: ", @retrievedDate))
NEXT @rowIndex
ELSE
OutputLine("No subscribers found for the specified Client ID.")
ENDIF
]%%
Write an AMPScript block to run SQL Activity
%%[
/* Set the name of the QueryDefinition to retrieve */
SET @queryName = "Query1"
/* Create a RetrieveRequest object for querying the QueryDefinition */
SET @retrieveRequest = CreateObject("RetrieveRequest")
/* Specify that we are retrieving a QueryDefinition and the properties we want */
SetObjectProperty(@retrieveRequest, "ObjectType", "QueryDefinition")
AddObjectArrayItem(@retrieveRequest, "Properties", "Name") /* Retrieve the Name property */
AddObjectArrayItem(@retrieveRequest, "Properties", "ObjectID") /* Retrieve the ObjectID property */
/* Create a filter for the RetrieveRequest to specify which QueryDefinition to retrieve */
SET @filterPart = CreateObject("SimpleFilterPart")
SetObjectProperty(@filterPart, "Property", "Name") /* Filter by the Name property */
SetObjectProperty(@filterPart, "SimpleOperator", "equals") /* Use an equality check */
AddObjectArrayItem(@filterPart, "Value", @queryName) /* Set the filter value to @queryName */
SetObjectProperty(@retrieveRequest, "Filter", @filterPart) /* Assign the filter to the RetrieveRequest */
/* Invoke the RetrieveRequest and store the response */
SET @retrieveResponse = InvokeRetrieve(@retrieveRequest, @statusMessage, @requestId)
/* Check if the RetrieveRequest was successful */
IF Empty(@retrieveResponse) OR RowCount(@retrieveResponse) == 0 THEN
OutputLine("No query found with the specified name or retrieve operation failed.")
IF NOT Empty(@statusMessage) THEN
OutputLine(Concat("Retrieve Status Message: ", @statusMessage))
ENDIF
ELSE
/* Retrieve the first row from the response */
SET @responseRow = Row(@retrieveResponse, 1)
SET @retrievedObjectID = Field(@responseRow, "ObjectID") /* Get the ObjectID of the QueryDefinition */
SET @name = Field(@responseRow, "Name") /* Get the Name of the QueryDefinition */
/* Output the name and ObjectID of the QueryDefinition for verification */
OutputLine(Concat("Query Definition Name: ", @name))
OutputLine(Concat("ObjectID: ", @retrievedObjectID))
/* Create an instance of the QueryDefinition object for invoking the automation */
SET @query = CreateObject("QueryDefinition")
/* Create ClientID object to specify the context for the automation */
SET @clientId = CreateObject("ClientID")
SetObjectProperty(@clientId, "ID", AuthenticatedMemberID()) /* Set the Member ID */
SetObjectProperty(@clientId, "UserID", AuthenticatedEmployeeID()) /* Set the User ID */
/* Attempt to set up the Automation object for starting */
SetObjectProperty(@query, "ObjectID", @retrievedObjectID) /* Use the retrieved ObjectID */
SetObjectProperty(@query, "Client", @clientId) /* Attach the Client context */
/* Attempt to start the automation process by invoking the 'start' operation */
SET @statusCode = InvokePerform(@query, "start", @statusMessage)
/* Check if the automation start was successful */
IF @statusCode != "OK" THEN
/* Output error message if starting the automation failed */
OutputLine(Concat("Failed to start query. Status Message: ", @statusMessage))
ELSE
/* Output success message if starting the automation succeeded */
OutputLine("Automation started successfully.")
ENDIF
ENDIF
]%%
Comments
Post a Comment