How can we help?

Cordial utilities reference page

Overview

This page includes all of Cordial's custom Smarty utilities that allow you to read and write data and simplify complex personalization rules. 

Data & message automations Data automations only Message automations only

Data and message automations

deleteSupplementRecord

Deletes a supplement record from the supplement collection using Smarty. If the target supplement record does not exist, the utility will not interrupt script execution.

  • Used in: Message Automations Data Automations
  • Syntax: {$utils->deleteSupplementRecord($supplementKey*, $supplementID*)}
  • {$record.supplementKey = 'automobiles'}
    {$record.supplementId = 1}
    
    {$record.data = $utils->deleteSupplementRecord($record.supplementKey, $record.supplementId)}
    
    {if $record.data}
    Supplement record <strong>{$record.SupplementId}</strong> was deleted from the <strong>{$record.SupplementKey}</strong> supplement collection.
    {else}
    The record was not deleted.
    {/if}
  • Supplement record 1 was deleted from the automobiles supplement collection.
  • Parameters Description Required Expected Default
    supplementKey A unique supplement collection identifier. Required String NA
    supplementId Unique record ID for each supplement in a collection. Cannot be a 24 character hex string. Required String NA

distanceBetweenPostalCodes

Calculates the distance between two postal codes for rendering content based on that distance.

  • {$distance.zip1 = '35244'}
    {$distance.zip2 = '92109'}
    
    {$distance.data = $utils->distanceBetweenPostalCodes($distance.zip1, $distance.zip2)}
    
    {if $distance.data !== 0}
      Distance = {$distance.data}          
    {/if}
    
    <h2>Debug $distance</h2>
    {$utils->jsonPrettyPrint($distance)}
  • Distance = 1756.88

    Debug $distance
    {
        "zip1": 35244,
        "zip2": 92109,
        "data": "1756.88"
    }
    
  • Display "Marketing Content" where the contact's postal code is less than 200 miles from 92131. The address attribute in this example assumes a geo-location type of attribute with a key of address. The contact's postal code can be pulled from any contact attribute.

    {$distance.zip1 = $contact.address.postal_code}
    {$distance.zip2 = '92131'}
    
    {$distance.data = $utils->distanceBetweenPostalCodes($distance.zip1, $distance.zip2)}
    
    {if $distance.data < 200 && $distance.data !== 0}
    Marketing content
    {else}
    Default content
    {/if}

    Calculate the distance between United States and Canada postal codes.

    {$distance.zip1 = '92107'}
    {$distance.zip2 = 'V6R'}
    {$distance.units = 'miles'}
    {$distance.countryZip1 = 'US'}
    {$distance.countryZip2 = 'CA'}
    
    {$distance.data = $utils->distanceBetweenPostalCodes($distance.zip1, $distance.zip2, $distance.units, $distance.countryZip1, $distance.countryZip2)}
    
    {if $distance.data !== 0}
      Distance = {$distance.data}          
    {/if}
    
    <h2>Debug $distanceh2</h2>
    {$utils->jsonPrettyPrint($distance)}
  • Parameters Description Required Expected Default
    zip1 A valid 5 digit US postal code Required Integer NA
    zip2 A valid 5 digit US postal code Required Integer NA
    units Unit of measurement (miles or kilometers) Optional String miles
    countryZip1 A valid 2 digit country code Optional String US
    countryZip2 A valid 2 digit country code Optional String US

getConvertedDate

Using the getConvertedDate utility, you are able to convert a given date and time to a different time zone.

  • Used in: Message Automations Data Automations
  • Syntax: {$utils->getConvertedDate(date*, TOtz*, FROMtz*, format*)}
  • {$convertDate.date = '2020-05-01T18:57:20Z'}
    {$convertDate.to = 'America/Los_Angeles'}
    {$convertDate.from = 'UTC'}
    {$convertDate.format = 'F d Y h:i:s A'}
    
    {$convertDate.data = $utils->getConvertedDate($convertDate.date, $convertDate.to, $convertDate.from, $convertDate.format)}
    
    <strong>Date in UTC:</strong> {$convertDate.date}<br>
    <strong>Date Converted to LA:</strong> {$convertDate.data}
  • Date in UTC: 2020-05-01T18:57:20Z
    Date Converted to LA: May 01 2020 11:57:20 AM
  • Parameters Description Required Expected Default
    date The date to be converted to a different time zone. Required String NA
    TOtz Specify the time zone. If not specified, the default account timezone will be used. Recognized time zone identifiers. Required valid timezone ID NA
    FROMtz Specify the time zone. If not specified, the default account timezone will be used. Recognized time zone identifiers. Required valid timezone ID NA
    format Returns a date string according to the given format. Available date format specifiers. Required string NA

getDistanceBetweenCoordinates

Calculates the distance between two points on the map using longitude and latitude coordinates, and renders the output in miles or kilometers. Message content can then be rendered based on the geographic area within the given distance.

  • Used in: Message Automations Data Automations
  • Syntax: {$utils->getDistanceBetweenCoordinates($latitude1*, $longitude1*, $latitude2*, $longitude2*, $units)}
  • {$distance.lat_1 = 44.1793}
    {$distance.lon_1 = -72.4731}
    {$distance.lat_2 = 32.9014}
    {$distance.lon_2 = -117.2079}
    {$distance.units = 'miles'}
    
    {$distance=$utils->getDistanceBetweenCoordinates($distance.lat_1, $distance.lon_1, $distance.lat_2, $distance.lon_2, $distance.units)}
    
    The distance between 44.1793, -72.4731 and 32.9014, -117.2079 coordinate points is <strong>{$distance}</strong> miles.
  • The distance between 44.1793, -72.4731 and 32.9014, -117.2079 coordinate points is 2505.51 miles.
  • For this example we are using the getCoordinatesFromZip utility to derive longitude and latitude coordinates from two postal codes for use with the getDistanceBetweenCoordinates utility.
    {$distance.zip_a = 92121}
    {$distance.zip_b = 92115}
    {$distance.lat_long_a = $utils->getCoordinatesFromZip($distance.zip_a, "US")}
    {$distance.lat_long_b = $utils->getCoordinatesFromZip($distance.zip_b, "US")}
    
    {$distance.BetweenCoordinates = $utils->getDistanceBetweenCoordinates($distance.lat_long_a.latitude, $distance.lat_long_a.longitude, $distance.lat_long_b.latitude, $distance.lat_long_b.longitude, 'miles')}
    
    <h2>Debug $distance</h2> {$utils->jsonPrettyPrint($distance)}
    Debug $distance
            {
        "zip_a": 92121,
        "zip_b": 92115,
        "lat_long_a": {
            "latitude": "32.9014",
            "longitude": "-117.2079"
        },
        "lat_long_b": {
            "latitude": "32.7555",
            "longitude": "-117.0701"
        },
        "BetweenCoordinates": "12.87"
    }
            
  • Parameter Description Required Expected Default
    $latitude1 Latitude value for the first map coordinate required String NA
    $longitude1 Longitude value for the first map coordinate required String NA
    $latitude2 Latitude value for the second map coordinate required String NA
    $longitude2 Longitude value for the second map coordinate required String NA
    units Unit of measurement (miles or kilometers) optional String miles

getEventRecords

Data stored within the contact activities collection can be referenced and used within any message body.

  • Used in: Message Automations Data Automations
  • Syntax: {$utils->getEventRecords($eventName*, $newerThan, $properties, $limit, $sort)}
  • Learn more about getEventRecords
  • {$events.eventName = 'browse'}
    {$events.newerThan = ''}
    {$events.properties = []}
    {$events.limit = 2}
    {$events.sort = []}
    
    {$events.data = $utils->getEventRecords($events.eventName, $events.newerThan, $events.properties, $events.limit, $events.sort)}
    
    <strong>Items You Browsed</strong><br><br>
    {foreach $events.data as $item}
      {$item.properties.title|capitalize}<br>
      ${$item.properties.price} <br>
      {$item.properties.description|capitalize} <br>
      {$item.properties.url} <br><br>
    {/foreach}
    
    <h2>Debug events</h2>
    {$utils->jsonPrettyPrint($events)}
  • Items You Browsed

    Khaki Shirt
    $9.99
    A Really Cool Khaki Shirt
    http://example.com/shirts

    Khaki Pants
    $19.99
    Awesome Khaki Pants
    http://example.com/shirt

    Debug $events
    [
      {
        "eventName": "browse",
        "newerThan": "",
        "properties": [],
        "limit": 2,
        "sort": [],
        "data": [
          {
            "cID": "58d2fc99ac0c8117814d4e78",
            "_id": "59014a9608ab4e356ec0706a",
            "properties": {
              "title": "khaki shirt",
              "url": "http://example.com/shirt",
              "price": 9.99,
              "description": "a really cool khaki shirt"
            },
            "action": "browse",
            "time": "2017-04-27T01:34:13+0000",
            "email": "fredgarvin@gmail.com"
          },
          {
            "cID": "58d2fc99ac0c8117814d4e78",
            "_id": "59014a9608ab4e356ec0706a",
            "properties": {
              "title": "khaki pants",
              "url": "http://example.com/pants",
              "price": 19.99,
              "description": "awesome khaki pants"
            },
            "action": "browse",
            "time": "2017-04-27T01:37:13+0000",
            "email": "fredgarvin@gmail.com"
          }
        ]
      }
    ]
                   
  • NewerThan: Return records newer than the specified date.

    {$events.newerThan = '2020-08-19T21:36:13+0000'}

    NewerThan: Return records newer than 1 day in the past.

    {$events.newerThan = '-1 day'|date_format:'Y-m-d\TH:i:sO'}

    NewerThan:  Using the the Smarty utility, lastSendTimestamp, you are able to set a variable for the last send date of an Automation and populate the newerThan parameter.

    {$lastSend.templateKey = 'automation_key'}
    {$lastSend.date = $utils->lastSendTimestamp($lastSend.templateKey)}
    
    {$events.newerThan = $lastSend.date|date_format:'Y-m-d\TH:i:sO'}

    Properties: Return records by multiple specified values.

    {$events.properties = ['category'=>'shoes','brand'=>'nike']}

    Sort: Sort results by action timestamp in descending order.

    {$events.sort = ['column'=>'ats','direction'=>'DESC']}
  • Parameter Description Required Expected Default
    eventName The name of the event stored in the contactactivities collection. Required Valid event/contactactivity name NA
    newerThan Filters the event records returned based on the timestamp of the events. Optional Date string null
    properties Filters the event records returned based on a matching property value(s). Optional Array of property key/value pairs []
    limit Maximum number of records returned. Optional Integer, null 25
    sort Sort order of the returned records. Optional Array []

getJson

