Initial SDK Setup

Integrating the Appboy SDK will provide you with basic analytics functionality as well as in-app messages with which you can engage your users.

Time Estimate: 10-15 Minutes

Step 1: Integrate the Appboy Library

To integrate the Appboy Web SDK, simply follow the instructions in the “Getting Started” section of the Appboy Web SDK Github Repository. Be sure to substitute the API key found within the App Settings page of the Appboy dashboard for YOUR-API-KEY-HERE. For more detailed technical documentation, refer to the complete JSDocs.

Error Logging

To enable logging, you can pass the option enableLogging: true to your initialize function (or call appboy.toggleAppboyLogging() after initialization), which will cause Appboy to log to the javascript console. This is useful for development but is visible to all users, so you should remove this option or provide an alternate logger with appboy.setLogger() before you release your page to production.

Tag Managers

Google Tag Manager

Appboy has been tested with Google Tag Manager. Follow the standard installation instructions, but instead of placing the Web SDK initialization HTML/JavaScript code in your header, place it within a new Custom HTML-type tag in Google Tag Manager: Screenshot of GTM setup

Please note the tag must fire in order for Appboy to work in any capacity on your site.

Tealium iQ

Tealium iQ offers a basic turnkey Appboy integration. To configure the integration, just search for Appboy in the Tealium Tag Management interface, and provide the Web SDK API key from your dashboard: Tealium dashboard

For more details, or in-depth Tealium configuration support, please reach out to your Tealium account manager.

Other Tag Managers

Appboy may also be compatible with other tag management solutions. Please reach out to the Success Squad if you need help evaluating these solutions.

Push Notifications

Integration

A push notification is an alert that appears on the user’s screen when an important update occurs. Push notifications can be received even when your web page is not currently open in the user’s browser. Push notifications are a valuable way to provide your users with time-sensitive and relevant content or to re-engage them with your site.

Sample push notification:

Sample Push

Check out Appboy Academy for additional best practices.

Web push notifications are implemented using the W3C Push standard, which browsers are in the process of supporting. Currently, the browsers which support web push are Chrome (on the Desktop and Android) and Firefox; it’s expected that as the standard becomes more widely adopted other browsers will implement support as well. Additionally, desktop Safari (on Mac OS X) has a custom web push solution based on Apple Push Notification Services; Appboy supports these Safari notifications as well.

HTTPS Requirement

Web standards require that the domain requesting push notification permission be secure.

What defines a secure site?

A site is deemed secure if it matches one of the following secure origin patterns:

  • (https, , *)
  • (wss, *, *)
  • (, localhost, )
  • (, .localhost, *)
  • (, 127/8, )
  • (, ::1/128, *)
  • (file, *, —)
  • (chrome-extension, *, —)

This is a security requirement in the open standards specification that Appboy Web Push is built on, and prevents man-in-the-middle attacks.

What if a secure site is not available?

While industry best practice is to make your whole site secure, customers who cannot secure their site domain can work around the requirement by using a secure modal. Appboy has prepared an example of this approach.

Time Estimate: 7 Minutes

Step 1: To Support Chrome, Enable FCM/GCM

  1. If you do not already have a Google API project with FCM or GCM messaging enabled, follow these instructions to create an API project and Enable the Firebase Cloud Messaging (FCM) Service.

  2. Within the Firebase dashboard within the “Cloud Messaging” tab of the Project Settings page please note the “Server Key” as well as your “SenderID”

Firebase Console Server Key and Sender ID Location

Note: Please ensure that you do not restrict access to your FCM/GCM Server Key to specific IP ranges. This will allow any IP to utilize your FCM/GCM API Key so Appboy can send push notifications appropriately.

Step 2: Configure your Site

Once you have set up your Google API project, it is time to configure your site.

  • Add <link rel="manifest" href="/manifest.json" /> in your <head> section
  • Create a manifest.json file with the content below, and place it in the root directory of your website:

    {
      "gcm_sender_id": "YOUR_FCM_OR_GCM_SENDER_ID"
    }
    
  • Create a service-worker.js file and place it in the root directory of your website. Give it the same content as https://js.appboycdn.com/web-sdk/latest/service-worker.js

Step 3: Browser Registration

