Salesforce Marketing Cloud Ampscript Basics

Salesforce-Marketing-Cloud-Ampscript-Basics-Body

Scripted Personalization

Why AMPscript?

ampscript

Why we have scripting

  • Advanced dynamic content scenarios
  • Accessing relational data
  • Accessing subscriber metadata (attributes) & MC metadata
  • Data formatting and validation
  • Control logic

WHAT DOES THAT MEAN???

  • Lookup Flight Stats Data
  • Credit Card Number Encrypted
  • Update SF Case Status from Landing Page
  • 2-Way SMS Conversations
  • Online/Offline Location-based Offers
  • Dynamic Barcode Generation
  • Social Sentiment Offer Generation
  • Understanding Channel Context (SOCIAL, PREVIEW, EMAIL)

Languages  :- 

AMPscript (amp)

  • Mainly used in emails & landing pages
  • Supported in MobileConnect, MobilePush, Microsites, CloudPages
  • Released in 2008
  • Fully supported and updated
  • Similar syntax to Visual Basic

Server-Side JavaScript (ssjs)

  • Landing pages and Interactions Script Activities only (for production) 
  • In maintenance mode – no support or new functionality will be added
  • Follows ECMAScript 3.0 standards (6.0 is the latest)
  • No 1:1 AMPscript functionality
  • Slower rendering time in OMM (a lot slower)
  • Outbound Mail Management (where the code is compiled)

Guide Template Language (GTL)

  • Message templates & templating language
  • Same message content area across all channels
  • Don’t use…

<h1>{{title}}</h1>

<p>{{description}}</p>

ampscript2

AMP & SSJS

How & when + examples

ampscript3

Triggered Send :- 

AMPscript

VAR @ts, @tsDef, @ts_sub, @ts_attr, @tsctr, @ts_subkey, @ts_statusCode, @ts_statusMsg, @errorCode

 SET @ts = CreateObject(“TriggeredSend”)

SET @tsDef = CreateObject(“TriggeredSendDefinition”)

SET @ts_subkey = RequestParameter(“Email”)

SetObjectProperty(@tsDef, “CustomerKey”, “RequestDemo”)

SetObjectProperty(@ts, “TriggeredSendDefinition”, @tsDef)

 SET @ts_sub = CreateObject(“Subscriber”)

SetObjectProperty(@ts_sub, “EmailAddress”, RequestParameter(“Email”))

IF NOT EMPTY(@ts_subkey) THEN

SetObjectProperty(@ts_sub, “SubscriberKey”, @ts_subkey)

ELSE

SetObjectProperty(@ts_sub, “SubscriberKey”, RequestParameter(“Email”))

ENDIF

 AddObjectArrayItem(@ts, “Subscribers”, @ts_sub)

SET @ts_statusCode = InvokeCreate(@ts, @ts_statusMsg, @errorCode)

IF @ts_statusCode != “OK” THEN

RaiseError(@ts_statusMsg, 0, @ts_statusCode, @errorCode)

ENDIF

 

SSJS

var triggeredSend = TriggeredSend.Init(“triggeredSend”);

var status = triggeredSend.Send(“aruiz@example.com”);

Capabilities

  • API CRUD (create, retrieve, update & delete)
  • Data Extension/List retrieve, lookup & upsert
  • Externally/Internally hosted RSS/XML Content Syndication
  • Email attachments
  • Encryption/Decryption
  • Dynamically set URLs
  • Interact with Salesforce
  • “API” page with Landing Pages

Tools  & Testing

