PBA web SDK integration guide

At a glance: The Web SDK is a lightweight JavaScript tag for recording visitor activity on the website. Use it to record and measure user actions like visits, events, conversions, and revenue on your website.

5107_Infographic_Web_S2S_759x270_option1.jpg

Web SDK user and integration guide

  • The web SDK JavaScript tag:
    • is part of the People-Based Attribution (PBA) solution for analyzing user journeys across multiple platforms.
    • reports user visits and actions on your website to the AppsFlyer platform.
    • is a website plug-in module that needs no programming. It is agnostic to the website visitor's operating system and browser. Si
    • Size: 40-60Kb.
  • Implement the web SDK alongside the AppsFlyer mobile SDK to record and map user activity across your mobile app and web environments.
  • Events occurring outside of the website can be recorded using Web server-to-server events API (Web S2S)

Integrating the Web SDK into the website

Installation and integration

Considerations

  • To ensure that visits and events are recorded, the Web SDK must be installed on all pages of your website. 
  • Place the snippet code so that it loads as early as possible in the page scope. Do so by placing the code near the top of the head tag.
  • If you are integrating the SDK using Google Tag Manager (GTM):
    • Ensure that the SDK loads once per page load.
    • Set the SDK to load as soon as the page loads using GTM prioritization.
  • You can implement the web SDK with or without Smart Banners. Follow the appropriate instructions in the sections that follow.

Prerequisites

  • Get the Web SDK Web Dev Key. Note! This is not the same key used by mobile apps.
    • To get the Web Dev Key: 
      1. In AppsFlyer, go to the My Apps tab.
      2. Click View brand bundles.
      3. Copy the required Web Dev Key.
  • If you implement Smart Banners, get the Smart Banner key. 
    • To get the Smart Banner Key:
      1. In AppsFlyer, go to Engagement & Deep LinkingSmart Banners.
      2. Copy the required Smart Banner Key
  • Permissions to add scripts to head tags on the website.
  • If you use Google Tag Manager, it must be integrated into the website.

Proceed to integrate web SDK by using one of the following options. 

Native  Google Tag Manager  Adobe Launch Tag Manager 

JavaScript code snippet

Integrate the web SDK using one of the following methods. 

To install the Web SDK without Smart Banners:

  1. Repeat the procedure that follows on all pages in your website.
  2. In the code snippet, that follows, replace the WEB_DEV_KEY  using the key specified in the prerequisites.
  3. Paste the code snippet, in the head tag on your website. Paste it near the top of the head tag.
<script>
!function(t,e,n,s,a,c,i,o,p){t.AppsFlyerSdkObject=a,t.AF=t.AF||function(){
(t.AF.q=t.AF.q||[]).push([Date.now()].concat(Array.prototype.slice.call(arguments)))},
t.AF.id=t.AF.id||i,t.AF.plugins={},o=e.createElement(n),p=e.getElementsByTagName(n)[0],o.async=1,
o.src="https://websdk.appsflyer.com?"+(c.length>0?"st="+c.split(",").sort().join(",")+"&":"")+(i.length>0?"af_id="+i:""),
p.parentNode.insertBefore(o,p)}(window,document,"script",0,"AF","pba",{pba: {webAppId: "WEB_DEV_KEY"}})
</script>

To implement the Web SDK with Smart Banners:

  1. Repeat the procedure that follows on all pages in your website.
  2. In the code snippet, that follows, replace the WEB_DEV_KEY and YOUR_BANNER_KEYusing the keys specified in the prerequisites.
  3. Paste this code snippet, in the head tag of the website. Paste it near the top of the head tag.
<script>
!function(t,e,n,s,a,c,i,o,p){t.AppsFlyerSdkObject=a,t.AF=t.AF||function(){
(t.AF.q=t.AF.q||[]).push([Date.now()].concat(Array.prototype.slice.call(arguments)))},
t.AF.id=t.AF.id||i,t.AF.plugins={},o=e.createElement(n),p=e.getElementsByTagName(n)[0],o.async=1,
o.src="https://websdk.appsflyer.com?"+(c.length>0?"st="+c.split(",").sort().join(",")+"&":"")+(i.length>0?"af_id="+i:""),
p.parentNode.insertBefore(o,p)}(window,document,"script",0,"AF", "pba,banners",{pba: {webAppId: "WEB_DEV_KEY"}, banners: {key: "YOUR_BANNER_KEY"}});
AF('banners', 'showBanner');
</script>