In order for a browser to receive push notifications, you must register it for push by calling appboy.registerAppboyPushMessages(). Note that this will immediately request push permission from the user. Refer to Chrome’s best practices for user experience guidance on when to call this method. If you wish to show your own push-related UI to the user before requesting push permission (known as a soft push prompt), note that you can test to see if push is supported in the user’s browser with appboy.isPushSupported(). See below for a soft push prompt example using Appboy In-App Messages. If you wish to unsubscribe a user, you can do so by calling appboy.unregisterAppboyPushMessages().

Step 4: Set your GCM/FCM Server API Key and SenderID on the Appboy Dashboard

  1. On the app settings page (where your API keys are located), select your Web app.
  2. Enter your GCM/FCM Server API Key in the field labeled Cloud Messaging API Key under the Push Notifications section.
  3. Insert your GCM/FCM SenderID in the field labeled Cloud Messaging Sender ID.

FCM/GCM Keys and SenderID Input

Step 5: Configure Safari Push

If you wish to support push notifications for Safari on Mac OS X, follow these additional instructions:

  • Generate a Safari Push Certificate following these “Registering with Apple” instructions
  • In the Appboy dashboard, on the app settings page (where your API keys are located), select your Web app. Click “Configure Safari Push” and follow the instructions, uploading the push certificate you just generated.
  • When you call appboy.initialize supply the optional safariWebsitePushId configuration option with the Website Push ID you used when generating your Safari Push Certificate, for example appboy.initialize('YOUR-API-KEY', {safariWebsitePushId: 'web.com.example.domain'})

Common Issues

  1. I followed the integration instructions but I’m still not receiving any push notifications.
    • Not all browsers can receive push messages. Please ensure that appboy.isPushSupported() returns true in the browser.
    • Note that if a user has denied a site push access, they won’t be prompted for permission again unless they remove the denied status from their browser preferences.
    • Note that web push notifications require that your site be https.

Soft Push Prompts

It’s often a good idea for sites to implement a “soft” push prompt where you “prime” the user and make your case for sending them push notifications before requesting push permission. This is useful because if the user denies permission, you can never ask them again. This can be done simply through Appboy’s triggered In-App Messages for a seamless user experience. Instead of calling appboy.registerAppboyPushMessages() directly as described above, instead:

  1. Create a “Prime for Push” in-app messaging Campaign on the Appboy dashboard.
    • Make it a “Modal” In-App Message. Give it whatever text and styling you wish to present to the user (“Can we stay in touch?”)
    • Give the in-app message a Button 1 Text value of “OK” (or whatever affirmative text you wish), and set the On-Click Behavior to “Close Message.” You’ll customize that behavior later.
    • Under the gear composer section, add a key/value pair. Give it a key of msg-id and a value of push-primer.
    • Give the message a trigger action of the Custom Event ‘prime-for-push’ (you can create that custom event manually from the dashboard here if you need to)
  2. In your Appboy SDK integration, find and remove any calls to appboy.display.automaticallyShowNewInAppMessages() from within your loading snippet.

  3. Replace the removed call with the following snippet:
appboy.subscribeToNewInAppMessages(function(inAppMessages) {
  var message = inAppMessages[0];
  if (message != null) {
    var shouldDisplay = true;

    if (message instanceof appboy.ab.InAppMessage) {
      // Read the key/value pair for msg-id
      var msgId = message.extras["msg-id"];

      // If this is our push primer message
      if (msgId == "push-primer") {
        // We don't want to display the soft push prompt to users on browsers that don't support push, or if the user
        // has already granted/blocked permission
        if (!appboy.isPushSupported() || appboy.isPushPermissionGranted() || appboy.isPushBlocked()) {
          shouldDisplay = false;
        }
        if (message.buttons[0] != null) {
          // Prompt the user when the first button is clicked
          message.buttons[0].subscribeToClickedEvent(function() {
            appboy.registerAppboyPushMessages();
          });
        }
      }
    }

    // Display the message
    if (shouldDisplay) {
      appboy.display.showInAppMessage(message);
    }
  }

  // Remove this message from the array of IAMs and return whatever's left
  return inAppMessages.slice(1);
});

When you wish to display the soft push prompt to the user, call appboy.logCustomEvent("prime-for-push") - if the user is eligible to subscribe to push, the push primer in-app message will be triggered, and if the user clicks the affirmative button, they’ll receive the permission request.

In-App Messaging

Time Estimate: 0-15 Minutes

