You can use Dynamic Yield’s recommendation engine to return the results of a recommendation without Dynamic Yield rendering it using a client-side API. This lets you control how to display the recommendation. The results are returned as a set of products in JSON format.
Creating Recommendations Using the Client-Side API
- Create a recommendation strategy. Enable the Activate using API setting, and configure the number of products to be requested.
- After saving the strategy, use the Embed Code option within the strategies list to obtain API snippet:
- Edit the recommendationWidgetData API as required. For details, see below. You can also use this API in addition to the Return Recommendation Realtime Filter Data API to add real-time filter rules to filter the results based on data obtained within the session.
- Track the performance of the recommendations using the recommendations.registerElements API. For details, see below.
Render Recommendation or Dynamic Content
Render the Dynamic Content or Recommendation defined by a name or id. This is only applicable for campaigns whose Location is determined by "Embed code":
Syntax
DYO.smartObject(smartObjectId, props)
Parameters:
- smartObjectId: Id or name of the Dynamic Content or Recommendation
- props:
rendering properties:
target – selector id used as rendered tag target
afterRenderCallback – an optional function to execute after the item is rendered
Example:
DYO.smartObject('Car Ad', {
target: 'car_ad_div_id',
inline: true
});
Return Recommendation Widget Data
Use Dynamic Yield’s recommendation engine to return the results of a recommendation without Dynamic Yield rendering it using a client-side API.
This lets you control:
- How to display the recommendation
- Adding real-time filters to enable real-time results based on data obtained within the session (e.g. show products priced higher than the currently viewed product, present products based on the visitors explicit selection, etc.)
The results are returned as a set of products in JSON format. For more details, see Recommendations API – Client-Side. This API also requires you to track the recommendation widget as detailed below.
Syntax
DYO.recommendationWidgetData(id, opts, callback)
Parameters:
- id: The ID of the strategy to use when rendering the recommendation.
- opts: Optional parameters
- context: The page context is taken from the current page unless you specify a different context here.
- maxProducts: Overrides the “number of items” value from the Strategy configuration screen.
- exclude: An array of SKUs or Group_IDs to exclude from the recommendation results. This is often used to prevent displaying the same item more than once on a page that has multiple recommendation widgets.
- realtimeRules: Add real-time filter rules in order to enable real-time results based on data obtained within the session. Use-case and real time filter data information can be found in Return Recommendation Realtime Filter Data below.
- callback: Callback function to execute once recommendation data is returned.
Example Call:
// pass product context manually to request
DYO.recommendationWidgetData(12345, {
exclude: {
'group_id': ['127829', '1217317', '1247581']
},
context: {
'lng': 'en_GB',
'type': 'PRODUCT',
'data': ["1253851-001"]
}},
function(err, data) {
if (err) {
//error handling
}
var rcomData = data;
});
Example Response:
{
"wId": 3197,
"name": "TOP_N", // strategy mame
"expData": {
"varId": null,
"expId": null
},
"fId": 543,
"fallback": true, //at least one of the items used a fallback
"slots": [
{
"item": {
"entity_id": "330367",
"color": "1349",
"product_url": "......html",
"color_prod_img": "https:.....3.jpg",
"publish_time": "2019-07-05T03:22:08",
"flag_img_url": "NONE",
"size_label": "38",
"color_image": "https://tropicalflowerdress.......jpg",
"size": "1899",
"category": "dresses",
"related_colors_label": "string",
"title": "great flower dress",
"related_colors": "619,628,3064,3070,3133",
"color_label": "flower",
"item_group_id": "620",
"category1": "women",
"sku": "6510120",
"description": "the best tropical flower dress in the universe",
"price": 199,
"in_stock": true,
"categories": [
"women",
"dresses"
],
"dy_display_price": "199",
"name": "tropical flower dress",
"url": "https://www.tropicdresses........html",
"category4": "",
"flag": "",
"tier_prices": "NONE",
"thumbnail_url": "https://tropicdresses......jpg",
"image_url": "https://tropicdresses......jpg",
"keywords": [
"women",
"dresses",
],
"group_id": "33112327",
"quantity": "2"
},
"fallback": true, //this item used a fallback strategy
"strId": 1,
"md": {}
},
{
"item": {
"entity_id": "330368",
"color": "1349",
"product_url": "......html",
"color_prod_img": "https:.....4.jpg",
"publish_time": "2019-07-06T03:21:00",
"flag_img_url": "NONE",
"size_label": "38",
"color_image": "https://tropicalflowerpants.......jpg",
"size": "1899",
"category": "pants",
"related_colors_label": "string",
"title": "great flower pants",
"related_colors": "619,628,3064,3070,3133",
"color_label": "flower",
"item_group_id": "534",
"category1": "women",
"sku": "6510145",
"description": "the best tropical flower pants in the universe",
"price": 89,
"in_stock": true,
"categories": [
"women",
"pants"
],
"dy_display_price": "89",
"name": "tropical flower pants",
"url": "https://www.tropicpants........html",
"category5": "",
"flag": "",
"tier_prices": "NONE",
"thumbnail_url": "https://tropicpants......jpg",
"image_url": "https://tropicpants......jpg",
"keywords": [
"women",
"pants",
],
"group_id": "33112347",
"quantity": "1"
},
"fallback": false, //this item used the chosen strategy
"strId": 1,
"md": {}
},
]
}
Return Recommendation Realtime Filter Data
Real time filters are used in order to enable real-time results based on data obtained within the session (e.g. show products priced higher than the currently viewed product, present products based on the visitors explicit selection, etc.). There can be up to 5 real-time rules defined per widget and up to 30 custom filter rules in all.
Parameters:
- id: Unique ID number for every rule. This id will be used for APIs response. (If there are 2 rules that have the same id, the second rule will be dropped)
- type: Include\exclude only
- slots: All or specific slot positions where the first slot is in position 0
- conditions:
- IS // string or boolean (‘In stock’ - true/false) only
- IS_NOT // string only
- CONTAINS // Up to 10 of this type per filter
- EQ, GT, GTE, LT, LTE // numbers only
- Conditions are used to define condition type for filtering recommendations. Condition types:
- Building conditions - When building the rule, inside an argument multiple conditions have ‘or’ operator between them and adding additional arguments will have ‘and’ operator.
- value: Parameter for filter value by condition. Regular-expressions are not supported for realtime filters (can and should be added as additional conditions to the filter)
- priority (optional): The real time filters will be given first priority above any existing filters (build in DY Admin). But If you choose to add priority this can be done by adding priority data and choosing priority between 0 and 29. If there are existing rules defined in Admin (regular or real-time, any rule type) this will lower their existing priority
Use Case #1 - Adding free shipping suggestions
Request recommended products that fall in the price range that would qualify the visitor to get free-shipping (pass the threshold). In this example, the free shipping threshold is 50 and we would like to recommend products that price > difference between free shipping threshold and cart total and price < free shipping threshold (50 in this case).
var THRESHOLD = 50; // Cart threshold
var CART_TOTAL_SELECTOR = '.js-cart-totals__total' // Cart selector per site
var STRATEGY_ID = 64040; // Strategy ID for recommendations
var cartValuePromise = DYO.waitForElementAsync(CART_TOTAL_SELECTOR).then(function(elements) {
return parseFloat(elements[0].textContent.replace(/[^\d.-]/g, ''))
});
cartValuePromise.then(function(cartValue) {
var freeShippingRemainder = THRESHOLD - cartValue;
if (freeShippingRemainder > 0) {
console.log('Products above', freeShippingRemainder);
getProducts(STRATEGY_ID, freeShippingRemainder, THRESHOLD);
} else {
console.log('Over shipping limit')
// no need for recs.
}
});
function getProducts(strategyId, min, max) {
var realtimeRules = [{
"id": -1,
"query": {
"conditions": [{
"field": "price", // Condition
"arguments": [{
"action": "GTE", // Action type IS / IS_NOT / CONTAINS / EQ / GT / GTE / LT / LTE
"value": min // Value of condition
}]
}, {
"field": "price", // Condition
"arguments": [{
"action": "LTE",
"value": max
}]
}]
},
"type": "include", // Include or exclude
"slots": [] // Position in widget
}];
DYO.recommendationWidgetData(strategyId, {maxProducts: 10, realtimeRules: realtimeRules}, function(err, data) {
console.log(data);
});
}
Use Case #2 - Build a Product finder for requesting recommended products based on explicit filters set by the visitor in the session. In this example we will trigger 3 slots (2, 3 and 4) of product recommendations from the category with the highest score based on the users affinity profile.
var STRATEGY_ID = 12345;
DY.API('callback', function() {
DY.ServerUtil.getUserAffinities(function(error, affinityObject) {
if (error || !affinityObject.categories) {
getProducts(STRATEGY_ID, null);
return;
}
var categories = affinityObject.categories;
var sortedCategories = Object.keys(categories).map(function(name) {
return {
name: name,
score: categories[name]
};
}).sort(function(a,b) {
return b.score - a.score;
});
getProducts(STRATEGY_ID, sortedCategories[0].name);
}, 5);
});
function getProducts(strategyId, categoryName) {
var realtimeRules = [{
"id": -2,
"query": {
"conditions": [{
"field": "categories", // Condition
"arguments": [{
"action": "IS", // Action type IS / IS_NOT / CONTAINS / EQ / GT / GTE / LT / LTE
"value": categoryName // Value of condition
}]
}]
},
"type": "include", // Include or exclude
"slots": [1, 2, 3] // Position in widget
}];
DYO.recommendationWidgetData(strategyId, {maxProducts: 10, realtimeRules: realtimeRules}, function(err, data) {
console.log(data);
});
}
Track Recommendation Widget
In order to track a recommendation widget you manually added to your site using the recommendationWidgetDataAPI (see above), you need to make sure Dynamic Yield can track the widget as well. The JSON results of recommendationWidgetData are used to configure this tracking.
Syntax
DYO.recommendations.registerElements(el);
Usage
- Add the following attributes to the DOM element that contain the recommendation widget:
<div data-dy-widget-id="WIDGET_ID_HERE" data-dy-feed-id="FEED_ID_HERE"> <div data-dy-product-id="PRODUCT_SKU_HERE" data-dy-strategy-id="STRATEGY_ID_HERE">...</div> <div data-dy-product-id="PRODUCT_SKU_HERE" data-dy-strategy-id="STRATEGY_ID_HERE">... </div> . . </div>
- widget id – the wId from the JSON response. This is the ID of the strategy.
- feed id – the fId from the JSON response.
- strategy id – the strId from the JSON response (can be found under each "slot"). This represents the strategy type of each slot.
- product id – the sku of each product from the JSON response.
- Run the following API call:
Where el is the DOM element with the widget ID attribute (data-dy-widget-id).DYO.recommendations.registerElements(el);
Show all Recommendation Widget Responses
Presents all products returned by all recommendation widgets on the page.
Syntax
DYO.recommendations.getLoadedWidgets()
Response is an array of Return Recommendation Widget Data results for all recommendation widgets returned on the page.