Ensure that the SDK is working

Once installed verify that the AppsFlyer websdk is called by the visitor's browser and that messages are sending. This is done by examining the message network connection reported in the browser.

To ensure that the SDK loads and is working:

  1. Go to the website.
  2. Open the browser developer tools. WebSDK.jpg
  3. Go to the (A) Network tab. 
  4. Refresh the page.
  5. Filter by (B) appsflyer
  6. Select the (C) message event. 
  7. In the headers tab, (D) ensure that :
    • Request URL  is wa.appsflyer.com/message.
    • site_id query parameter= WEB_DEV_KEY.
    • The status code is 200.
  8. Ensure that the SDK loads only once. Multiple SDK loading can cause the SDK to stop functioning.

Principles of event recording

Conversion and standard events

  • User events are recorded by the SDK, which sends the event to the AppsFlyer platform.
  • Using the conversion events list set by the marketer, AppsFlyer splits the events into standard and conversion events.
  • Conversion event data is available in PBA dashboards.
  • Conversion and standard event data are available in raw data reports.

Conversion events

  • Conversion events provide insights into your marketing and business efforts. Conversion events include purchases, downloads, signups, and subscriptions.
  • PBA attributes conversion events to the media source that drove the user to visit the website.
  • By identifying the attributed media source, you can measure and differentiate the quality of users brought by different media sources.
  • Conversion events are used to record revenue and calculate ROI.
  • Use them to compare the budget of ads for specific media sources against the revenue generated from the users that come from these media sources.

Standard events

  • Standard events are used to validate the user journey and funnels that lead to conversions.
  • Use them to measure user activity and highlight media sources that bring engaged users.
  • Record user activity to mark users for re-engagement campaigns.

Recording events

Trigger the web SDK to record events when certain conditions are met, for example, when a landing page loads or when users interact with website elements. See examples of recording events.

Identifying users using customer user ID (CUID)

  • Web users are identified in AppsFlyer by using the unique CUID you allocate them. Typically the CUID is managed by your backend servers. 
  • Use the same CUID value you use in the mobile environment. Doing so enables you to have a holistic view of user activity across multiple platforms. The function in the mobile SDK is setCustomerUserId function (iOS, Android, Unity).
  • To set the CUID in the web SDK:
    • Wait for the user to identify via login or sign up.
    • Fire the JavaScript call to setCustomerUserId() as shown in the example that follows. 
      Note! Send the CUID as a string even if it is a number. Do so enclosing it in quotation marks.
  • If you implement web S2S, consider that you may need to notify PBA when you associate a CUID with a web visitor id in your backend. 
  • CUIDs must not contain directly identifiable personal information such as a phone number or email address.
Example - setting the CUID
// Associate all current user web events to distinct ID 663274 
AF('pba', 'setCustomerUserId' , '663274')

Web SDK event parameters

Parameter name Mandatory Description
eventType Yes

Event type

Format: String

Always populate this parameter with EVENT.

Example: eventType: "EVENT"

eventName Yes

Event name

Format: String

Example: Purchase, Subscription

eventCategory No

Event grouping

Format: String

Example: New year promo, Back to school

eventLabel No

Flexible client data labeling, useful for passing product id, A/B testing etc.
This data is available in the raw data reports. 

  • The event label parameter accepts strings and not objects. It is not like the event value parameter in the mobile SDK which accepts a map of key-value pairs.
  • Use this parameter for labeling purposes rather than sending rich in-app events

Format: String

eventRevenue No

Revenue assigned to a conversion event

Format: Float

eventRevenueCurrency No

Revenue currency

  • 3 character ISO 4217 currency code
  • Default: USD

Format: String

eventValue No
Map of event parameters describing the event. Use this parameter to send rich in-app events like product SKU, line item price. 
Format: JSON

Example: To send SKU ABC123, having blue color and a unit price of $3.99