In-App Messages are great for creating unobtrusive calls to action, notifying people of new content in the News Feed and driving them toward it, or communicating with users who have push turned off. They are also effective for other content that isn’t time-sensitive enough to warrant a push notification, or permanent enough to warrant a News Feed item. You can find a detailed explanation of in-app message behavior on Appboy Academy.

Integration

By default, in-app messages are automatically displayed as part of our recommended integration instructions. Additional customization can be done by following the steps in this guide.

In-App Message Types

Appboy currently offers the following default in-app message types: Slideup, Modal, and Full and HTML. Each in-app message type is customizable across content, images, icons, click actions, analytics, display, and delivery.

All in-app messages inherit their prototype from appboy.ab.InAppMessage, which defines basic behavior and traits for all in-app messages. The protypical subclasses are appboy.ab.SlideUpMessage, appboy.ab.ModalMessage, appboy.ab.FullScreenMessage, and appboy.ab.HtmlMessage.

Slideup In-App Messages

SlideUp in-app messages are so-named because traditionally on mobile platforms they “slide up” or “slide down” from the top or bottom of the screen. In the Appboy Web SDK, these messages are actually displayed as more of a Growl or Toast style notification, to align with the web’s dominant paradigm. They cover a small portion of the screen and provide an effective and non-intrusive messaging capability.

Slideup Example

Modal in-app messages appear in the center of the screen and are framed by a translucent panel. Useful for more critical messaging, they can be equipped with up to two click action and analytics enabled buttons.

Modal Example

Full In-App Messages

Full in-app messages are useful for maximizing the content and impact of your user communication. On narrow browser windows (e.g. the mobile web), full in-app messages take up the entire browser window. On larger browser windows, full in-app messages appear similarly to modal in-app messages. The upper half of a full in-app message contains an image and the lower half allows up to eight lines of text as well as up to two click action and analytics enabled buttons

Full Example

HTML In-App Messages

HTML in-app messages are useful for creating fully customized user content. User-defined HTML is displayed in an iframe and may contain rich content, such as images, fonts, videos, and interactive elements, allowing for full control over message appearance and functionality.

Note: To enable HTML in-app messages, your SDK integration must supply the enableHtmlInAppMessages initialization option to Appboy, e.g. appboy.initialize('YOUR-API_KEY', {enableHtmlInAppMessages: true}). This is for security reasons - HTML in-app messages can execute javascript so we require a site maintainer to enable them.

The following example shows a paginated HTML in-app message: HTML5 Example

In-App Message Delivery

In-App Messages (Triggered)

The following documentation refers to Appboy’s In-App Messaging product, aka “triggered in-app messages,” which are branded as highlighted below in the “Create Campaign” drop-down:

In-App Messaging Composer

You may also refer to the documentation for our deprecated Original In-App Messaging product.

Trigger Types

Our in-app message product allows you to trigger in-app message display as a result of several different event types: Any Purchase, Specific Purchase, Session Start, Custom Event, Push Click. Furthermore, Specific Purchase and Custom Event triggers can contain robust property filters.

Delivery Semantics

All in-app messages that a user is eligible for are automatically delivered to the user upon a session start event. For more information about the SDK’s session start semantics, see our session lifecycle documentation.

Minimum Time Interval Between Triggers

By default we rate limit in-app messages to once every 30 seconds to ensure a quality user experience. To override this value, you can pass the minimumIntervalBetweenTriggerActionsInSeconds configuration option to your initialize function.

// Sets the minimum time interval between triggered in-app messages to 5 seconds instead of the default 30
appboy.initialize('YOUR-API-KEY', { minimumIntervalBetweenTriggerActionsInSeconds: 5 })

Original In-App Messages (Deprecated)

The following documentation refers to Appboy’s Original In-App Messaging product, branded as highlighted below in the “Create Campaign” drop-down:

Original In-App Messaging Composer

As part of our recommended integration instructions, Appboy will automatically request and immediately display one new original in-app message in the following situations:

  • when appboy.openSession() is called, provided in-app messages have not been refreshed for this user in the last 10 minutes
  • whenever appboy.requestInAppMessageRefresh() is called

Our original in-app messages are deprecated and will be eventually removed in favor of triggered in-app messages. See our documentation about the key differences between original and triggered in-app messages, including reasons to use the latter.

Manual In-App Message Display

