Quick Start: Recommendations

Welcome to the Particular Audience Quick Start guide! By the end of this tutorial you will have a functioning recommendation UI widget that you can place on your website. Along the way you will also learn more about the PA recommendation system.

In 10 minutes you will build:

💻 Building a simple UI with React

To get started, let’s create a React project.

yarn create react-app pa-recommendation-ui

You should now have an empty React JS project.

Let’s now start building!

cd pa-recommendation-ui
yarn start

Adding the PA Sandbox Tag

Let’s go ahead and add in the PA Sandbox Tag. This (to an extent) mimics the production PA Tag that will be given to you. The tag also helps get the CustomerId for you from PA’s servers.

To add the tag, navigate to public/index.htmland add the following script in the head tag.

public/index.html
<script>window.addPAC = function (c, e) { document.cookie = 'PAC=' + c + ';' + e + ';' }</script>
<script src="https://cdn.particularaudience.com/js/sandbox/t.js"></script>

🧙 Tips: The PA Tag does a lot of house keeping work such as track user behaviour data and automatically fetch the CustomerID for you.

Boilerplate React code

Next, let’s go to src/App.js and add some boilerplate code.

This piece of code contains three key steps:

  1. Fetch recommendations

  2. Enrich recommendation data

  3. Display recommendations

src/App.js
import './App.css';
import React, { useState, useEffect } from "react";

const WEBSITE_ID = '11111111-1111-1111-1111-111111111111'

const PLACEHOLDER_DATA_STORE = {
  pr001: {
    title: 'Sennheiser CX 400BT True Wireless In-Ear Headphones (Black)',
    price: '$149',
    imageUrl: 'https://s3-syd-shrd-api-doc-public-assets.s3-ap-southeast-2.amazonaws.com/sennheiser-cx.jpeg'
  },
  pr002: {
    title: 'Sony WF-XB700 Truly Wireless In-Ear Extra Bass Headphones (Blue)',
    price: '$139',
    imageUrl: 'https://s3-syd-shrd-api-doc-public-assets.s3-ap-southeast-2.amazonaws.com/sony-wf-xb700.jpeg'
  }, pr003: {
    title: 'Urbanista Athens True Wireless In-Ear Headphones (Black)',
    price: '$114',
    imageUrl: 'https://s3-syd-shrd-api-doc-public-assets.s3-ap-southeast-2.amazonaws.com/urbanista-athens.jpeg'
  }, pr004: {
    title: 'SteelSeries Arctis 7 Wireless Gaming Headset 2019 Edition (Black)',
    price: '$339',
    imageUrl: 'https://s3-syd-shrd-api-doc-public-assets.s3-ap-southeast-2.amazonaws.com/steelseries-7.jpeg'
  }, pr005: {
    title: 'SteelSeries Arctis 9X Wireless Gaming Headset for Xbox Series X',
    price: '$359',
    imageUrl: 'https://s3-syd-shrd-api-doc-public-assets.s3-ap-southeast-2.amazonaws.com/steelseries-9x.jpeg'
  }, pr006: {
    title: 'SteelSeries Arctis 7P Wireless Gaming Headset (White)',
    price: '$349',
    imageUrl: 'https://s3-syd-shrd-api-doc-public-assets.s3-ap-southeast-2.amazonaws.com/steelseries-7p.jpeg'
  }
}

const STYLES = {
  container: {
    display: 'grid',
    gridGap: '16px 16px',
    gridTemplateColumns: 'auto auto auto auto',
    padding: 16
  },
  slot: {
    border: '1px solid black',
    padding: 8
  }
}