{"sku": "ABC123", “color": "blue", "unit_price":3.99,"currency": "USD"} 

Limitation: 1000 characters. Do not exceed this it will be truncated. 

Recording event scenarios

Example event

// purchase event of shoes with associated revenue
AF('pba', 'event', {eventType: 'EVENT', eventName: 'purchase', eventLabel: 'shoes', eventRevenue: 12, eventValue: {"key1": 123, "key2": "name"}});

The events that you send depend on the nature of your web app. For example, an online store app requires a set of events that differ from that of a news outlet. See the scenarios that follow to get a sense of the events you should and send and when.

Online store

Suppose you are managing an online store. Some standard events that you might want to record would be: 

  • Search: standard event
  • Add to cart: standard event
  • Remove from cart: standard event
  • Purchase: conversion event

News outlet

Suppose you are managing a new outlet. Some events that you might want to record would be:

  • Signup: conversion event
  • Purchase subscription: conversion event

Ensuring that events are sent

This part is intended for web developers.

To ensure that events are sent to AppsFlyer:

  1. Open the website.
  2. Open the browser developer tools.
  3. Switch to the network tab.
  4. Trigger the event.
  5. Filter by message.
    pba_af_event.png
  6. Look for a network request that starts with destination wa.appsflyer.com (see screenshot below).
  7. Ensure that:
    1. The status code is 200.
    2. The Request Payload aligns with the parameters in the event.

Examples

Recording events

The code provided is for illustrative purposes only. Don't use this code as-is. 

  • Assumptions: The Web SDK is already loaded by the page by the time the event is sent.
  • The example scenarios contain the code for recording events when: 
    • a landing page loads.
    • users interact with the website.
Native event recording Tag Manager event recording

Recording events when a landing page loads

  • You have a subscription page for newsletters and want to record subscriptions.
  • You can also set up a thank you page and redirect users to it after they subscribe.
<html>
    <head>
        <!-- Assume that the server returns a response with details about the newly subscribed user -->
        <!-- Alternatively, you can extract data from localstorage or cookies,
            in case data was set in either of them during the subscription process
        -->
        <script>window.onload = function(){
            AF('pba', 'event', {eventType: 'EVENT', eventCategory: 'conversion',eventName: 'subscription', eventLabel: 'newsletters'});
        }
        </script>
    </head>
    <body>
        <h1>Thank You for Subscribing to Our Newsletter</h1>
    </body>
</html>
  • The preceding code contains a basic HTML page. The web page needs to load the Web SDK in order for you to send events.
  • Once the page loads, after the user is redirected to it, the window loading method calls the AF() method to send the subscription event to AppsFlyer.

Recording events when users interact with the website

  • You have an eCommerce website and want to record checkout events.
  • When the user clicks on the checkout button, the Web SDK sends an event to AppsFlyer.
<html>
<head>
    <!-- Assume that data about products in the shopping cart
    is stored in localstorage -->
    <script>
        window.onload = function () {
            document.getElementById('checkout').addEventListener('click', function () {
                AF('pba', 'event', {eventType: 'EVENT',eventCategory: 'conversion', eventName: 'checkout'});
            });
        }
    </script>
</head>
<body>
    <h1>Shopping Cart</h1>
    <h2>Shirt</h2>
    <p>
        <ul>
            <li>Color: Blue</li>
            <li>Quantity: 2</li>
            <li>Price: $20</li>
        </ul>
    </p>
    <h2>Pants</h2>
    <p>
        <ul>
            <li>Color: Black</li>
            <li>Quantity: 3</li>
            <li>Price: $15</li>
        </ul>
    </p>
    <button id='checkout'>Checkout</button>
</body>
</html>

The preceding code above shows a basic HTML page. The web page needs to load the Web SDK in order for you to send events.

  • Once the page loads, it binds a click listener to the Checkout button.
  • When the user clicks the Checkout button the callback function:
    • fetches data from localstorage.
    • calls the AF() method and passes data to it.
  • The AF() method sends the event to AppsFlyer.
  • Make sure the web SDK functions tag is loaded before the event is fired.
  • Don't send special characters in event values, like currency symbols in revenue value.
  • Value strings should be shorter than 50 characters.

Setting customer user ID after signup

The code provided in these examples is for reference only. Do not use this code as-is. If you are not sure how to use this code, consult your web developer. 

Assumption: The Web SDK is loaded by the page before the event is sent; don't load the SDK again.

User scenario:

  • A user signs up to your website.
  • The website code gathers the user details and sends it to your server.
  • The server generates a unique CUID for the user.
  • In the thank you page after signup, you query the server for the new CUID.
  • Using the server response, you set AppsFlyer CUID using the Web SDK setCustomerUserId() method.
Native Google Tag Manager

Set up a signup page:

<html>
<head>
    <!-- The Web SDK script loads first -->
    <script>
!function(t,e,n,s,a,c,i,o,p){t.AppsFlyerSdkObject=a,t.AF=t.AF||function(){
(t.AF.q=t.AF.q||[]).push([Date.now()].concat(Array.prototype.slice.call(arguments)))},
t.AF.id=t.AF.id||i,t.AF.plugins={},o=e.createElement(n),p=e.getElementsByTagName(n)[0],o.async=1,
o.src="https://websdk.appsflyer.com?"+(c.length>0?"st="+c.split(",").sort().join(",")+"&":"")+(i.length>0?"af_id="+i:""),
p.parentNode.insertBefore(o,p)}(window,document,"script",0,"AF","pba",{pba: {webAppId: "WEB_DEV_KEY"}})
    </script>
    <script>
        };
    // This function stores the user email sent to the server after the user reaches the thank you page
    // The response from the server is a unique CUID that should be set using the web SDK setCustomerUserId method
        function storeUserEmail (){
            var userEmail = document.getElementById('email').value;
            localStorage.setItem('user_email', userEmail);
        }
    </script>