If you don’t want your site to immediately display new in-app messages when they’re received, you can disable automatic display and register your own display subscribers. First, find and remove the call to appboy.display.automaticallyShowNewInAppMessages() from within your loading snippet. Then, create your own subscriber:

appboy.subscribeToNewInAppMessages(function(inAppMessages) {
  // Display the first in-app message. You could defer display here by pushing this message to code within in your own application.
  // If you don't want to use Appboy's built-in display capabilities, you could alternatively pass the in-app message to your own display code here.
  appboy.display.showInAppMessage(inAppMessages[0]);

  // Return an array with any remaining, unhandled messages to appboy's internal queue.
  // These will be part of the inAppMessages param the next time this subscriber is invoked.
  return inAppMessages.slice(1);
});

The inAppMessages parameter will be an array of appboy.ab.InAppMessage subclass or appboy.ab.ControlMessage objects, each of which has various lifecycle event subscription methods. See the JSDocs for full documentation.

Note: Only one Modal or Full in-app message can be displayed at a given time. If you attempt to show a second Modal or Full message while one is already showing, appboy.display.showInAppMessage will return false, and the message will automatically be returned to Appboy’s internal queue, where it will part of the inAppMessages array parameter the next time your subscriber is invoked.

Local In-App Messages

In-app messages can also be created within your site and displayed locally in real-time. All customization options available on the dashboard are also available locally. This is particularly useful for displaying messages that you wish to trigger within the app in real-time. However, analytics on these locally-created messages will not be available within the Appboy dashboard.

  // Displays a slideup type in-app message.
  var message = new appboy.ab.SlideUpMessage("Welcome to Appboy! This is an in-app message.");
  message.slideFrom = appboy.ab.InAppMessage.SlideFrom.TOP;
  appboy.display.showInAppMessage(message);

Exit-Intent Messages

Exit-intent in-app messages appear when visitors are about to navigate away from your site. They provide another opportunity to communicate important information to users, while not interrupting their experience on your site. To be able to send these messages, first reference the open-source library with the code below, which will log ‘exit intent’ as a custom event. In-app message campaigns can then be created in the dashboard using ‘exit intent’ as the trigger custom event.

  var _ouibounce = ouibounce(false, {
    callback: function() { appboy.logCustomEvent('exit intent'); }
  });

Customization

Key/Value Pair Extras

In-app message objects may carry Key/Value pairs as their extras property. These are specified on the dashboard under “Additional Message Settings” when creating an in-app message campaign. These can be used to send data down along with an in-app message for further handling by your site. For example:

appboy.subscribeToNewInAppMessages(function(inAppMessages) {
  if (inAppMessages[0] instanceof appboy.ab.InAppMessage) {
    var extras = inAppMessages[0].extras;
    for (var key in extras) {
      if (data.hasOwnProperty(key)) {
         console.log("key: " + key + ", value: " + extras[key]);
      }
    }
  }

  appboy.display.showInAppMessage(inAppMessages[0]);
  return inAppMessages.slice(1);
});

Custom Styling

Appboy UI elements come with a default look and feel that matches the composers within the Appboy Dashboard and aims for consistency with other Appboy mobile platforms. Appboy’s default styles are defined in CSS within appboy.min.css. By overriding selected styles in your application, it is possible to customize our standard in-app message types with your own background images, font families, styles, sizes, animations, and more. For instance, the following is an example override that will cause a in-app messages’ headers to appear italicized:

  .ab-in-app-message .ab-message-header {
    font-style: italic;
  }

See the JSDocs for more information.

Troubleshooting

Troubleshooting Scenarios

Expected In-App Message Did Not Display

Most in-app message issues can be broken down into two main categories: delivery and display. To troubleshoot why an expected in-app message did not display on your device, you should first ensure that the in-app message was delivered to the device, then troubleshoot message display.

Impressions Are Lower Than Expected

Triggers take time to sync to the device on session start, so there can be a race condition if users log an event or purchase right after they start a session. One potential workaround could be changing the campaign to trigger off of session start, then segmenting off of the intended event or purchase. Note that this would deliver the in-app message on the next session start after the event has occurred.

In-App Message Delivery

The SDK requests in-app messages from Appboy’s servers on session start. To check if in-app messages are being delivered to your device, you’ll need to ensure that in-app messages are being both requested by the SDK and returned by Appboy’s servers.