Data stored within an externally hosted JSON feed can be referenced and used within any message body.

  • Used in: Message Automations Data Automations
  • Syntax: {$utils->getJson($url*, $cacheMinutes, $options)}
  • Learn more about getJson
  • {$json_feed.url = 'http://p5.zdassets.com/hc/theme_assets/656597/200049057/automobiles.json'}
    {$json_feed.cacheMinutes = 10}
    {$json_feed.options = []}
    
    {$json_feed.data = $utils->getJson($json_feed.url, $json_feed.cacheMinutes, $json_feed.options)}
    
    {foreach $json_feed.data as $car}  
     <strong>{$car.brand|capitalize} {$car.model|capitalize}</strong><br>
       ${$car.price}<br>
      Mileage: {$car.mileage}<br><br>
    {/foreach}
    
    <h2>Debug $json_feed</h2>
    {$utils->jsonPrettyPrint($json_feed)}
  • Honda Pilot
    $33000
    Mileage: 100000
    View details

    Ford Explorer
    $34000
    Mileage: 39000
    View details

    Toyota Prius
    $27000
    Mileage: 66000
    View details

    Debug $json_feed
    {
      "url": "http://p5.zdassets.com/hc/theme_assets/656597/200049057/automobiles.json",
      "cacheMinutes": 10,
      "options": {
        "timeout": 1
      },
      "data": [
        {
          "model": "pilot",
          "brand": "honda",
          "price": 33000,
          "mileage": 100000,
          "id": "01"
        },
        {
          "model": "explorer",
          "brand": "ford",
          "price": 34000,
          "mileage": 39000,
          "id": "02"
        },
        {
          "model": "prius",
          "brand": "toyota",
          "price": 27000,
          "mileage": 66000,
          "id": "03"
        }
      ]
    }
  • Options: Setting HTTP request headers for authorization.

    {$json_feed.options = ['headers'=>['Authorization' => 'Basic <base64 encoded username:password>']]}

    Options: Setting the maximum wait time (cannot exceed 60 seconds).

    {$json_feed.options = ['timeout' => 1]}

    Options: Setting the limit on the number of records returned.

    {$json_feed.options = 3}
  • Parameter Description Required Expected Default
    url URL for the JSON resource. required valid URL NA
    cacheMinutes Number of minutes to store the feed data in memory. This optimizes send time if the system doesn't have to request the feed for every individual message. optional integer 10
    options Allows for the configuration of options such as HTTP request headers or maximum wait time. Can be used to limit the maximum number of records returned when only an integer is supplied. optional array or integer []

getMicroNow

Similar to the getNow utility, you can render the current time for a specified time zone, with the addition of microseconds.

  • Used in: Message Automations Data Automations
  • Syntax: {$utils->getMicroNow($tzId, $format)}
  • {$getMicroNow.tzId = 'UTC'}
    {$getMicroNow.format = 'U.u'}
    
    {$getMicroNow.data = $utils->getMicroNow($getMicroNow.tzId, $getMicroNow.format)}
    
    <strong>Time since Unix epoch with microseconds:</strong><br>
    {$getMicroNow.data}
    
    <h2>Debug $getMicroNow</h2>
    {$utils->jsonPrettyPrint($getMicroNow)}
  • Time since Unix epoch with microseconds:
    1590861373.977000

    Debug $getMicroNow
    {
        "tzId": "UTC",
        "format": "U.u",
        "data": "1590861373.977000"
    }
  • Parameter Description Required Expected Default
    tzId Specify the time zone identifier. Recognized time zone identifiers. optional valid time zone ID UTC
    format Returns a date string according to the given format. Available date format specifiers. optional string Y-m-d h:i:s

getNow

Using the getNow utility, you can render the current time for a specified time zone when the template is compiled.

  • {$getNow.tzId = 'America/Los_Angeles'}
    {$getNow.format = 'Y-m-d\TH:i:sO'}
    
    {$getNow.data = $utils->getNow($getNow.tzId, $getNow.format)}
    
    <strong>Curent time:</strong><br>
    {$getNow.data}
    
    <h2>Debug $getNow</h2>
    {$utils->jsonPrettyPrint($getNow)}
  • Current time:
    2020-04-27 13:30:57

    Debug $getNow
    {
        "tzId": "America\/Los_Angeles",
        "format": "Y-m-d\\TH:i:sO",
        "data": "2020-04-27 13:30:57"
    }
  • Rendering a copyright date in the footer of your email:

    {$getNow.tzId = $account.timezone}
    {$getNow.format = 'Y'}
    
    {$getNow.data = $utils->getNow($getNow.tzId, $getNow.format)}
    
    © {$getNow.data} Example Company

    The time zone can be a variable unique to each contact if you are storing the time zone as an attribute value. Learn how to set an attribute as the primary time zone.

    {$getNow.tzId = $contact.address.tz}
    {$getNow.format = 'Y-m-d\TH:i:sO'}
    
    {$getNow.data = $utils->getNow($getNow.tzId, $getNow.format)}
    
    Time unique to the contact: {$getNow.data}
  • Parameter Description Required Expected Default
    tzId Specify the time zone identifier. Recognized time zone identifiers. optional valid time zone ID UTC
    format Returns a date string according to the given format. Available date format specifiers. optional string Y-m-d h:i:s

getOrders