</head>
<body>
    <h1>Sign Up</h1>
    <form onsubmit="storeUserEmail()" action="/signup" method="post">
        <div><label>Name</label>
            <input type="text" name="name" id="name"></div>
        <br />
        <div> <label>Email</label>
            <input type="email" name="email" id="email"></div>
        <br />
        <input type="submit" id="submit">
    </form>
</body>
</html>

The preceding code above is a simple signup form. When the form is submitted, the email is stored in localStorage. When the user reaches the thank you page, the user email address is sent to the server to generate the unique CUID for the email address.

Set up a thank you page for users who sign up:

<html>
<head>
    <script>
!function(t,e,n,s,a,c,i,o,p){t.AppsFlyerSdkObject=a,t.AF=t.AF||function(){
(t.AF.q=t.AF.q||[]).push([Date.now()].concat(Array.prototype.slice.call(arguments)))},
t.AF.id=t.AF.id||i,t.AF.plugins={},o=e.createElement(n),p=e.getElementsByTagName(n)[0],o.async=1,
o.src="https://websdk.appsflyer.com?"+(c.length>0?"st="+c.split(",").sort().join(",")+"&":"")+(i.length>0?"af_id="+i:""),
p.parentNode.insertBefore(o,p)}(window,document,"script",0,"AF","pba",{pba: {webAppId: "WEB_DEV_KEY"}})
    </script>
    <script>
        // Using the fetch API to send the user email to the server
        // and get the unique user id in return	
        window.onload = function () {
            var userEmail = localStorage.getItem('user_email');
            fetch('users/' + userEmail).then(function (res) {
                   res.text().then(function (id) {
                    console.log(id);
                    AF('pba', 'setCustomerUserId', id);
                });
            });
        }  </script> 
     </head> 
     <body> 
        <h1>Thank You for Signing Up!</h1> 
     </body> 
</html>

The code makes use of the fetch API. It sends the server the email address entered by the user. Assuming that the server creates a user with a unique CUID upon signup, sending the email address to the server is for the purpose of receiving a unique CUID. The server responds with a unique CUID and this unique CUID is the value that is passed with the setCustomerUserId method.

The setCustomerUserId function can be sent at any stage in the user flow, for example, after user login and signup. AppsFlyer uses the most recent CUID sent to update the current observed user for past or future touchpoints and events.

Use the same CUID value as you do in the setCustomerUserd function in the mobile app (see mobile setCustomerUserId for: iOS, Android, Unity)

Release notes and deprecations

Release notes

Web SDK release notes
Date  Version Notes
 2020-04-16 1.0  The customerUserId() function replaces the IDENTIFY event for sending the unique CUID

Deprecations

  • A deprecation notice provides a heads up of our intention to stop supporting a feature or method. The feature or method continues to work until its sunset date.
  • Regard deprecation notices as an opportunity to make changes to your code.
Deprecations

Deprecation date

Sunset date Details
2020-04-16 To be announced

Deprecated method: Sending the customer user ID (CUID) in the event parameter customUserid with the eventType set to "IDENTIFY" 

Current method: Send the CUID using the setCustomerUserId() function. 

Was this article helpful?