Check If Messages Are Requested and Returned

  1. Add yourself as a test user on the Dashboard.
  2. Set up an in-app message campaign targeted at your user.
  3. Ensure that a new session occurs in your application.
  4. Use the Event User Logs to check that your device is requesting in-app messages on session start. Find the SDK Request associated with your test user’s session start event.
    • If your app was meant to request triggered In-App Messages, you should see trigger in the Requested Responses field under Response Data.
    • If your app was meant to request Original In-App Messages, you should see in_app in the Requested Responses field under Response Data.
  5. Use the Event User Logs to check if the correct in-app messages are being returned in the Response Data.

In-App Message

Troubleshoot Messages Not Being Requested

If your in-app messages are not being requested, your app might not be tracking sessions correctly, as in-app messages are refreshed upon session start. Also be sure that your app is actually starting a session based on your app’s session timeout semantics:

Session Start

Troubleshoot Messages Not Being Returned

If your in-app messages are not being returned, you’re likely experiencing a campaign targeting issue:

  • Your segment does not contain your user.
    • Check your user’s Engagement tab to see if the correct segment appears under Segments.
  • Your user has previously received the in-app message and was not re-eligible to receive it again.
    • Check the campaign re-eligibility settings under the Delivery tab of the Campaign Composer and make sure the re-eligibility settings align with your testing setup.
  • Your user hit the frequency cap for the campaign.
  • If there was a control group on the campaign, your user may have fallen into the control group.
    • You can check if this has happened by creating a segment with a “Received Campaign Variant” filter, where the campaign variant is set to “Control”, and checking if your user fell into that segment.
    • When creating campaigns for integration testing purposes, make sure to opt-out of adding a control group.

In-App Message Display

If your app is successfully requesting and receiving in-app messages but they are not being shown, some device-side logic may be preventing display:

  • Triggered in-app messages are rate-limited based on the minimum time interval between triggers, which defaults to 30 seconds.
  • If you have custom in-app message handling through appboy.subscribeToNewInAppMessages, check that subscription to ensure it is not affecting in-app message display.

News Feed

The News Feed is a fully customizable in-app content feed for your users. Our targeting and segmentation allows you to create a stream of content that is individually catered to the interests of each user. Depending on their position in the user life cycle and the nature of your app, this could be an on-boarding content server, an advertisement center, an achievement center, or a generic news center.

Time Estimate: 10 Minutes

Example News Feed

Sample News Feed

News Feed Integration

To toggle display of the news feed through the Appboy Web SDK, simply call

appboy.display.toggleFeed();

This will display the most recent cached news feed cards (kicking off a refresh if these cards are more than 1 minute stale, or if the news feed has never been refreshed) and will automatically update the display when new cards are received from Appboy servers for as long as it’s on the screen.

By default, the feed will be shown in a fixed-position sidebar on the right-hand side of the website (or as a full-screen overlay on mobile devices, through responsive css). If you wish to override this behavior and display a statically positioned news feed inside your own parent element, simply provide this element as the first argument to showFeed, for instance:

appboy.display.toggleFeed(document.getElementById('my-news-feed-parent'));

If you wish to display a specific static set of news feed cards, filter the cards from the server, or provide your own refresh semantics, you can disable automatic updating and supply your own cards. For instance:

appboy.subscribeToFeedUpdates(function(feed) {
  var cards = feed.cards;
  appboy.display.showFeed(undefined, cards);
});
appboy.requestFeedRefresh();

See the JSDocs for full documentation for showFeed, destroyFeed, and toggleFeed.

News Feed Customization

Appboy UI elements come with a default look and feel that matches the composers within the Appboy Dashboard and aims for consistency with other Appboy mobile platforms. Appboy’s default styles are defined in CSS within appboy.min.css. By overriding selected styles in your application, it is possible to customize our standard feed with your own background images, font families, styles, sizes, animations, and more. For instance, the following is an example override that will cause the news feed to appear 800px wide:

.ab-feed {
  width: 800px;
}

Categories

Instances of the Appboy News Feed can be configured to only receive cards from a certain “category”. This allows for effective integration of multiple news feed streams within a single application. For more information on this feature see Appboy Academy

News Feed Categories can be defined by providing the third “allowedCategories” parameter to toggleFeed:

appboy.display.toggleFeed(undefined, undefined, [appboy.ab.Card.Category.NEWS]);