Editors

  • TextMate (https://github.com/whgfive/AMP-Bundle)
  • Sublime (Package Control)
  • Any ole’ text editor (Perl)

ampscript6

ampscript4

ampscript5

Scripting Resources

Understanding Documentation

Lookup(S1, S2, S3, S4)

  • Lookup(“Flights”, “FlightNumber”, “CustomerId”, _subscriberkey)

Quick Testing – Dropbox

dropbox1 dropbox2 dropbox3

%%=V(TreatAsContent(HTTPGet(“DROPBOXLINK”)))=%%

Troubleshooting Techniques

  • Comment out as much as possible
  • Set everything to variables and output
  • Double-check delimiters, quotes, parentheses, etc…
  • Double-check names

Introduction to Scripting

Basic Syntax

AMPscript Block vs. Inline

  1. %%[
  2.   VAR @firstName, @greeting
  3.   SET @firstName = ”William”
  4.   SET @greeting = Concat(“Hello ”, @firstName)
  5.   Output(@greeting)
  6. ]%%
  7. %%=Concat(“Hello ”, @firstName)=%%
  8. %%=V(@greeting)=%%

 

%%[ Block ]%%

  • Declare and set variables
  • Process conditional logic (if else)
  • Large amounts of data formatting / processing  

%%= Inline =%%

  • Output variables or function responses
  • Embed easily into HTML
  1. %%[
  2.   VAR @firstName, @greeting
  3.   SET @firstName = ”William”
  4.   SET @greeting = Concat(“Hello ”, @firstName)
  5.   Output(@greeting)
  6. ]%%
  7. %%=Concat(“Hello ”, @firstName)=%%

Output

                  Hello William

Output       

                  Hello William

Best Practices for Variables

  • Always DECLARE the variable and SET the value separately
  • Always START variable names with letters A – Z  (after the @ of course)
  • Variable names cannot contain spaces
  • Avoid names that are already common system variables or personalization strings
    • @emailaddr
    • @date
  • You can DECLARE multiple variables at once by comma-delimiting the variable names
  • VAR @thing1, @thing2
  • You can only SET one variable at a time  

Declaring & Setting Variables 

  1. %%[
  2.     VAR @firstName, @email, @returnValue
  3.     SET @firstName = ”William”
  4.     SET @email = emailaddr
  5.     SET @returnValue = Concat(@firstName, “ – ”, @email)
  6.     // Make sure you DECLARE and SET separately
  7.     VAR @badSyntax = ”This won’t work”
  8. ]%% 

AMPscript Comments

  1. %%[
  2.     /*
  3.       This is a block comment
  4.     */
  5.     // This is an inline comment… 
  6.        “We’re just like javascript”
  7. ]%%

Nesting Functions 

  1. %%[
  2.     VAR @firstName, @greeting
  3.     SET @firstName = ”William”
  4.     SET @greeting = Concat(“Hello ”, @firstName)
  5.  Output(Concat(“Hello ”, @firstName))
  6. ]%%
  7. // Also works inline… 
  8. %%=Output(Concat(“Hello ”, @firstName))=%%

 Various Attribute Sources

  • Profile Attributes
  • Sendable Data Extension Fields
  • Send-Time Attributes
  • System Variables 

Accessing Attributes from Script Block 

  1. %%[    
  2.     SET @profileAttribute = Gender
  3.     SET @profileAttributeWithSpaces = [First Name]
  4.     SET @profileAttributeFormatted = ProperCase([Last Name])
  5.     SET @unknownAttributeName = AttributeValue(@attributeName)
  6.     SET @sendableDEField = FlightNumber 
  7.     SET @sendTime = SKU
  8.     SET @systemVariable = MOBILE_NUMBER
  9.     SET @queryString = QueryParameter(“email”)
  10. ]%%

Accessing Attributes Inline

  1. %%Gender%%
  2.     %%First Name%%
  3.     %%=ProperCase([Last Name])=%%
  4.     %%=AttributeValue(@attributeName)=%%
  5.     %%FlightNumber%%
  6.     %%SKU%%
  7.     %%MOBILE_NUMBER%%
  8.     %%=QueryParameter(“email”)=%% 

Mobile Usage 

  1. %%[SET @msg = MSG(0)]%%
  2.        //Returns the message
  3.     %%[SET @verb = MSG(0).VERB]%%
  4.        //Returns the verb/keyword of the message
  5.     %%[SET @nouns = MSG(0).NOUNS]%%
  6.        //Returns the part of the current message after the verb
  7.     %%[SET @noun = MSG(0).NOUN(1)]%%
  8.       //Returns the second noun in the current message.

SendLogging

  1. SET @LoyaltyLevel = “1”
  2.     SET @Membership = IIF(NOT EMPTY(member),”TRUE”,”FALSE”)
  3.     SET @ZipCode = Lookup(…)  

sendlogging

Common Uses

Conditions 

Common Types of Conditions

  • IF THEN ELSE ENDIF
  • Checks for validity   

IF THEN ELSE  

  1. %%[IF expression1 <comparison operator> expression2 THEN]%%
  2. %%[ELSEIF expression1 <comparison operator> expression3 THEN]%%
  3. %%[ELSE]%%
  4. %%[ENDIF]%%

Conditions  

  1. == Is equal to
  2. != Is not equal to
  3. > Greater than
  4. < Less Than
  5. >= Greater than or equal to
  6. <= Less than or equal to
  7. AND Both conditions must be true
  8. OR Either condition must be true

NOT Reverses the Boolean expression

Combined 

  1. %%[IF expression1 <comparison operator> expression2
  2.         AND [NOT] (expression3 <comparison operator> expression4
  3.         OR expression3 <comparison operator> expression5)
  4. THEN 
  5. ENDIF]%%
  6. %%[IF @age > 13 AND loyalty == TRUE THEN]%%
  7. %%MailingAddress%%
  8. %%[ENDIF]%%
  9. %%[IF NOT empty(MailingAddress) THEN]%%
  10. %%MailingAddress%%
  11. %%[ENDIF]%%

Utilities 

Common Types of Utilities

  • DateTime Functions
  • Math Functions
  • Formatting Text, Numbers or Currency
  • Validation & Parsing

Common DateTime Scenarios

  1. SET @today = Now()
  2.     // –> 8/28/2013 12:05:00 PM
  3. SET @formatted = Format(@today, “MM/dd/yyyy”)
  4.     // –> 08/28/2013
  5. SET @tomorrow = DateAdd(@today, 1, “D”)
  6.     // –> 8/29/2013 12:05:00 PM 
  7. SET @theYear = DatePart(@today, “year”)
  8.     // –> 2013 

Common Formatting Scenarios 

  1. SET @uppercaseName = Uppercase(“william”)
  2.     // –> WILLIAM
  3. SET @capitalizedName = ProperCase(“william garrison”)
  4.     // –> William Garrison
  5. SET @fullName = Concat(@firstName, “ ”,@lastName)
  6.     // –> William Garrison
  7. SET @replacedName = Replace(@fullName, “William”, “John”)
  8.     // –> John Garrison

Common Validation Scenarios  

  1. SET @firstName = “William”
  2. SET @emptyTest = Empty(@firstName)
  3.     // –> false
  4. SET @result = IIf(Empty(@firstName), “Friend”, @firstName)
  5.     // –> William
  6. SET @emailTest = IsEmailAddress(“wgarrison@salesforce.com”)
  7.     // –> true

Common Parsing Scenarios

  1. SET @firstLetter = Char(“william”, 1)
  2.     // –> a
  3. SET @regexResult = ProperCase(“ABC_123_DEF_456”, “.*_([0-9]+)_.*_([0-9]+)”, 1)
  4.     // –> 123  

ampscript7

Query Parameters  

  1. SET @fn = QueryParameter(“fn”)
  2.     // –> rachel
  3. SET @ln = QueryParameter(“ln”)
  4.     // –> morris

Content

Common Types of Content Functions

  • Content areas
  • Treating data as content

Content Areas (Email Only) 

  1. SET @ca1 = ContentArea(“123456”)
  2.     // –> Retrieves the content from id 123456
  3. SET @ca2 = ContentAreaByName(“My ContentsAd Block 250px”)
  4.     // –> Retrieves the content from a named content area

Treating as Content

  1. SET @fn = QueryParameter(“fn”)
  2.     // –> rachel
  3. SET @ln = QueryParameter(“ln”)
  4.     // –> morris

HTTP + Content

Common Types of HTTP Functions

  • Retrieval (HTTPGet/HTTPPost)
  • Link wrapping
  • Query Parameters

Retrieve XML 

  1. SET @blogXML = AttributeValue(“BlogXML”)
  2. SET @blogXML = HTTPGET(“http://news.yahoo.com/rss/entertainment”)
  3. // –> Raw XML String 

Convert XML into Rowset

  1. SET @titles = BuildRowSetFromXML(@blogXML, “//item/title”, 1)
  2. SET @descriptions = BuildRowSetFromXML(@blogXML, “//item/description”, 1)

Loop Over Each Row in the Rowset 

  1. SET @count = RowCount(@titles)
  2. FOR @i = 1 TO @count DO
  3.     SET @currentTitle = Row(@titles, @i)
  4.     SET @currentDescription = Row(@descriptions, @i)
  5.     // –> Title Row at @i Index & Description Row at @i Index
  6.     // Additional processing code goes here…
  7. NEXT @i 

Access a Field from the Row 

  1. SET @title = Field(@currentTitle, “Value”)
  2.     // –> McCartney Added to iHeartRadio festival lineup
  3. SET @description = Field(@currentDescription, “Value”)
  4.     // –> <p><a href=“http://news.yahoo.com/mccartney-added.. 

Retrieving Data

ampscript9ampscript10

Retrieving a Column Value from a DE Row 

  1. SET @flightNo = Lookup(“Flights”, “FlightNumber”, “CustomerId”, _subscriberkey)
  2.     // –> 385

 

Retrieving a Set of Rows from a DE

  • Set Values for the Where Clause
  • Execute a Lookup to Retrieve a Rowset
  • Loop Over Each Row in the Returned Rowset
  • Access a Field from the Row

Updating Data

ampscript13

ampscript14

ampscript15

Upserting a DE Row from an Email

  • Set Values for the Where Clause
  • Set Values to be Upserted
  • Execute the Upsert
  • No Value is Returned

Set Values for the Where Clause

  1. SET @subKey = _subscriberkey
  2.   SET @airline = “American Airlines”

Execute a Lookup to Retrieve a Rowset

  1. SET @flights = LookupRows(“Flights”, “CustomerId”, @subKey, “Airline”, @airline)
  2.     // –> Rowset of every row that matched criteria

Execute a Lookup to Retrieve a Rowset 

  1. SET @flights = LookupOrderedRows(“Flights”, 0, “Departure ASC”, “CustomerId”,       
                                        @subKey, “Airline”, @airline) 
  2.     // –> Rowset of every row that matched criteria, sorted by Departure
  3. SET @flights = LookupOrderedRows(“Flights”, 3, “Departure ASC”, “CustomerId”,       
                                      @subKey, “Airline”, @airline)
  4.     // –> Rowset of the first 3 rows that matched criteria, sorted by Departure

Loop Over Each Row in the Rowset 

  1. SET @count = RowCount(@flights)
  2. FOR @i = 1 TO @count DO
  3.     SET @currentRow = Row(@flights, @i)
  4.     // –> Row at @i Index
  5.     // Additional processing code goes here…
  6. NEXT @i

Access a Field from the Row 

  1. SET @flightNo = Field(@currentRow, “FlightNumber”)
  2.     // –> 385
  3. SET @departure = Field(@currentRow, “Departure”)
  4.     // –> 8/29/2013 09:15:00 AM   

Retrieving a Set of Rows from a DE

  • Set Values for the Where Clause
  • Execute a Lookup to Retrieve a Rowset
  • Loop Over Each Row in the Returned Rowset
  • Access a Field from the Row

Updating Data

ampscript13

ampscript14

ampscript15

Upserting a DE Row from an Email

  • Set Values for the Where Clause
  • Set Values to be Upserted
  • Execute the Upsert
  • No Value is Returned

 

Set the Values for the Where Clause

  1. SET @subKey = _subscriberkey
  2.   SET @flightNo = 385

Set the Values to Be Upserted 

  1. SET @delayed = true
  2.   SET @notifiedDate = NOW() 

Execute the Upsert 

  1. UpsertDE(“Delays”, 2, “CustomerId”, @subKey, “FlightNumber”, @flightNo,    
                “IsDelayed”, @delayed, “NotifiedDate”, @notifiedDate) 
  2.     
  3.     // –> No return value

Execute the Upsert

  1. UpsertData(“Delays”, 2, “CustomerId”, @subKey, “FlightNumber”, @flightNo,    
                “IsDelayed”, @delayed, “NotifiedDate”, @notifiedDate) 
  2.     
  3.     // –> Number of rows affected

Upserting a DE Row from an Email

  • Set Values for the Where Clause
  • Set Values to be Upserted
  • Execute the Upsert

Best Practices

  • Data Management
    • Minimize lookup calls by combining data needed beforehand into sending DE or limited # of DEs using queries, filters, etc
  • LookupRows vs. Lookups
    • Limit count on lookups
  • Always use conditionals to validate variable values needed for logic
  • TreatAsContent for caching
  • Don’t RaiseError() as a segment – filter the data
  • For troubleshooting print variable values into content
  • SSJS does not belong in production code

Haxath0n

ampscript16

Leave a Reply

Your email address will not be published. Required fields are marked *