Data stored within the orders collection can be referenced and used within any message body.

  • {$orders.query = []}
    {$orders.limit = 1}
    {$orders.sort = []}

    {$orders.data = $utils->getOrders($orders.query, $orders.limit, $orders.sort)}

    {foreach $orders.data as $order}
    <b>OrderID {$order.orderID}</b><br>
    Purchase Date - {$order.purchaseDate|date_format}<br><br>
    {foreach $order.items as $orderitem}
    Product {$orderitem.productID}<br>
    {$orderitem.description|capitalize} - ${$orderitem.amount|string_format:'%.2f'}<br>
    Size - {$orderitem.attr.size}<br>
    Color - {$orderitem.attr.color}<br><br>
    {/foreach}
    Total Amount - ${$order.totalAmount}<br><br>
    Shipping Address:<br>
    {$order.shippingAddress.name|capitalize}<br>
    {$order.shippingAddress.address|capitalize}<br>
    {$order.shippingAddress.city|capitalize} {$order.shippingAddress.state|capitalize} {$order.shippingAddress.postalCode}<br><br>
    {/foreach}

    <h2>Debug $orders</h2>
    {$utils->jsonPrettyPrint($orders)}
  • OrderID 001
    Purchase Date - Jan 10, 2015

    Product 111
    Khaki Shorts - $19.99
    Size - large
    Color - tan

    Product 222
    Khaki Pants - $29.99
    Size - large
    Color - tan

    Total Amount - $49.98

    Shipping Address:
    Fred Garvin
    555 Truss St
    San Diego CA 92108

    Debug $orders
    [
      {
        "query": [],
        "limit": 1,
        "sort": [],
        "data": [
          {
            "cID": "58d2fc99ac0c8117814d4e78",
            "orderID": "001",
            "purchaseDate": "2015-01-10T01:47:43+0000",
            "shippingAddress": {
              "name": "fred garvin",
              "address": "555 truss St",
              "city": "san diego",
              "state": "ca",
              "postalCode": "92108",
              "country": "usa"
            },
            "billingAddress": {
              "name": "fred garvin",
              "address": "555 truss st",
              "city": "san diego",
              "state": "ca",
              "postalCode": "92108",
              "country": "usa"
            },
            "items": [
              {
                "productID": "111",
                "description": "khaki shorts",
                "sku": "1212",
                "category": "shorts",
                "name": "khaki shorts",
                "qty": 1,
                "itemPrice": 19.99,
                "amount": 19.99,
                "attr": {
                  "color": "tan",
                  "size": "large"
                }
              },
              {
                "productID": "222",
                "description": "khaki pants",
                "sku": "1213",
                "category": "pants",
                "name": "khaki pants",
                "qty": 1,
                "itemPrice": 29.99,
                "amount": 29.99,
                "attr": {
                  "color": "tan",
                  "size": "large"
                }
              }
            ],
            "tax": 0,
            "totalAmount": 49.98
          }
        ]
      }
    ]
  • Query: Return records filtered by a specified value.

    {$orders.query = ['orderID"=>'002']}

    Query:  Return records filtered by a value within an order item.

    {$orders.query = ['items'=>['productID'=>'111']]}

    Query: Return records by multiple specified values.

    {$orders.query = ['purchaseDate'=>['gt'=>'2016-01-09'],'shippingAddress.city'=>'san diego']}

    Sort: Sort results by order ID in descending order.

    {$orders.sort = ['column'=>orderID,'direction'=>'DESC']}
  • Parameter Description Required Expected Default
    query A filter used to limit the data set. Optional Array []
    limit A filter that sets a maximum number of records to return. Optional Integer 25
    sort Sort order of the returned records. Optional Array []

getProducts

Data stored within the products collection can be referenced and used within any message body.

  • Used in: Message Automations Data Automations
  • Syntax: {$utils->getProducts($query, $limit, $sort, $cacheMinutes)}
  • Learn more about getProducts
  • {$products.query = []}
    {$products.limit = 2}
    {$products.sort = []}
    {$products.cacheMinutes = 20}
    
    {$products.data = $utils->getProducts($products.query, $products.limit, $products.sort, $products.cacheMinutes)}
    
    {foreach $products.data as $product}  
      <strong>{$product.productName|capitalize}</strong> - ${$product.price}<br><br>
      {foreach $product.variants as $variant}
        Color: {$variant.attr.color}<br>
        Size: {$variant.attr.size}<br>
        Sku: {$variant.sku}<br><br>
      {/foreach}
    {/foreach}
    
    <h2>Debug $products</h2>
    {$utils->jsonPrettyPrint($products)}
  • Skirt - $19.99

    Color: blue
    Size: small
    Sku: 111

    Color: blue
    Size: medium
    Sku: 112

    Shorts - $29.99

    Color: green
    Size: small
    Sku: 221

    Color: green
    Size: medium
    Sku: 222

    Debug $products
    [
      {
        "query": [],
        "limit": 2,
        "sort": [],
        "cacheMinutes": 20,
        "data": [
          {
            "productID": "1172",
            "productName": "skirt",
            "price": 19.99,
            "variants": [
              {
                "sku": "111",
                "attr": {
                  "color": "blue",
                  "size": "small"
                }
              },
              {
                "sku": "112",
                "attr": {
                  "color": "blue",
                  "size": "medium"
                }
              }
            ]
          },
          {
            "productID": "1173",
            "productName": "shorts",
            "price": 29.99,
            "variants": [
              {
                "sku": "221",
                "attr": {
                  "color": "green",
                  "size": "small"
                }
              },
              {
                "sku": "222",
                "attr": {
                  "color": "green",
                  "size": "medium"
                }
              }
            ]
          }
        ]
      }
    ]
  • Query: Return records filtered by values between two numbers.

    {$products.query = ['price'=>['between'=>['start'=>10,'end'=>30]]]}

    Query: Return records filtered by multiple specified values of the same key.

    {$products.query = ['productID'=>['in' => [123,1234]]]}

    Query: Return records that are not in the specified array.

    {$products.query = ['productID'=>['notIn' => [123,1234]]]}

    Query: Return records filtered by comparison operators (lt, gt, gte).

    {$products.query = ['price'=>['lt'=>39]]}

    Sort: Sort results by price in descending order.

    {$products.sort = ['column'=>'price','direction'=>'DESC']}
  • Parameter Description Required Expected Default
    query A filter used to limit the data set. Optional Array []
    limit A filter that sets a maximum number of records to return. Optional Integer 25
    sort Sort order of the returned records. Optional Array []
    cacheMinutes Number of minutes to store the feed data in memory. This optimizes send time if the system doesn't have to request the feed for every individual message. Optional Integer 0

getRaw

The getRaw utility allows you to retrieve unfiltered HTML from a file on an external server. The retrieved content is unprocessed and can be inserted anywhere in your message body. Can be used to include content such as product recommendations.

  • Used in: Message Automations Data Automations
  • Syntax: {$supplements->getRaw($url*, $cacheMinutes)}
  • {$raw.url = 'https://example.com/55788/sunglasses.htm'}
    {$raw.cacheMinutes = 20}
    
    {$raw.data = $supplements->getRaw($raw.url, $raw.cacheMinutes)}
    
    <h2>Display HTML:</h2>
    {$raw.data}
  • This is the raw HTML within the sunglasses.htm file.

    <table width="579" cellspacing="0" cellpadding="0" border="0" align="center">
    <tbody>
    <tr>
    <td style="font-family: arial, san-serif; text-align: center; padding: 10px; color: #666; font-size: 14px; line-height: 22px;">QUAY AUSTRALIA<br>Retro and modern influences merge seamlessly on lightweight sunglasses featuring tortoiseshell frames and flashy mirrored lenses.
    </td>
    <td><img src="https://example.com/files/products/3467238.jpg"></td></tr></tbody></table>
  • Display HTML:
    QUAY AUSTRALIA
    Retro and modern influences merge seamlessly on lightweight sunglasses featuring tortoiseshell frames and flashy mirrored lenses.
  • Parameter Description Required Expected Default
    url URL for the HTML resource. required valid URL NA
    cacheMinutes Number of minutes to store the retrieved data in memory. This optimizes send time if the system doesn't have to request the data for every individual message. optional integer 10

getSessionStore

Returns data stored in a previous action for use in the current action within a Podium orchestration.

This utility is only available in Podium orchestrations.

  • Used in: Message Automations Data Automations
  • Syntax: {$data = $utils->getSessionStore()}
  • {$coupon = '12345'}
    <h1>{$coupon}</h1>
    {$utils->updateSessionStore($coupon)}

    {$coupon = $utils->getSessionStore()} <h1>{$coupon}</h1>

    Here is your coupon code: <strong>{$coupon.code}</strong>
  • Here is your coupon code: 12345
  • Parameter Description Required Expected Default
    key A unique key created by the user for a stored session.   required String  N/A 
    filteroptions A filter used to query session records by date. Only indexed fields can be queried.  optional Array  [] 

getSimpleXML

Data stored within an externally hosted XML feed can be referenced and used within any message body.

  • {$xml.url = 'http://p13.zdassets.com/hc/theme_assets/656597/200049057/simpleXML_example_1.xml'}
    {$xml.cacheMinutes = 20}
    
    {$xml.data = $utils->getSimpleXML($xml.url, $xml.cacheMinutes)}
    
    <h1>{$xml.data->channel->title}</h1>
    {foreach $xml.data->channel->item as $record}
      <h2>{$record->title}</h2>
      {$record->link}<br>
      {$record->description}<br><br>
    {/foreach}
  • <rss version="2.0">
    <channel>
    <title>Classic Albums</title>
    <link>https://www.example.com</link>
    <description>A list of classic albums.</description>
    <item>
    <title>Fleetwood Mac - Rumours</title>
    <link>http://fleetwoodmac.com</link>
    <description>Rumours tends to be remembered as the album that was characterized by personal strife between the band members.</description>
    </item>
    <item>
    <title>Pink Floyd - Dark Side of the Moon</title>
    <link>http://www.pinkfloyd.com/</link>
    <description>No-one in March 1973 could have imagined that an album released in that month would still be thrilling listeners 38 years later, but it's true. </description>
    </item>
    </channel>
    </rss>
  • Classic Albums

    Fleetwood Mac: Rumours

    http://fleetwoodmac.com
    Rumours tends to be remembered as the album that was characterized by personal strife between the band members.

    Pink Floyd: Dark Side of the Moon

    http://www.pinkfloyd.com/
    No one in March 1973 could have imagined that an album released that month would still be thrilling listeners thirty-eight years later, but it's true.
  • Parameter Description Required Expected Default
    url URL for the XML resource. required valid URL NA
    cacheMinutes Number of minutes to store the feed data in memory. This optimizes send time if the system doesn't have to request the feed for every individual message. optional integer 0

getSupplementRecords

Data stored within a supplement can be referenced and used within any message body.

  • {$supplement_records.key = 'automobiles'}
    {$supplement_records.query = []}
    {$supplement_records.limit = 25}
    {$supplement_records.sort = []}
    {$supplement_records.cacheMinutes = 25}
    
    {$supplement_records.data = $utils->getSupplementRecords($supplement_records.key, $supplement_records.query, $supplement_records.limit, $supplement_records.sort, $supplement_records.cacheMinutes)}
    
    {foreach $supplement_records.data as $car}  
      <strong>{$car.brand|capitalize} {$car.model|capitalize}</strong><br>
      ${$car.price}<br>
      Mileage: {$car.mileage}<br><br>
    {/foreach}
    
    <h2>Debug $supplement_records</h2>
    {$utils->jsonPrettyPrint($supplement_records)}
  • Honda Pilot
    $33000
    Mileage: 100000
    View details

    Ford Explorer
    $34000
    Mileage: 39000
    View details

    Debug $supplement_records
    [
      {
        "key": "automobiles",
        "query": [],
        "limit": 25,
        "sort": [],
        "cacheMinutes": 25,
        "data": [
          {
            "model": "pilot",
            "brand": "honda",
            "price": "33000",
            "milage": "100000",
            "ct": "2020-04-15T04:32:49+0000",
            "lm": "2020-04-15T04:32:49+0000",
            "id": "1"
          },
          {
            "model": "explorer",
            "brand": "ford",
            "price": "34000",
            "milage": "39000",
            "ct": "2020-04-15T04:32:49+0000",
            "lm": "2020-04-15T04:32:49+0000",
            "id": "2"
          }
        ]
      }
    ]
  • Query: Return records filtered by values between two numbers.

    {$supplement_records.query = ['price'=>['between'=>['start'=>10000,'end'=>50000]]]}

    Query: Return records filtered by values between two dates.

    {$supplement_records.query = ['date'=>['lt'=>{$smarty.now|date_format:'%Y-%m-%dT%H:%M:%S+0000'}],'date'=>['gt'=>{'2020-10-10T22:21:18+0000'}]]}

    Query: Return records that are not in the specified array.

    {$supplement_records.query = ['brand'=>['notIn' => [toyota,honda]]]}

    Query: Return records where the color black is contained in the array with the key of colors:

    {$supplement_records.query = ['colors' => ['array_contains' => 'black']]}

    Sort: Last modified in descending order.

    {$supplement_records.sort = ['column'=>'lm','direction'=>'DESC']}
  • Parameter Description Required Expected Default
    key A unique key created by the user for a stored supplement. Required Valid key NA
    query A filter used to limit the data set. Only indexed fields can be queried. Optional Array []
    limit A filter that sets a maximum number of records to return. Optional Integer 25
    sort Sort order of the returned records. ASC (ascending), DESC (descending), LM (last modified), CT (created). Optional Array []
    cacheMinutes Number of minutes to store the feed data in memory. This optimizes send time if the system doesn't have to request the feed for every individual message. Optional Integer 0

jsonPrettyPrint

You can use the jsonPrettyPrint Smarty utility to view all data available from the get methods within the message preview.

For example, you can retrieve all product data in message preview by pasting the following code in the HTML editor and clicking the Preview button.

  • Used in: Message Automations Data Automations
  • Syntax: {$utils->jsonPrettyPrint($object*)}
  • {$products=$utils->getProducts()} 
    {$utils->jsonPrettyPrint($products)}
    
  • [
      {
        "_id": "5668084929aa544d754bd640",
        "productID": "09990",
        "productName": "Shirts for Men",
        "productType": "physical",
        "manufacturerName": "Cordial Threads",
        "accountID": "45",
        "lm": "2015-12-09T10:54:01+0000",
        "ct": "2015-12-09T10:54:01+0000"
      },
      {
        "_id": "56b2fb56733462ca89f52f3c",
        "productID": "TB111",
        "category": "Performance Wear",
        "productName": "Adult Medium Cut Brief",
        "price": 16.66,
        "variants": [
          {
            "sku": "TB111",
            "attr": ""
          }
        ],
        "accountID": "45",
        "lm": "2016-02-04T07:18:46+0000",
        "ct": "2016-02-04T07:18:46+0000"
      }
    ]

This will work for all data utilities, as well as retrieving contact attribute data.

lastSendTimestamp

The lastSendTimestamp utility allows you to render the last send date of a specified automation template.

  • {$lastSend.templateKey = 'order-confirmation'}
    
    {$lastSend.date = $utils->lastSendTimestamp($lastSend.templateKey)}
    
    Message last sent: {$lastSend.date|date_format:'Y-m-d\TH:i:sO'};
  • Message last sent: 2020-04-27T22:17:58+0000
  • Parameter Description Required Expected Default
    templateKey A unique automation template key. required Valid automation template key NA

postJSON

Data stored within an externally hosted server can be updated using postJSON.

  • Used in: Message Automations Data Automations
  • Syntax: {$utils->postJson($url*, $payload*, $options)}
  • Learn more about postJSON
  • {$result = $utils->postJson('https://postman-echo.com/post', [
    "firstName" => 'John',
    "lastName" => 'Smith',
    'email' => 'jsmith@gmail.com',
    'id' => 101],
    ['headers'=>['Authorization' => 'Basic Y29yZGlhbF9zYXlzOmhlbGxv'],
    'timeout' => 6, "cacheMinutes" => 10])}
    {$utils->jsonPrettyPrint($result)}
  • {
        "statusCode": 200,
        "headers": {
            "Date": [
                "Tue, 26 Apr 2022 12:22:35 GMT"
            ],
            "Content-Type": [
                "application\/json; charset=utf-8"
            ],
            "Content-Length": [
                "525"
            ],
            "Connection": [
                "keep-alive"
            ],
            "ETag": [
                "W\/\"20d-+gcDrs5d958cxHuybRpToiFbjew\""
            ],
            "Vary": [
                "Accept-Encoding"
            ],
            "set-cookie": [
                "sails.sid=s%3AI1ab0jhxbf6Hgt-elkujWi01RPVGKUC7.giirYI%2BWP2N9635pAbOIad0AbWLmCBwIERRe6eIYM80; Path=\/; HttpOnly"
            ]
        },
        "data": {
            "args": [],
            "data": {
                "firstName": "John",
                "lastName": "Smith",
                "email": "jsmith@gmail.com",
                "id": 101
            },
            "files": [],
            "form": [],
            "headers": {
                "x-forwarded-proto": "https",
                "x-forwarded-port": "443",
                "host": "postman-echo.com",
                "x-amzn-trace-id": "Root=1-6267e40b-4acf40691c406ac61c60214e",
                "content-length": "75",
                "authorization": "Basic Y29yZGlhbF9zYXlzOmhlbGxv",
                "content-type": "application\/json",
                "user-agent": "Cordial Platform"
            },
            "json": {
                "firstName": "John",
                "lastName": "Smith",
                "email": "jsmith@gmail.com",
                "id": 101
            },
            "url": "https:\/\/postman-echo.com\/post"
        },
        "error": null
    }
    
  • Parameter

    Description

    Required

    Expected

    Default

    url

    URL for the externally hosted endpoint

    required

    valid URL

    NA

    payload

    payload for the request containing the data update

    required

    an array of key/values pairs

    NA

    options

    Allows for the configuration of options such as HTTP request headers or maximum wait time.

    optional

    an array of key/values pairs

    []

putJSON

Data stored within an externally hosted server can be updated using putJSON.

  • Used in: Message Automations Data Automations
  • Syntax: {$utils->putJson($url*, $payload*, $options)}
  • Learn more about putJSON
  • {$result = $utils->putJson('https://postman-echo.com/post', [
    "firstName" => 'John',
    "lastName" => 'Smith',
    'email' => 'jsmith@gmail.com',
    'id' => 101],
    ['headers'=>['Authorization' => 'Basic Y29yZGlhbF9zYXlzOmhlbGxv'],
    'timeout' => 6, "cacheMinutes" => 10])}
    {$utils->jsonPrettyPrint($result)}
  • {
        "statusCode": 200,
        "headers": {
            "Date": [
                "Tue, 26 Apr 2022 12:22:35 GMT"
            ],
            "Content-Type": [
                "application\/json; charset=utf-8"
            ],
            "Content-Length": [
                "525"
            ],
            "Connection": [
                "keep-alive"
            ],
            "ETag": [
                "W\/\"20d-+gcDrs5d958cxHuybRpToiFbjew\""
            ],
            "Vary": [
                "Accept-Encoding"
            ],
            "set-cookie": [
                "sails.sid=s%3AI1ab0jhxbf6Hgt-elkujWi01RPVGKUC7.giirYI%2BWP2N9635pAbOIad0AbWLmCBwIERRe6eIYM80; Path=\/; HttpOnly"
            ]
        },
        "data": {
            "args": [],
            "data": {
                "firstName": "John",
                "lastName": "Smith",
                "email": "jsmith@gmail.com",
                "id": 101
            },
            "files": [],
            "form": [],
            "headers": {
                "x-forwarded-proto": "https",
                "x-forwarded-port": "443",
                "host": "postman-echo.com",
                "x-amzn-trace-id": "Root=1-6267e40b-4acf40691c406ac61c60214e",
                "content-length": "75",
                "authorization": "Basic Y29yZGlhbF9zYXlzOmhlbGxv",
                "content-type": "application\/json",
                "user-agent": "Cordial Platform"
            },
            "json": {
                "firstName": "John",
                "lastName": "Smith",
                "email": "jsmith@gmail.com",
                "id": 101
            },
            "url": "https:\/\/postman-echo.com\/post"
        },
        "error": null
    }
  • Parameter

    Description

    Required

    Expected

    Default

    url

    URL for the externally hosted endpoint

    required

    valid URL

    NA

    payload

    payload for the request containing the data update

    required

    an array of key/values pairs

    NA

    options

    Allows for the configuration of options such as HTTP request headers or maximum wait time.

    optional

    an array of key/values pairs

    []

renderInfo

A utility that renders automation metadata. Useful for setting conditional statements based on the rendering engine in use. Allows for execution of automation scripts that are reusable across message and data automations. The metadata object contains the automation name (Message Automation or Data Automation) and preview (true or false) key-value pairs.

  • Used in: Message Automations Data Automations
  • Syntax: {$utils->renderInfo()}
  • {$metadata = $utils->renderInfo()}
    <h2>Debug $metadata</h2> {$utils->jsonPrettyPrint($metadata)}
  • Debug $metadata
    {
        "name": "Data Automation",
        "preview": true
    }
  • An example of executing the stopMessage Smarty function in a Message Automation and otherwise returning information text if the script is ran in a Data Automation, where stopMessage is not supported.

    {$data.metadata = $utils->renderInfo()}
    
    {if $data.metadata.name == 'Message Automation'}
      {$data.info[] = 'We are in Message Automation, stopMessage can run'}
      {if $contact.city == 'San Diego'}{stopMessage}{/if}
    {else}
      {$data.info[] = 'We are in Data Automation, stopMessage can NOT run'}
    {/if}
    
    {if $data.metadata.name == 'Message Automation' and $data.metadata.preview == true}
      <h2>Debug $data</h2>
      {$utils->jsonPrettyPrint($data)}
    {elseif $data.metadata.name == 'Data Automation' and $data.metadata.preview == true}
      <h2>Debug $data</h2>
      {$utils->jsonPrettyPrint($data)}
    {/if}
    Debug $data:
    {
      "metadata": {
        "name": "Data Automation",
        "preview": true
      },
      "info": [
        "We are in Data Automation, stopMessage can NOT run"
      ]
    }

setContact

Sets a contact object for which the transformation is to be carried out. Once set, the contact object is accessible to utilities and Smarty functions that rely on contact data for the remainder of the transformation. Subsequent instances of setContact will unset the preceding contact object, allowing for execution of consecutive context-sensitive and contact-dependent transformations. Also useful for providing the cID value when targeting contact data using utilities such as updateSupplementRecord.

  • Used in:    Message Automations   Data Automations
  • Syntax: {$utils->setContact($lookup_key*)}
  • {$contact = $utils->setContact('email:msmith@example.com')}
    {* Contact object is msmith@example.com for the followng context *}
    {$mdtKey = 'messageKey'} {$order = [..list of attributes..]} {if !empty($contact)} {$utils->sendMessage($mdtKey)} {$utils->upsertOrder($order)} {/if} {$contact = $utils->setContact('cID:58d2fc99ac0c8117814d4e78')}
    {* Contact object has been changed to 58d2fc99ac0c8117814d4e78 for the followng context *}
    {if !empty($contact)} {$utils->sendMessage($mdtKey)} {$utils->upsertOrder($order)} {/if}
  • Parameter Description Required Expected Default
    lookup_key A valid primary or secondary contact identifier key/value pair - email:msmith@example.com, cID:58d2fc99ac0c8117814d4e78, custID:idValue. required String NA

sortArray

Cordial provides a custom Smarty utility to sort an array of data in a message. This is useful if you need to sort an array of data after it is retrieved using a "get" method.

The example below shows the sortArray utility in conjunction with the getJson utility to sort the list of cars by price in ascending order.

  • Used in:   Message Automations   Data Automations
  • Syntax: {$utils->sortArray($arrayName, $column_name, $sort)}
  • Learn more about sortArray
  • {$json_feed.data = $utils->getJson('http://p5.zdassets.com/hc/theme_assets/656597/200049057/automobiles.json')}
    
    {$sorted = $utils->sortArray($json_feed.data, 'price', 'asc')}
    {foreach $sorted as $car} <strong>{$car.brand|capitalize} {$car.model|capitalize}</strong> ${$car.price}<br> Mileage: {$car.mileage}<br> ID: {$car.id}<br><br> {/foreach}
  • [
      {
        "model": "prius",
        "brand": "toyota",
        "price": 27000,
        "mileage": 66000,
        "id": "03"
      },
      {
        "model": "versa",
        "brand": "nissan",
        "price": 16000,
        "mileage": 94000,
        "id": "05"
      },
      {
        "model": "accord",
        "brand": "honda",
        "price": 24000,
        "mileage": 49000,
        "id": "07"
      }
    ]
  • Nissan Versa
    $16000
    Mileage: 94000
    ID: 05

    Honda Accord
    $24000
    Mileage: 49000
    ID: 07

    Toyota Prius
    $27000
    Mileage: 66000
    ID: 03
  • Parameter Description Required Expected Default
    arrayName Name of the array to be sorted.  required String  NA 
    column_name Data column name by which to sort.  required  String  NA
    sort Sort the order of the records returned. ASC (ascending) or DESC (descending). optional Sort direction ASC 

strContains

The strContains utility can be used to find a string of characters within another string of characters.

Our example uses the utility to check if fire exists in firestorm, and then prints the result with an {if} statement.

  • Used in: Message Automations Data Automations
  • Syntax: {$utils->strContains($lookup_str*, $string*, $caseSensitive)}
  • Learn more about strContains
  • {$contains.lookup_str = 'Fire'}
    {$contains.string = 'firestorm'}
    {$contains.caseSensitive = true}
    
    {if $utils->strContains($contains.lookup_str, $contains.string, $contains.caseSensitive)}
      {$contains.found = true}
    {else}
      {$contains.found = false}
    {/if}
    
    {$utils->jsonPrettyPrint($contains)}
  • {
      "lookup_str": "Fire",
      "caseSensitive": true,
      "found": false
    }
  • Parameter Description Required Expected Default
    lookup_str String of characters to be searched for. required   String NA 
    string Given string to be checked for the specified lookup_str. required  String  NA 
    caseSensitive Determines if the search should adhere to letter casing (true or false). optional Boolean string true

updateContact

Updates an existing contact record in the Cordial database using the supplied data. Cannot be used to create new contact records. In this example, we are using the setContact utility to look up an existing contact record and then pass update data using the updateContact utility.

  • Used in: Message Automations Data Automations
  • Syntax: {$utils->updateContact($data*, $waitForResult, $suppressTriggers, $forceSubscribe)}
  • {$lookup_key = 'email:msmith@example.com'}
    {$contactRecord = $utils->setContact($lookup_key)}
    {$updateRecord.data = ['last_name'=>'Smith', 'age' => ['inc' =>'+1']]}
    {$updateRecord.waitForResult = true}
    {$updateRecord.suppressTriggers = true}
    {$updateRecord.forceSubscribe = false}
    {if !empty($contactRecord)}
    {$contactRecord = $utils->updateContact($updateRecord.data, $updateRecord.waitForResult, $updateRecord.suppressTriggers, $updateRecord.forceSubscribe)} {/if}

    Contact Age: {$contact.age}<br>
    Last Name: {$contact.last_name}

    <h2>Debug $updateRecord</h2>
    {$utils->jsonPrettyPrint($updateRecord)}
  • Contact Age: 46
    Last Name: Smith

    Debug $updateContact
    {
        "data": {
            "last_name": "Smith",
            "age": {
                "inc": "+1"
            }
        },
        "waitForResult": true,
        "suppressTriggers": true,
    "forceSubscribe": false }
  • An example of using the forceSubscribe parameter to update an existing contact's channel subscribe status from unsubscribed to subscribed. Note that the channel key for SMS and push channels will vary depending on your account configuration.
    {$lookup_key = 'email:msmith@example.com'}
    {$contactRecord = $utils->setContact($lookup_key)}
    
    {$channelKey = 'email'}
    {$subscribeStatus = 'subscribed'}
    
    {$updateRecord.waitForResult = true} 
    {$updateRecord.suppressTriggers = true}
    {$updateRecord.forceSubscribe = true}
    
    {$contactRecord = $utils->updateContact(["channels.$channelKey.subscribeStatus" => $subscribeStatus], $updateRecord.waitForResult, $updateRecord.suppressTriggers, $updateRecord.forceSubscribe)}

    Updated Contact:

    {$utils->jsonPrettyPrint($contactRecord)}
    The following example demonstrates looking up contacts who performed a click event 1 day in the past, retrieves the click date, and updates the lastClick contact attribute.
    {$clickEvents.eventName = 'click'}
    {$clickEvents.newerThan = '-600 days'|date_format:'%Y-%m-%dT%H:%M:%S+0000'}
    {$clickEvents.properties = []}
    {$clickEvents.limit = 1}
    {$clickEvents.sort = ['column'=>'ats','direction'=>'DESC']}
    {$clickEvents.data = $utils->getEventRecords($clickEvents.eventName, $clickEvents.newerThan, $clickEvents.properties, $clickEvents.limit, $clickEvents.sort)}{$write.data.lastClick = $clickEvents.data.0.ats}

    {if not empty($write.data.lastClick)}
    {* We have new data to write *}
    {$write.data.channels.email.address = $contact.channels.email.address} {* need to set Primary Key *}
    {$write.data.lastetldate = $utils->getNow('UTC', 'Y-m-d\TH:i:sO')} {* remember the last time We ETLed this record *}

    {if not $block_update}
    {$write.waitForResults = true}
    {$write.suppressTriggers = true}
    {$result_of_write = $utils->updateContact($write.data, $write.waitForResults, $write.suppressTriggers)}
    {/if}
    {/if}

    {if $debug}
    <h2>Debug $write</h2>
    {$utils->jsonPrettyPrint($write)}
    <h2>Debug $clickEvents</h2>
    {$utils->jsonPrettyPrint($clickEvents)}
    <h2>Debug $contact</h2>
    {$utils->jsonPrettyPrint($contact)}
    {/if}
  • Parameter Description Required Expected Default
    data Contact data to be updated including attribute values and list associations. required Array NA
    waitForResult If true, will wait on the preceding contact update operation to complete before moving to the next line of Smarty. Typically set to true when subsequent Smarty functions require the newly created contact identifier value for successful execution. optional Boolean string false
    suppressTriggers If true, will suppress any triggered messages set to fire based on updates to values in the import. Defaults to true. optional Boolean string true
    forceSubscribe If set to true, will allow previously unsubscribed contacts to be updated as subscribed. Defaults to false. optional Boolean string false

updateSupplementRecord

Updates an existing supplement record within the specified supplement collection.

When updating a contact attribute supplement record, you can use the setContact utility as a way to provide the required contact ID (cID) value.

  • {$supplement.key = 'automobiles'}
    {$supplement.writeData.id = 2}
    {$supplement.writeData.price = '36000'}
    {$supplement.writeData.milage = '100'}
    {$supplement.writeData.model = 'explorer'}
    {$supplement.writeData.brand = 'ford'} {$supplement.automobiles = $supplements->updateSupplementRecord($supplement.key, $supplement.writeData)} <h2>Debug $supplement</h2> {$utils->jsonPrettyPrint($supplement)}
  • This is our existing supplement record within the automobiles collection before the update. We are updating the price and milage field key values.

    [
    { "model": "explorer", "brand": "ford", "price": "34000", "milage": "39000", "ct": "2020-04-15T04:32:49+0000", "lm": "2020-04-15T04:32:49+0000", "id": "2" }
    ]
  • {
        "key": "automobiles",
        "writeData": {
            "id": 2,
            "price": "36000",
            "milage": "100"
        },
        "automobiles": {
            "_id": "2",
            "model": "explorer",
            "brand": "ford",
            "price": "36000",
            "milage": "100",
            "ct": "2020-04-15T04:32:49+0000",
            "lm": "2020-06-15T21:26:48+0000",
            "_action": "updated"
        }
    }
  • Parameters Description Required Expected Default
    supplementKey A unique supplement collection identifier. Required String NA
    data An array of supplement record field key/value pairs. Required Array NA

Data automations only

addEvent

Adds a custom event to the events data collection and associates it to specific contact(s).

  • Used in: Data Automations
  • Syntax: {$utils->addEvent($a*, $UID, $contact_identifier*, $ats, $properties)}
  • {$event=$utils->addEvent([
        'a' => 'browse', 
        'UID' => '', 
        'email' => 'msmith@example.com', 
        'ats' => '2018-12-18T17:50:25+0000',
        'properties' => [
            'category' => 'Shirts',
            'url' => 'http://example.com/shirts',
            'description' => 'A really cool khaki shirt.',
            'price' => 9.99,
            'title' => 'Khaki Shirt'
        ]
    ])}; 
    
    <h2>Debug $event</h2>
    {$utils->jsonPrettyPrint($event)}
  • Debug $event
    {
        "success": true,
        "messages": "created"
    }
  • Parameter Description Required Expected Default
    a Defines an action such as open, click, or any other custom action. The maximum length of the parameter is 40 characters. required String NA
    UID Unique event identifier. If undefined, a value will automatically be generated. optional String NA
    contact_identifier Unique primary or secondary contact identifier key/value pair to look up and reference the contact. required String NA
    ats Action occurrence timestamp. If undefined, the current date and time will be used. Date format is ISO 8601 standard. optional String current time
    properties An object of additional event attributes.
    Note that property keys consisting of numeric-only values (e.g. 57) or keys containing a "dot" (e.g. shoes.color) will be stripped.
    optional Object NA

addExportRecord

Used to add a record to one or more of the pre-initialized export files (via UI). Dynamically build a collection of data records that will be processed in the data transformation and exported to the target file. Multiple instances of addExportRecord can be added to a single transformation to add data rows at varying states of the transformation or to create separate export files using unique file identifiers.

  • Used in: Data Automations
  • Syntax: {$utils->addExportRecord($file_identifier*, $row*)}
  • {$supplement_records.key = 'automobiles'}
    {$supplement_records.data = $utils->getSupplementRecords($supplement_records.key)}
    
    {foreach $supplement_records.data as $car}  
    {$export_record.file_identifier = 'CoolCarsExport'}
    {$utils->addExportRecord($export_record.file_identifier, ['brand' => $car.brand, 'price' => $car.price])}
    {/foreach}
    
    {$products.query = ['productID'=>['in' => [123,1234]]]}
    {$products.data = $utils->getProducts($products.query)}
    
    {foreach $products.data as $product}  
    {$export_record.file_identifier = 'CoolProductsExport'}
    {$utils->addExportRecord($export_record.file_identifier, ['product name' => $product.productName, 'product price' => $product.productID])}
    {/foreach}
  • This example generates two CSV files with Local download as the file destination (previously set in our Data Job settings via the UI). The source of data is internal supplement and product data. After the script is run, the files can be downloaded from the Jobs page in Cordial. Additional file destinations include FTP, SFTP, and Amazon S3.

    More advanced use cases carry out data transformations on loaded data, using addExportRecord to add export file data rows.

  • {* debug flag(s) *}
    {* set value to 0 when ready to go live *}
    {$block_update = 1} 
    
    {* get metadata about this automation *}
    {$data.metadata = $utils->renderInfo()}
    
    {* settings *}
    {$export.file_identifier = 'my_export_name'}
    
    {* data transformation *}
    {foreach $contact as $attr => $value}
      {* now, we build up a data record to export; can perform transformations in this codeblock *}
      {$export.data[$attr] = $value}
    {/foreach}
    
    {* add row to export *}
    {if not $block_update and not empty($export.data)}
      {$utils->addExportRecord($export_record.file_identifier, $export.data)}}  
    {/if}
    
    {* debug output *}
    {if $data.metadata.preview}
      <h2>Debug <code>$contact</code></h2>
      {$utils->jsonPrettyPrint($contact)}
      <h2>Debug <code>$export.data</code></h2>
      {$utils->jsonPrettyPrint($export.data)}
    {/if}
  • Parameter Description Required Expected Default
    file_identifier Export file identifier (Export name field from the Data Mapping UI). required String NA
    row Object of data to insert as a row into the export file. required Object NA

createTmpSupplementVersion

Creates an empty, structurally identical copy of an existing supplement collection. The temporary version inherits the name, options, and index fields of the original, making it fully compatible to accept the same data types.

The createTmpSupplementVersion utility should only be used within the pre job script. It is also always used in conjunction with replaceTmpSupplementVersion utility in post job script of the same data transformation.

  • {* in preview mode createTmpSupplementVersion does not run *}
    {$utils->createTmpSupplementVersion('existing_collection_name')}
    

deleteTmpSupplementVersion

This utility provides the means for clearing temporary supplement collection data in the event of a critical swap supplement data job failure. There are only a handful of instances when this utility should be used and always with consultation from the Cordial Solutions Engineering team.

Please only run deleteTmpSupplementVersion under the guidance of a Solutions Engineer. There are very few instances where this would ever be needed in production, as it will clear out the unused tmp collection.

  • {* If running deleteTmpSupplementVersion, it should be the only line of code in the script *}
    {$utils->deleteTmpSupplementVersion('existing_collection_name')}
    

generateUUID4

Generates a random universally unique identifier using UUID4 standards. Can be used to assign unique data record identifiers during data transformations, imports, and exports.

  • Used in: Data Automations
  • Syntax: {$utils->generateUUID4()}
  • {$uuid = $utils->generateUUID4()}
    
    <h2>Random UUID:</h2><br>
    {$uuid}
  • Random UUID:
    86f556b0-7882-48ef-8f09-5b735066e856

getContactByDeviceToken

Checks if an existing contact record already contains the provided mobile push device token. When importing mobile push contacts, it can be used in conjunction with other Smarty utilities and functions. For example, if the token already exists, you could choose to skip that record or perform a number of updates on that record.

  • Used in: Data Automations
  • Syntax: {$utils->getContactByDeviceToken($channelKey, $token)}

The mobile push channel key may differ depending on your account configuration.

  • {$mobileContact = $utils->getContactByDeviceToken('push', 'do4-_NCZRbiKTo_l-8jVKy...')}
    
    {if $mobileContact}
    Contact record with this token exists.<br><br>
    <h2>Contact record:</h2>
    {$utils->jsonPrettyPrint($mobileContact)}
    {else}
    No contact records contain this token.
    {/if}
    
  • Contact record with this token exists.

    Contact record:
    {
      "_id": "541137c785a750ffef7500999",
      "channels": {
        "email": {
          "address": "msmith@example.com",
          "subscribeStatus": "subscribed",
          "subscribedAt": "2020-01-06T18:29:12+0000",
          "unsubscribedAt": ""
        }
      },
      "push": {
        "address": {
          "5c98d21q-b3o8-42bc-9dac-e9d3c00e34e1": {
            "app": "1.0.0-MobileApp",
            "os": "android",
            "pushEnabled": true,
            "sdk": "1.0",
            "token": "do4-_NCZRbiKTo_l-8jVKy...",
            "v": "10"
          },
          "createdAt": "2020-01-06T18:29:12+0000",
          "lastModified": "2020-01-08T15:24:01+0000",
          "cID": "541137c785a750ffef7500999",
          "id": "541137c785a750ffef7500999"
        }
      }
    }
  • Parameter Description Required Expected Default
    $channelKey Mobile push channel key. required String NA
    $token APNS (Apple) or FCM (Android) issued device token. required String NA

mergeContacts

The mergeContacts utility allows you to merge a source contact into a destination contact while choosing which data is kept.

  • Used in: Data Automations
  • Syntax: {$utils->mergeContacts($sourceContactCID, $destinationContactCID, $options)}
  • {*
    Trigger Data:
    - Event = crdl_contact_update_unique_constraint_error
    - originCID = The contact that was attempted to be updated
    - conflictCID = The contact that already has the unique value in the request payload
    - requestData = A copy of the data in the request
    *}

    {$data.originCID = $triggerData.properties.originCID}
    {$data.conflictCID = $triggerData.properties.conflictCID}
    {$data.requestData = $triggerData.properties.requestData}

    {*Examine the conflicting contact and conflicting fields*}
    {*
    {$contact = $utils->setContact($data.conflictCID)}
    {$utils->jsonPrettyPrint($contact)}

    {$contact = $utils->setContact($data.originCID)}
    {$utils->jsonPrettyPrint($contact)}
    *}

    {*Decide to merge the conflicting contact into the origin contact*}
    {* Available options and theirs values:
    - orders: merge, ignore
    - events: merge, ignore
    - cart: sourceContact, destinationContact, lastModified
    - lists: sourceContact, destinationContact
    - attributes: sourceContact, destinationContact
    - supplements: sourceContact, destinationContact
    - email_channels: sourceContact, destinationContact
    - sms_channels: sourceContact, destinationContact
    - push_channels: merge, ignore
    *}

    {$options = [
    'orders' => 'merge',
    'events' => 'merge',
    'cart' => 'lastModified',
    'lists' => 'destinationContact',
    'attributes' => 'sourceContact',
    'supplements' => 'destinationContact',
    'email_channels' => 'destinationContact',
    'sms_channels' => 'sourceContact',
    'push_channels' => 'merge'
    ]}

    {$sourceContactCID = $data.conflictCID}
    {$destinationContactCID = $data.originCID}
    {$result = $utils->mergeContacts($sourceContactCID, $destinationContactCID, $options)}
  • Parameter Description Required Expected Default
    sourceContactCID Contact ID (CID) of the source contact. This contact will be deleted after the merge. required Valid Contact ID NA
    destinationContactCID Contact ID (CID) of the destination contact. This contact will still exist after the merge. required Valid Contact ID NA
    options A list of which data to keep from each contact required A valid json object with all required fields (See above example) NA

replaceTmpSupplementVersion

Swaps the production and temporary supplement collection versions after all data are loaded into the temporary supplement collection.

The replaceTmpSupplementVersion utility should only be used within the post job script. It is also always used in conjunction with createTmpSupplementVersion utility in the pre job script of the same data transformation.

  • {* in preview mode replaceTmpSupplementVersion does not run and also post job script does not run *}
    {$utils->replaceTmpSupplementVersion('existing_collection_name')}
    

sendMessage

The sendMessage utility can send a message using the message automation template key. Typically used to send an automation template sometime in the future if certain conditions are met.

This utility requires the enablement of an additional account feature. Please contact your CSM if your use case absolutely relies on the implementation of this utility.

  • Used in:  Data Automations
  • Syntax: {$utils->sendMessage($templateKey*, $extVars, $scheduledTime)}
  • {$send.templateKey = 'order-confirm'}
    {$send.extVars = ['orderID'=>1233,'totalAmount'=>12.33]}
    {$send.scheduledTime = '2120-06-21T12:23:00Z'}
    
    {$send.data = $utils->sendMessage($send.templateKey, $send.extVars, $send.scheduledTime)}
    
  • Parameter Description Required Expected Default
    templateKey A unique automation template key. required Valid automation template key NA
    extVars Data for use as external variables within the message. optional Array NA
    scheduledTime A future date when the message is to be sent. If time zone offset is not provided, UTC time zone will be used. optional String NA

upsertContact

Updates or creates a contact record in the Cordial database using supplied data. A new contact record will be created if the supplied lookup_key value does not already exist.

The contact channels.email.address property must be defined and populated if using the forceSubscribe argument of this method.

  • Used in: Data Automations
  • Syntax: {$utils->upsertContact($data*, $lookup_key*, $suppressTriggers, $forceSubscribe)}
  • {$contact_upsert.data.channels.email.address = 'msmith@example.com'}
    {$contact_upsert.lookup_key = "email:{$contact_upsert.data.channels.email.address}"}
    {$contact_upsert.data.age = 26}
    {$contact_upsert.data.welcome_series = 1}
    {$contact_upsert.data.weekly_deals = 0}
    {$contact_upsert.data.channels.email.subscribeStatus = 'subscribed'}
    {$contact_upsert.suppressTriggers = true}
    {$contact_upsert.forceSubscribe = true}
    
    {$contact = $utils->upsertContact($contact_upsert.data, $contact_upsert.lookup_key, $contact_upsert.suppressTriggers, $contact_upsert.forceSubscribe)}
    
    <h2>Debug $contact_upsert:</h2>
    {$utils->jsonPrettyPrint($contact_upsert)}
    <h2>Debug $contact:</h2>
    
  • Debug $contact_upsert:
    {
      "data": {
        "channels": {
          "email": {
            "address": "msmith@example.com"
          }
        },
        "age": 26,
        "welcome_series": 1,
        "weekly_deals": 0
      },
      "lookup_key": "msmith@example.com",
      "suppressTriggers": true,
      "forceSubscribe": false
    }
    
    Debug $contact:
    {
      "_id": "541137c785a750ffef7500999",
      "channels": {
        "email": {
          "address": "msmith@example.com",
          "subscribeStatus": "subscribed",
          "subscribedAt": "2020-01-06T18:29:12+0000",
          "unsubscribedAt": ""
        }
      },
      "age": 26,
      "lists": [
        "welcome_series"
      ],
      "createdAt": "2020-01-06T18:29:12+0000",
      "lastModified": "2020-01-08T15:24:01+0000",
      "cID": "541137c785a750ffef7500999",
      "id": "541137c785a750ffef7500999"
    }
  • Parameter Description Required Expected Default
    data Contact data to be updated including attribute values and list associations. required Array NA
    lookup_key A valid primary or secondary contact identifier key/value pair - email:msmith@example.com cID:58d2fc99ac0c8117814d4e78 custID:idValue. required String NA
    suppressTriggers If true, will suppress any triggered messages set to fire based on updates to values in the import. Defaults to true. optional Boolean string true
    forceSubscribe If set to true, will allow previously unsubscribed contacts to be updated as subscribed. Defaults to false. optional Boolean string false

upsertOrder

Creates a new order in the orders collection or performs an update if the orderID already exists. Please see the orders API documentation for a complete list of order attributes.

The contact identifier attribute is not part of the upsertOrder utility schema. Contact must be set in the context of a transformation, using the setContact utility for example.

  • Used in: Data Automations
  • Syntax: {$utils->upsertOrder($data*, $options)}
  • {$order=$utils->upsertOrder([
      'orderID' => '33451',
      'storeID' => '1',
      'customerID' => 4321,
      'purchaseDate' => '2018-12-14T17:50:25+0000',
      'shippingAddress' => [
        'name' => 'Mark Smith',
        'address' => '404 W Broadway',
        'city' => 'San Diego',
        'state' => 'CA',
        'postalCode' => 500000,
        'country' => 'USA'
      ],
      'billingAddress' => [
        'name' => 'Mark Smith',
        'address' => '404 W Broadway',
        'city' => 'San Diego',
        'state' => 'CA',
        'postalCode' => 500000,
        'country' => 'USA'
      ],
      'items' => [
        [
          'productID' => 'AC30',
          'description' => 'Stapler',
          'sku' => 'AC30-1000R',
          'category' => 'office_supplies',
          'name' => 'Acme-30 Stapler',
          'qty' => 1,
          'itemPrice' => 14.95,
          'salePrice' => 14.95,
          'url' => 'http://acmeofficesupplies.com/AC30',
          'productType' => 'physical',
          'manufacturerName' => 'Acme',
          'UPCCode' => '8 34460 00372 4',
          'images' => [
            'http://acmeofficesupplies.com/AC30/image.png'
          ],
          'tags' => [
            'tag1'
          ],
          'properties' => [ 'p1' => 'v1' ],
          'inStock' => true,
          'taxable' => true,
          'enabled' => true
        ]
      ],
      'tax' => 10,
      'shippingAndHandling' => '3.99',
      'properties' => [
         'p1' => 'v1',
         'p2' => 'v2'
      ]
    ])}
  • Parameter Description Required Expected Default
    data An array of order attributes. Empty quotes should be used for optional order attributes that have no value. required Array NA
    options An array of options. The only available option is suppressTriggers which is either true or false. optional Array NA

upsertProduct

Creates a new product record in the products collection or performs an update if the supplied productID already exists. Please see the products API documentation for a complete list of product attributes.

  • Used in: Data Automations
  • Syntax: {$utils->upsertProduct($data*, custom_id)}
  • {$product=$utils->upsertProduct([
    'productID' => 'AC30', 'productName' => 'AC30 Stapler', 'productType' => 'physical', 'category' => 'Office Supplies', 'price' => 35.99, 'images' => [ 'http://example.com/image.png' ], 'variants' => [ [ 'sku' => '321', 'qty' => 2, 'attr' => [ 'color' => 'red', 'size' => 'm' ] ], [ 'sku' => '444', 'qty' => 5 ] ], 'tags' => [ 'tag1', 'tag12' ], 'sale' => [ [ 'enabled' => 1, 'price' => 29.99, 'start' => '2018-12-13T01:09:07+0000', 'end' => '2018-12-31T01:09:07+0000' ] ] ], 'custom_id' (if productID is not specified) )}
  • Parameter Description Required Expected Default
    data An array of product attributes. Empty quotes should be used for optional product attributes that have no value. required String NA
    custom_id If product records do not inherently have a value for productID, the custom_id parameter can be used to set this value. Provide only the value without the attribute key. optional  String NA 

upsertSupplementRecord

Creates a new supplement record using the supplied data. If the supplied record with id already exists, the record will be updated. Learn more about how supplement records are stored.

  • Used in: Data Automations
  • Syntax: {$utils->upsertSupplementRecord($key*, $data*, $pk, $options)}
  • {$supplement.key = 'automobiles'}
    {$supplement.writeData.brand = 'honda'}
    {$supplement.writeData.model = 'odyssey'}
    {$supplement.writeData.price = '11000'}
    {$supplement.writeData.id = 5}

    {$supplement.automobiles = $utils->upsertSupplementRecord($supplement.key, $supplement.writeData)}

    <h2>Debug $supplement</h2>
    {$utils->jsonPrettyPrint($supplement)}
  • The _action parameter will indicate action type as being updated or created.

    Debug $supplement
    {
        "key": "automobiles",
        "writeData": {
            "brand": "honda",
            "model": "odyssey",
            "price": "11000",
            "id": 5
        },
        "automobiles": {
            "_id": "5",
            "brand": "honda",
            "model": "odyssey",
            "price": "11000",
            "lm": "2020-05-12T20:58:58+0000",
            "ct": "2020-05-12T20:58:58+0000",
            "_action": "created"
        }
    }
  • An example of creating a supplement record using the custom_id as pk parameter when id is not passed in $data:

    {$supplement = $utils->upsertSupplementRecord(
      'automobiles',
      [
      'brand' => 'honda', 
      'model' => 'odyssey', 
      'price' => '11000'
      ],
      'customID123'
    )}
    
    <h2>Debug $supplement</h2>
    {$utils->jsonPrettyPrint($supplement)}

    Debug $supplement

    {
        "_id": "customID123",
        "brand": "honda",
        "model": "odyssey",
        "price": "11000",
        "lm": "2020-05-13T21:07:57+0000",
        "ct": "2020-05-13T20:56:04+0000",
        "_action": "created"
    }
  • Parameter Description Required Expected Default
    key A unique supplement collection identifier. required String NA
    data An array of supplement record field key/value pairs. Mind that if the supplement is a contact attribute, contact identifier (cID) should be provided. required Array NA
    pk A unique supplement record identifier. Parameter is optional as supplement record identifier can be set as one of the field key/value pairs in the data parameter. A unique id will be generated automatically if one is not passed in data or pkparameters. If different identifiers are passed in both data and pkparameters pk has priority over data. optional String NA
    options

    An array of key/value pairs describing the function execution behaviour.

    As one of the optionsthe strategy can be set. strategy defines whether the supplement records update and create actions are allowed or not. strategy possible values are upsert|update|insert. If strategy is update then only the existent records will be updated. If strategy is insert then only the new records will be introduced. If strategy is upsert then both actions are allowed.

    optional    Array  upsert

Message automations only

addSendProperties

The Smarty utility addSendProperties allows you to add key/value pairs to the system events (message-sent, open, click, bounce, etc.) properties object. System events are associated with every contact receiving the message and are stored in the contact activities collection.

Send properties must be added before the message is sent. It is not possible to add send properties to sent messages.

  • {$contactSendProperties = [
    'region' => 'northwest',
    'internalCode' => 'pacific'
    ]} {$utils->addSendProperties($contactSendProperties)} {$utils->jsonPrettyPrint($contactSendProperties)}
  • The resulting system events properties object:

    "properties":{
      "region":"northwest",
      "internalCode":"pacific"
    }
  • Parameter Description Required Expected Default
    sendProperties An array of system event property key/value pairs. required String NA

addSendTag

To maintain consistent stats filter results over time, you can apply send tag filters. Send tag filters are added within the message code using Smarty and can be unique per contact based on a contact's attribute. Send tags can be added to batch and automated messages.

Ensure that tags added using the addSendTag utility are not duplicates of tags added during message creation. When duplicate tags are present, only one instance will be tracked.

For example, you may want to filter message stats according to a contact loyalty attribute to check a subset of the message send stats for Gold, Silver and Platinum members.

  • Used in: Message Automations
  • Syntax: {$utils->addSendTag($tagName)}
  • {$send.tagName = $contact.loyalty}
    
    {$utils->addSendTag($send.tagName)}
  • Loyalty attribute category values can now be added to message Stats Filters of sent messages containing the utility:

  • Add a single string value as message send tag:

    {$utils->addSendTag('value1')}

    Add an array of string values as message send tags:

    {$utils->addSendTag(['value1', 'value2'])}

    Add a default send tag along with conditional tags based on contact's list membership:

    {$send.tagName[] = '2020 Donor List Member'}
    {if in_array('donate19campaign', $contact.lists)} {$send.tagName[] = '2019 Donor List Member'} {/if} {if in_array('donate18campaign', $contact.lists)} {$send.tagName[] = '2018 Donor List Member'} {/if}
    {$utils->addSendTag($send.tagName)}
  • Parameter Description Required Expected Default
    tagName Send tag name. Can be an array of message send tag values. Variables are allowed. required String NA

addVcard

The addVcard utility inserts the parameters and media into an MMS Contact Card, such as your company name, logo, phone number, address, email, address, and note. All parameters are optional but at least one is required to send the Contact Card.

  • Used in: Message Automations 
  • Syntax: {$utils->addVcard
  • {$utils->addVcard([ 
    'photo' => 'https://images.cordial.com/1003/96x96/CordialThreads_favicon_96x.png',
    'first' => 'Cordial',
    'last' => 'Threads',
    'phone' => '+18885551212',
    'title' => 'Best ESP',
    'url' => 'https://www.cordial.com/',
    'company' => 'Cordial Inc',
    'street' => '123 Main Street',
    'city' => 'San Diego',
    'state' => 'CA',
    'postal' => '92109',
    'country' => 'USA'
    ])}
  • Parameters Description Required Expected
    photo Thumbnail image (90x90) optional String
    first First name optional String
    last Last name optional String
    title Title optional String
    url Company name optional Object
    street Phone number optional String
    city City optional String
    state State optional String
    postal Postal code optional String
    country Country optional String
    note Additional text optional String

getBarcodeURL

The barcode generator provides an easy way to generate high-quality horizontal barcode images in your messages based on the provided code.

  • {$barCode.code = '28373984'}
    {$barCode.symbology = code39}
    {$barCode.options.padding = 20}
    {$barCode.options.scale = 2}
    {$barCode.options.height = 100}
    
    {$barCode.data = $utils->getBarcodeURL($barCode.code, $barCode.symbology, $barCode.options)}
    
    <strong>Scan the code:</strong><br>
    <img src={$barCode.data}>
    
    <h2>Debug $barCode</h2>
    {$utils->jsonPrettyPrint($barCode)}
  • Scan the code:

    Debug $barCode
    {
      "code": "28373984",
      "symbology": "code39",
      "options": {
        "padding": 20,
        "scale": 2,
        "height": 100
      },
      "data": "https://barcodes.cfw.cordial.com/gen/?p=eyJzeW1ib2xvZ3kiOiJjb2RlMzkiLCJ0ZXh0IjoiMjgzNzM5ODQiLCJwYWRkaW5nIjoyMCwic2NhbGUiOjIsImhlaWdodCI6MTAwfQ&s=OebhWu6WWVufZPk7oc_erEQpurBjL8lWz2E0GRqlmYw"
    }
  • Generate a barcode using the value of the contact attribute "membership_number" as the code parameter. Note that the contact record must have a value for the "membership_number" attribute or the barcode will not render.

    {$barcode.code = $contact.membership_number}

    You are able to upload a supplement of coupon codes, and using the reserveOne utility, provide unique codes to each of your contacts.

    The following example assumes that you have a supplement collection called "couponBank1" with codes stored as supplement records in the proper format.

    {$coupon=$supplements->reserveOne('couponBank1')}
    
    {$barcode.code = $coupon.code}
  • Parameter Type Description Example
    *code string A code that will be used to generate the bar code.
    Note:
    If symbology is set to "code128", the code can contain letters and numbers.
    If symbology is set to "code39", the code can only contain numbers.
    1723746389
    *symbology string Defines the symbology type for the bar code.
    Possible Values:
    code128, code39
    code39
    options object An object of key/value pairs for additional control of barcode rendering. See below for parameters. See below
    padding number Sets the padding in pixels of the barcode.
    Default is 0, Max is 25.
    Possible Values:
    1-25
    5
    scale number Sets the scale of the barcode using a range of 1-5. Pixel width is determined by the number of characters set in the code parameter.
    Default is 2, max is 5.
    Possible Values:
    1-5
    2
    height number Sets the height of the barcode in pixels using a range of 0-300px
    Default is 100, max is 300.
    Possible Values:
    0-300
    50

getMessageLinkAppendValue

The getMessageLinkAppendValue utility returns link append key/value pairs previously set as defaults at the account level and those set using the setMessageLinkAppendValue utility. Useful for verifying existing link append key/value pairs before setting additional pairs.

This utility does not return link appends set using the appendQueryString Smarty modifier or the data-crdl-linkappend attribute.

  • Used in: Message Automations
  • Syntax: {$utils->getMessageLinkAppendValue()}
  • {$links.account_level_appends = $utils->getMessageLinkAppendValue()}
    
    {$links.returns_null = $utils->setMessageLinkAppendValue('foo', 'bar')}
    
    {$links.account_and_utility_appends = $utils->getMessageLinkAppendValue()}
    
    {$utils->jsonPrettyPrint($links)}
  • {
      "account_level_appends": {
        "utm_campaign": "{$message.name}",
        "utm_source": "cordial",
        "utm_medium": "email",
        "mciD": "{$mcID}"
      },
      "returns_null": null,
      "account_and_utility_appends": {
        "utm_campaign": "{$message.name}",
        "utm_source": "cordial",
        "utm_medium": "email",
        "mciD": "{$mcID}",
        "foo": "bar"
      }
    }

jwt_encode

The jwt_encode utility is used to create a JSON Web Token with the provided payload, using the RS256 signing algorithm.

See the jwt_decode utility to verify that the JWT is valid with the provided public key.

  • Used in: Message Automations
  • Syntax: {$utils->jwt_encode(array $data, str $privateKey, str $algorithm)}
  • {$privateKey=MIIEogIBAAKCAQEAnzyis1ZjfNB0bBgKFMSvvkTtwlvBsaJq7S5wA+kzeVOVpVWw
    kWdVha4s38XM/pa/yr47av7+z3VTmvDRyAHcaT92whREFpLv9cj5lTeJSibyr/Mr
    m/YtjCZVWgaOYIhwrXwKLqPr/11inWsAkfIytvHWTxZYEcXLgAXFuUuaS3uF9gEi
    NQwzGTU1v0FqkqTBr4B8nW3HCN47XUu0t8Y0e+lf4s4OxQawWD79J9/5d3Ry0vbV
    3Am1FtGJiJvOwRsIfVChDpYStTcHTCMqtvWbV6L11BWkpzGXSW4Hv43qa+GSYOD2
    QU68Mb59oSk2OB+BtOLpJofmbGEGgvmwyCI9MwIDAQABAoIBACiARq2wkltjtcjs
    kFvZ7w1JAORHbEufEO1Eu27zOIlqbgyAcAl7q+/1bip4Z/x1IVES84/yTaM8p0go
    bmMhvgry/mS8vNi1BN2SAZEnb/7xSxbflb70bX9RHLJqKnp5GZe2jexw+wyXlwaM
    +bclUCrh9e1ltH7IvUrRrQnFJfh+is1fRon9Co9Li0GwoN0x0byrrngU8Ak3Y6D9
    D8GjQA4Elm94ST3izJv8iCOLSDBmzsPsXfcCUZfmTfZ5DbUDMbMxRnSo3nQeoKGC
    0Lj9FkWcfmLcpGlSXTO+Ww1L7EGq+PT3NtRae1FZPwjddQ1/4V905kyQFLamAA5Y
    lSpE2wkCgYEAy1OPLQcZt4NQnQzPz2SBJqQN2P5u3vXl+zNVKP8w4eBv0vWuJJF+
    hkGNnSxXQrTkvDOIUddSKOzHHgSg4nY6K02ecyT0PPm/UZvtRpWrnBjcEVtHEJNp
    bU9pLD5iZ0J9sbzPU/LxPmuAP2Bs8JmTn6aFRspFrP7W0s1Nmk2jsm0CgYEAyH0X
    +jpoqxj4efZfkUrg5GbSEhf+dZglf0tTOA5bVg8IYwtmNk/pniLG/zI7c+GlTc9B
    BwfMr59EzBq/eFMI7+LgXaVUsM/sS4Ry+yeK6SJx/otIMWtDfqxsLD8CPMCRvecC
    2Pip4uSgrl0MOebl9XKp57GoaUWRWRHqwV4Y6h8CgYAZhI4mh4qZtnhKjY4TKDjx
    QYufXSdLAi9v3FxmvchDwOgn4L+PRVdMwDNms2bsL0m5uPn104EzM6w1vzz1zwKz
    5pTpPI0OjgWN13Tq8+PKvm/4Gb2MjgOgPWQkslulO/oMcXbPwWC3hcRdr9tcQtn9
    Imf9n2spL/6EDFId+Hp/7QKBgAqlWdiXsWckdE1Fn91/NGHsc8syKvjjk1onDcw0
    NvVi5vcba9oGdElJX3e9mxqUKMrw7msJJv1MX8LWyMQC5L6YNYHDfbPF1q5L4i8j
    8mRex97UVokJQRRA452V2vCO6S5ETgpnad36de3MUxHgCOX3qL382Qx9/THVmbma
    3YfRAoGAUxL/Eu5yvMK8SAt/dJK6FedngcM3JEFNplmtLYVLWhkIlNRGDwkg3I5K
    y18Ae9n7dHVueyslrb6weq7dTkYDi3iOYRW8HRkIQh06wEdbxt0shTzAJvvCQfrB
    jg/3747WSsf/zBTcHihTRBdAv6OmdhV4/dD5YBfLAkLrd+mX7iE=}
    {$token=$utils->jwt_encode([ "iss" => "cordial.com", "aud" => "example.com", "iat" => 1356999524, "nbf" => 1357000000 ],$privateKey)}
    Token: {$token}
  • Token: sampleTokenvalue112233445566
  • Parameter Description Type Default
    data Claims are not required but provide security and permissions. Array NA
    privateKey The secret key used to generate the signature, which is validated by the consumer's public key. String NA
    algorithm Determines which algorithm is used to sign the JWT. String rs256

jwt_decode

The jwt_decode utility returns true/false based on if a public key successfully decodes the provided JSON Web Token.

  • Used in: Message Automations
  • Syntax: {$utils->jwt_decode(str $token, str $publicKey, str $algorithm)}
  • {$token=$utils->jwt_encode([$data],$privateKey)}
    
    {$decoded=$utils->jwt_decode($token, $publicKey, $algorithm)}
    Decoded: {$utils->jsonPrettyPrint($decoded)}
    
  • Decoded: true
  • Parameter Description Type Default
    token A signed JSON Web Token that certifies that the public/private key pairing can be verified and trusted. String NA
    publicKey The consumer of the JWT gets a public key that is used to validate the signature given by the private key of the provider. String NA
    algorithm Determines which algorithm is used to sign the JWT. String rs256

mmsMedia

The mmsMedia utility inserts an experiment into an MMS or SMS message.

SMS & MMS experiments are only supported in batch messages.

  • Used in: Batch Messages
  • Syntax: {$utils->mmsMedia($mediaURL, $mediaType)}
  • {$utils->mmsMedia("https://images-na.ssl-images-amazon.com/images/I/61IkrxQ9p8L._AC_SL1500_.jpg") type= "image"}
    {/mmsMedia}
  • The media type parameter supports the following media types:
    Image
    {$utils->mmsMedia("https://images-na.ssl-images-amazon.com/images/I/61IkrxQ9p8L._AC_SL1500_.jpg", "image")}
    Audio
    {$utils->mmsMedia("https://cordialdev-testclient.s3.us-west-2.amazonaws.com/johanna/HappyFace.mp3", "audio")}
    Video
    {$utils->mmsMedia("https://cordialdev-testclient.s3.us-west-2.amazonaws.com/johanna/SampleVideo_1280x720_1mb.mp4", "video")}
    
  • Parameter Description Required Expected Default
    mediaURL A valid URL to the media asset. required String NA
    mediaType Specifies the type of media. Accepted values are: image audio video required String NA

reserveOne

The reserveOne utility allows you to reserve a supplement record and render its value in a message. Once a supplement record is reserved and rendered in a message, it it is given a time of use stamp, and cannot be rendered again via the reserveOne utility. Therefore, one of the primary use cases for this utility is to reserve and render a unique coupon code for individual message recipients.

In addition to live message sends, test message sends will also flag a record as "reserved".

  • {$coupon.key = 'couponBank1'}
    {$coupon.filter = ['filterOptions' => ['expdate' => ['gt' => {$smarty.now|date_format:'%Y-%m-%d'}]]]}
    
    {$coupon = $supplements->reserveOne($coupon.key, $coupon.filter)}
    
    Here is your coupon code: <strong>{$coupon.code}</strong>
  • In our example, these coupon codes are stored as supplement records in the couponBank1 supplement collection. We are using the expdate supplement field to filter for coupons that have not expired using the filterOptions parameter.
    {
      "code": "1234015",
      "id": "1",
      "expdate": "2023-03-23T17:45:18+0000"
    },
    {
      "code": "1234016",
      "id": "2",
      "expdate": "2023-03-23T17:45:18+0000"
    },
    {
      "code": "1234017",
      "id": "3",
      "expdate": "2023-03-23T17:45:18+0000"
    }
  • Here is your coupon code: 1234015
  • Parameter Description Required Expected Default
    key A unique key created by the user for a stored supplement. required String NA
    filterOptions A filter used to query supplement records by date. Only indexed fields can be queried. optional Array []

sendWebhook

The sendWebhook utility allows you to ping a URL when a message renders during preview or send time. This is useful if you need to ping a URL with a query string unique to the contact.

Due to the high traffic volume that the sendWebhook utility can generate, it is recommended to only use this on a service your company owns, or a service your company has explicit permission to use.

  • Used in:Message Automations
  • Syntax: {$utils->sendWebhook($url}
  • {$webhook_response = $utils->sendWebhook("http://analytics.example.com/pingme?cID=$cID&mcID=$mcID&msID=$message.msID")}

setEmailHeaders

Use the setEmailHeaders utility to set or override email headers at the message level. If email headers are set at the account level, the headers specified by this util will override the ones set at the account level. 

The following headers cannot be overridden: X-Feedback-ID, X-MSYS-SUBACCOUNT, X-Crdl-Mc, fromDesc, fromEmail, subject, toName, replyEmail, DKIM-Signature, To, From, MIME-Version, Content-type, Return-Path, Received, Path, Sender, bcc, cc, reply-to, Message-ID, Date

  • Used in: Message Automations 
  • Syntax: {$utils->setEmailHeaders($headers)}
  • {$utils->setEmailHeaders(["foo"=>"bar", "biz"=> $baz])}
  • Parameter Description Required Expected Default
    headers Used to set custom headers on an email message. required Array of key value pairs NA

setEmailLinkTracking

Use the setEmailLinkTracking utility to disable link tracking at the message level. When set to false, link tracking will be disabled for every sent message unless conditionally applied to individual messages using Smarty conditionals. Links are tracked by default for all sent messages.

The Link Tracking setting under message Goals and Tracking does not override the utility.

When using conditionals with this utility, you can check whether link tracking will be enabled or disabled for a particular message using the getEmailLinkTracking utility.

  • Used in: Message Automations
  • Syntax: {$utils->setEmailLinkTracking(true/false)}
  • {$utils->setEmailLinkTracking(false)}
    
    {$linkTrack = $utils->getEmailLinkTracking()}
    {if $linkTrack == false}
    Link tracking is <strong>disabled</strong> for this message.
    {else}
    Link tracking is <strong>enabled</strong> for this message.
    {/if}
  • Link tracking is disabled for this message.
  • Link tracking can be disabled conditionally using Smarty. Here is a simple example of using an {if} statement to display specific content and disable link tracking for messages where the recipient's age is 23.
    {if $contact['age'] == 23}
      Message content with a <a href="example.com">link</a>.
      {$utils->setEmailLinkTracking(false)}
    {/if}
  • Use the true and false boolean values to enable or disable link tracking in email messages. Links are tracked by default.

setEmailOpensTracking

Use the setEmailOpensTracking utility to disable email opens tracking at the message level. When set to false, opens tracking will be disabled for every sent message unless conditionally disabled for qualifying messages using Smarty conditionals. By default, opens tracking is set to true for all sent messages.

When using conditionals with this utility, you can check whether opens tracking will be enabled or disabled for a particular message using the getEmailOpensTracking utility.

  • Used in: Message Automations
  • Syntax: {$utils->setEmailOpensTracking(true/false)}
  • {$utils->setEmailOpensTracking(false)}
    
    {$opens = $utils->getEmailOpensTracking()}
    
    {if $opens == false}
      Opens tracking is <strong>disabled</strong> for this message.
    {else}
      Opens tracking is <strong>enabled</strong> for this message.
    {/if}
  • Opens tracking is disabled for this message.
  • Message opens tracking can be disabled conditionally using Smarty. Here is a simple example of using an {if} statement to display specific content and disable opens tracking for messages where the recipient's age is 23.
    {if $contact['age'] == 23}
      Message content with a <a href="example.com">link</a>.
      {$utils->setEmailOpensTracking(false)}
    {/if}
  • Use the true and false boolean values to enable or disable email message opens tracking. The setEmailOpensTracking utility is set to true by default.

setMessageLinkAppendValue

The setMessageLinkAppendValue utility appends a key/value pair to all links in a message. Similar to default link appends, the utility operates on a global level. Unlike with default link appends, the output of dynamic Smarty variables can be used as the append value.

Additional notes:

  • If the utility key matches any of the default keys set at the account level, its value will overwrite the account default value
  • Link appends defined with the utility are appended to the default link append string
  • If default link appends are disabled at the message level, the utility appends will still render

Link appends can also be set using the appendQueryString Smarty modifier and the data-crdl-linkappend attribute.

You can preview default link append key/value pairs set at the account level during message creation using the getMessageLinkAppendValue utility.

  • Used in: Message Automations
  • Syntax: {$utils->setMessageLinkAppendValue($appendKey*, $appendValue*)}
  • {$links.account_level_appends = $utils->getMessageLinkAppendValue()}
    
    {$links.returns_null = $utils->setMessageLinkAppendValue('foo', 'bar')}
    
    {$links.account_and_utility_appends = $utils->getMessageLinkAppendValue()}
    
    {$utils->jsonPrettyPrint($links)}
  • {
      "account_level_appends": {
        "utm_campaign": "{$message.name}",
        "utm_source": "cordial",
        "utm_medium": "email",
        "mciD": "{$mcID}"
      },
      "returns_null": null,
      "account_and_utility_appends": {
        "utm_campaign": "{$message.name}",
        "utm_source": "cordial",
        "utm_medium": "email",
        "mciD": "{$mcID}",
        "foo": "bar"
      }
    }
  • Parameter Description Required Expected Default
    appendKey Link append key such as utm_medium. required String NA
    appendValue Link append value such as email or output of a dynamic variable. required String NA

setMmsMedia

The setMmsMedia utility inserts media into an MMS message. Supported media types are images, audio and video.

The setMmsMedia utility is only supported in SMS channel messages when the send type is set to MMS

  • Used in: Message Automations
  • Syntax: {$utils->setMmsMedia($mediaURL, $mediaType)}
  • {$utils->setMmsMedia("https://images-na.ssl-images-amazon.com/images/I/61IkrxQ9p8L._AC_SL1500_.jpg", "image")}
    
  • The media type parameter supports the following media types:
    Image
    {$utils->setMmsMedia("https://images-na.ssl-images-amazon.com/images/I/61IkrxQ9p8L._AC_SL1500_.jpg", "image")}
    Audio
    {$utils->setMmsMedia("https://cordialdev-testclient.s3.us-west-2.amazonaws.com/johanna/HappyFace.mp3", "audio")}
    Video
    {$utils->setMmsMedia("https://cordialdev-testclient.s3.us-west-2.amazonaws.com/johanna/SampleVideo_1280x720_1mb.mp4", "video")}
    
  • Parameter Description Required Expected Default
    mediaURL A valid URL to the media asset. required String NA
    mediaType Specifies the type of media. Accepted values are: image audio video required String NA

signature_encode

The signature_encode utility generates a signature from a private key that is shared between the provider and the consumer.

  • Used in: Message Automations
  • Syntax: {$utils->signature_encode($data,$privateKey,$algorithm)}
  •               {$stringForEncode = "email@example.com"}
                  {$signature = $utils->signature_encode($stringForEncode,$privateKey)}
                  
    Signature: {$signature}
  • Signature: HSsCsYgbdJckwiGLKCWGsRcthSkMzz6Dg-9aeC52MptjtSE3t45JRCs
  • Parameter Description Type Default
    data The payload to be encoded that will be available to the recipient after verifying the credentials. String NA
    privateKey The shared secret key between the provider and the consumer. String NA
    algorithm Determines which algorithm is used to sign the token. String rs256

 

Comments

0 comments

Please sign in to leave a comment.