You can also populate a feed with a combination of categories as in the following example:

appboy.display.toggleFeed(undefined, undefined, [appboy.ab.Card.Category.ANNOUNCEMENTS, appboy.ab.Card.Category.NEWS]);

Read/Unread Indicators

Appboy provides an Unread/Read indicator on news feed cards as pictured below:

UnreadvsRead

Disabling the Indicators

In order to disable this functionality add the following style to your css:

.ab-read-dot { display: none; }
.ab-read-indicator { display: none; }

Card Types

The Appboy Web SDK supports 3 unique news feed card types, ab.ClassicCard, ab.Banner, ab.CaptionedImage which share a base model, ab.Card.

Requesting Unread Card Count

You can request the number of unread cards at any time by calling:

appboy.getCachedFeed().getUnreadCardCount();

This is often used to power badges signifying how many unread news-feed cards there are. See the JSDocs for more information. Note that Appboy will not refresh news feed cards on new page loads (and so this function will return 0) until you show the feed or call appboy.requestFeedRefresh();

Key/Value Pairs

ab.Card objects may optionally carry key value pairs as extras. These can be used to send data down along with a card for further handling by the application. Simply call card.extras to access these values.

See the JSDocs for ab.ClassicCard, ab.Banner, or ab.CaptionedImage for more information.

Analytics

Session Tracking

The Appboy SDK reports session data that is used by the Appboy dashboard to calculate user engagement and other analytics integral to understanding your users. Based on the below session semantics, our SDK generates “start session” and “close session” data points that account for session length and session counts viewable within the Appboy Dashboard.

Session Lifecycle

By default, sessions begin when appboy.openSession() is first called and remain open until there are at least 30 minutes of inactivity. This means that if the user navigates away from the site and then returns less than 30 minutes later, the same session will be continued. If they return after the 30 minutes have expired, a “close session” datapoint is automatically generated for the time at which they navigated away, and a new session opens.

Note: If you need to force a new session, you can do so by changing users.

Customizing Session Timeout

To customize the session timeout, pass the the sessionTimeoutInSeconds option to your initialize function.

// Sets the session timeout to 15 minutes instead of the default 30
appboy.initialize('YOUR-API-KEY-HERE', { sessionTimeoutInSeconds: 900 });

If you have set a session timeout, then the above session semantics all extend to that customized timeout.

Testing Session Tracking

To detect sessions via your user, find your user on the dashboard and navigate to “App Usage” on the user profile. You can confirm that session tracking is working by checking that the “Sessions” metric increases when you would expect it to.

test_session

Setting User IDs

User IDs should be set for each of your users. These should be unchanging and accessible when a user opens the app. A database ID or a hashed email address/username is usually a good reference to use. We strongly recommend providing this identifier as it will allow you to:

  • Track your users across devices and platforms, improving the quality of your behaviorial and demographic data.
  • Import data about your users using our User Data API.
  • Target specific users with our Messaging API for both general and transactional messages.

Note: If such an identifier is not available, Appboy will assign a unique identifier to your users, but you will lack the capabilities above. You should avoid setting User IDs for users for whom you lack a unique identifier that is tied to them as an individual. Passing a device identifier offers no benefit versus the automatic anonymous user tracking Appboy offers by default.

Note: These User IDs should be private and not easily obtained (e.g. not a plain email address or username).

Time Estimate: 2 Minutes

You should make the following call as soon as the user is identified (generally after logging in) in order to set the user id:

appboy.changeUser(YOUR_USER_ID_STRING);

Note: Do not call changeUser() when a user logs out. Setting changeUser() to a static default value will associate ALL user activity with that default “user” until the user logs in again. Additionally, we recommend against changing the user ID when a user logs out, as it makes you unable to target the previously logged-in user with reengagement campaigns. If you anticipate multiple users on the same device, but only want to target one of them when your app is in a logged out state, we recommend separately keeping track of the user ID you want to target while logged out and switching back to that user ID as part of your app’s logout process.

Refer to the changeUser documentation for more information.

Automatic Preservation of Anonymous User History

Identification Context Preservation Behavior
User has not been previously identified Anonymous history is merged with user profile upon identification
User has been previously identified in-app or via API Anonymous history is not merged with user profile upon identification

Additional Notes and Best Practices