function App() {

  const [rawRecommendations, setRawRecommendations] = useState([])
  const [enrichedRecommendations, setEnrichedRecommendations] = useState([])

  useEffect(() => {
    // Get PA CustomerID
    const customerId = getCookie('PAC')
    fetchRecommendations(customerId)
  }, []);

  useEffect(() => {
    // Enrich data
    enrichRecommendations()
  }, [rawRecommendations]);


  const getCookie = (cookieName) => {
    let name = cookieName + '='
    let cookieAttributes = document.cookie.split(';')
    for (var i = 0; i < cookieAttributes.length; i++) {
      let cookieAttribute = cookieAttributes[i]
      while (cookieAttribute.charAt(0) === ' ') {
        cookieAttribute = cookieAttribute.substring(1)
      }
      if (cookieAttribute.indexOf(name) === 0) {
        return cookieAttribute.substring(name.length, cookieAttribute.length)
      }
    }
    return ''
  }

  const fetchRecommendations = async (customerId) => {
    const res = await fetch(`https://recs-1a.particularaudience.com/1.0/ClientRecom/${WEBSITE_ID}/Personalized?customerId=${customerId}`)
    if (res.ok) {
      const resultsJson = await res.json()
      setRawRecommendations(resultsJson.payload)
    }
  };

  const enrichRecommendations = () => {
    const enrichedRecs = []
    rawRecommendations.forEach(productId => {
      enrichedRecs.push(PLACEHOLDER_DATA_STORE[productId])
    })
    setEnrichedRecommendations(enrichedRecs)
  }

  return (
    <div className="App">
      <h1>Particular Audience React Recommendation UI</h1>
      <div style={STYLES.container}>
        {
          enrichedRecommendations.map((recommendation) => {
            return (
              <div style={STYLES.slot}>
                <img width={150} height={150} src={recommendation.imageUrl} />
                <p>{recommendation.price}</p>
                <p>{recommendation.title}</p>
              </div>
            )
          })
        }
      </div>
    </div>
  );
}

export default App;

Fetching recommendations There are three key unique IDs to keep in mind when making a GET request to any recommendation endpoint:

  • WebsiteID: this is an ID given to you, the client, when the tracker is completed

  • CustomerID: this is the customer ID

  • ProductID: this is the primary ID of the product, either on a SKU level or item group level depending on how the recommendations were set up for you

🧙 Tips: The Sandbox WebsiteID is 111111-1111-1111-1111-111111111111

🧠 Note: CustomerID vs ProductID based requests We have customer centric recommendations that require a customer ID such as recently viewed products. On the other hand, we have product based recommendations which depend on what product the user is viewing at the current moment. To get a full idea of all the available tactics, please refer to our API Reference. If you’re unsure of what tactic or strategy to implement, reach out to your account manager and we can create a plan for you!

For this tutorial, we will use one of the CustomerID specific endpoints that you can see below.

https://recs-1a.particularaudience.com/1.0/ClientRecom/11111111-1111-1111-1111-111111111111/Personalized?customerId={CustomerID}

Before we make the request we need to get the CustomerID. The PA Tag stores the CustomerID either:

  • In a cookie

  • As part of the HTML body

The boilerplate code has included a function to get the CustomerID.

const getCookie = (cookieName) => {
    let name = cookieName + '='
    let cookieAttributes = document.cookie.split(';')
    for (var i = 0; i < cookieAttributes.length; i++) {
      let cookieAttribute = cookieAttributes[i]
      while (cookieAttribute.charAt(0) === ' ') {
        cookieAttribute = cookieAttribute.substring(1)
      }
      if (cookieAttribute.indexOf(name) === 0) {
        return cookieAttribute.substring(name.length, cookieAttribute.length)
      }
    }
    return ''
  }

Once you have the CustomerID you are able to make the sandbox request.

🧙 Tips: If you want to use PA Recommendations in your email or SMS campaigns, be sure to save the CustomerID down in your database for future requests.

Enrich recommendation data

The PA Recommendation API returns a list of product IDs. We do not include extra data such as product title, image, price, availability or other pieces of information. This provides flexibility in how you enrich the data with your own up-to-date product information.

In our code sample, we mimic this process with a constant variable called PLACEHOLDER_DATA_STORE which contains the product information.

Display recommendations

The easy part! Now that we have our enriched recommendations, we can display it however we want.

Last updated