Please note the following:

  • If your app is used by multiple people, you can assign each user a unique identifier to track them.
  • Once a user ID has been set, you cannot revert that user to an anonymous profile
  • Do Not change the user ID upon a user “log out”.
    • Doing so separates the device from the user profile. You will be unable to target the previously logged out user with re-engagement messages. If you anticipate multiple users on the same device, but only want to target one of them when your app is in a logged out state, we recommend separately keeping track of the user ID you want to target while logged out and switching back to that user ID as part of your app’s logout process. By default, only the last user that was logged in will receive push notifications from your app.
    • When you request the user switch, the current session for the previous user is automatically closed and a new session is started. Furthermore, Appboy will automatically make a data refresh request for the news feed, slideup and other Appboy resources for the new user.
  • Note: If you opt to use a hash of a unique identifier as your userID take care to ensure that you’re normalizing the input to your hashing function.
    • e.g. If you’re going to use a hash of an email address, ensure that you’re stripping leading and trailing whitespace from the input.

Tracking Custom Events

You can record custom events in Appboy to learn more about your app’s usage patterns and to segment your users by their actions on the dashboard.

Before implementation, be sure to review examples of the segmentation options afforded by Custom Events vs. Custom Attributes vs Purchase Events in our Best Practices section.

Time Estimate: 2 Minutes

appboy.logCustomEvent(YOUR_EVENT_NAME);

See the logCustomEvent documentation for more information.

Adding Properties

You can optionally add metadata about custom events by passing a properties object with your custom event.

Properties are defined as key-value pairs. Keys are strings and values can be string, numeric, boolean, or Date objects.

appboy.logCustomEvent(YOUR_EVENT_NAME, {key: 'value'});

See the logCustomEvent documentation for more information.

Setting Custom Attributes

Appboy provides methods for assigning attributes to users. You’ll be able to filter and segment your users according to these attributes on the dashboard.

Before implementation, be sure to review examples of the segmentation options afforded by Custom Events vs. Custom Attributes vs Purchase Events in our Best Practices section.

Time Estimate: 5 Minutes

To assign attributes to your users, call the appboy.getUser() method to get a reference to the current user of your app. Once you have a reference to the current user, you can call methods to set predefined or custom attributes.

Appboy provides predefined methods for setting the following user attributes within the ab.User class:

  • First Names
  • Last Names
  • Biographical Strings
  • Country
  • Date of Birth
  • Email
  • Avatar Image URLs for Appboy User Profiles
  • Gender
  • Home City
  • Phone Number

We strongly recommend collecting email addresses even if you’re not sending emails through Appboy. Email makes it easier to search for individual user profiles and troubleshoot issues as they arise.

Implementation Examples

Setting a first name

appboy.getUser().setFirstName("SomeFirstName");

Setting a gender

appboy.getUser().setGender(appboy.ab.User.Genders.FEMALE);

Setting a date of birth

appboy.getUser().setDateOfBirth(2000, 12, 25);

Assigning Custom User Attributes

In addition to our predefined user attribute methods, Appboy also provides custom attributes to track data from your applications. Appboy Custom Attributes can be set with the following data types:

  • Strings
  • Arrays
    • Includes methods to set arrays, add items to existing arrays, and delete items from existing arrays.
  • Integers
  • Booleans
  • Dates
  • Longs
  • Floats

Full method specifications for custom attributes can be found here within the ab.User class JSDocs.

Implementation Examples

Setting a Custom Attribute with a String Value

appboy.getUser().setCustomUserAttribute(
  YOUR_ATTRIBUTE_KEY_STRING,
  YOUR_STRING_VALUE
);

Setting a Custom Attribute with an Integer Value

appboy.getUser().setCustomUserAttribute(
  YOUR_ATTRIBUTE_KEY_STRING,
  YOUR_INT_VALUE
);

// Integer attributes may also be incremented using code like the following
appboy.getUser().incrementCustomUserAttribute(
  YOUR_ATTRIBUTE_KEY_STRING,
  THE_INTEGER_VALUE_BY_WHICH_YOU_WANT_TO_INCREMENT_THE_ATTRIBUTE
);

Setting a Custom Attribute with a Date Value

appboy.getUser().setCustomUserAttribute(
  YOUR_ATTRIBUTE_KEY_STRING,
  YOUR_DATE_VALUE
);

// This method will assign the current time to a custom attribute at the time the method is called
appboy.getUser().setCustomUserAttribute(
  YOUR_ATTRIBUTE_KEY_STRING,
  new Date()
);

// This method will assign the date specified by secondsFromEpoch to a custom attribute
appboy.getUser().setCustomUserAttribute(
  YOUR_ATTRIBUTE_KEY_STRING,
  new Date(secondsFromEpoch * 1000)
);

Note: Dates passed to Appboy with this method must be javascript Date objects.

Setting a Custom Attribute with an Array Value

Note: The maximum number of elements in Custom Attribute Arrays defaults to 25. The maximum for individual arrays can be increased to up to 100 in the Appboy Dashboard, under “Manage App Group -> Custom Attributes”. Arrays exceeding the maximum number of elements will be truncated to contain the maximum number of elements. For more information on Custom Attribute Arrays and their behavior, see our Documentation on Arrays.

appboy.getUser().setCustomAttribute(YOUR_ATTRIBUTE_KEY_STRING, YOUR_ARRAY_OF_STRINGS);

// Adding a new element to a custom attribute with an array value
appboy.getUser().addToCustomAttributeArray(YOUR_ATTRIBUTE_KEY_STRING, "new string");

// Removing an element from a custom attribute with an array value
appboy.getUser().removeFromCustomAttributeArray("custom_attribute_array_test", "value to be removed");

Unsetting a Custom Attribute

Custom Attributes can be unset by setting their value to null.

appboy.getUser().setCustomUserAttribute(YOUR_ATTRIBUTE_KEY_STRING, null);

Setting a Custom Attribute via the REST API

You can also use our REST API to set user attributes. To do so refer to the User API documentation.

Custom Attribute Length

Custom attribute keys and values have a maximum length of 255 characters. See the full technical documentation for complete details around valid custom attribute values.

Setting Up User Subscriptions

To set up a subscription for your users (either email or push), call the functions setEmailNotificationSubscriptionType() or setPushNotificationSubscriptionType(), respectively. Both of these functions take the enum type ‘appboy.ab.User.NotificationSubscriptionTypes’ as arguments. This type has three different states:

Subscription Status Definition
OPTED_IN Subscribed, and explicitly opted in
SUBSCRIBED Subscribed, but not explicitly opted in
UNSUBSCRIBED Unsubscribed and/or explicitly opted out

Note: When a user is registered for push, the browser forces them to choose to allow or block notifications, and if they choose to allow push, they are set OPTED_IN by default. For more information on implementing subscriptions and explicit opt-ins, visit the topic on Appboy Academy.

Sample Code

Unsubscribing a user from email:

appboy.getUser().setEmailNotificationSubscriptionType(appboy.ab.User.NotificationSubscriptionTypes.UNSUBSCRIBED);

Unsubscribing a user from push:

appboy.getUser().setPushNotificationSubscriptionType(appboy.ab.User.NotificationSubscriptionTypes.UNSUBSCRIBED);

Logging Purchases

Record in-app purchases so that you can track your revenue over time and across revenue sources, as well as segment your users by their lifetime value.

Appboy supports purchases in multiple currencies. Purchases that you report in a currency other than USD will be shown in the dashboard in USD based on the exchange rate at the date they were reported.

Before implementation, be sure to review examples of the segmentation options afforded by Custom Events vs. Custom Attributes vs Purchase Events in our Best Practices section.

Time Estimate: 3-5 Minutes

To use this feature, add this method call after a successful purchase in your app:

appboy.logPurchase(productId, price, "USD", quantity);

See the JSdocs for more information. Quantity must be less than or equal to 100.

Adding Properties

You can add metadata about purchases by passing an object of key-value pairs with your purchase information. Keys are string objects and values can be string, numeric, boolean, or Date objects.

appboy.logPurchase(productId, price, "USD", quantity, {key: "value"});

See the Jsdocs for more information.

REST API

You can also use our REST API to record purchases. Refer to the User API documentation for details.

Location Tracking

The Appboy Web SDK does not currently do any automatic GPS-based location tracking. To set a user’s last known location yourself, you can use

appboy.getUser().setLastKnownLocation(latitude, longitude, accuracy, altitude, altitudeAccuracy);

See the JSDocs for more information.

Additionally, when the Web SDK sends data to Appboy servers, the user’s country will be automatically detected from their IP Address if it has not been manually set by your application.