React Native plugin integration

At a glance: Integrate AppsFlyer SDK into iOS/Android apps developed with React Native to measure installs, in-app events, media sources, and more.

 Related reading

For a complete picture of working with the React Native plugin in AppsFlyer, be sure to read these articles:

Integration

After you implement and initialize the React Native plugin, you'll see two installs in your app's AppsFlyer dashboard—one organic, the other non-organic.

Install the plugin

These instructions apply to apps that support auto-linking. The plugin uses auto-linking from:

  • React Native v0.60
  • react-native-appsflyer v1.4.7

If your app doesn't support auto-linking, see this installation guide.

To install the plugin:

  1. Download the library from npm:
    $ npm install react-native-appsflyer --save
  2. Run the relevant set of commands: Android or iOS
Android iOS
$ react-native run-android

Implement and initialize the plugin

This section describes how to implement and initialize the React Native plugin.

Retrieve your dev key

Your AppsFlyer dev key is unique and identifies your account. Its use is mandatory as it allows the SDK to securely send and retrieve data belonging to your AppsFlyer account. Only an admin user can retrieve the dev key.

To retrieve a dev key:

  1. Go to the AppsFlyer platform.
  2. In the menu bar, go to Configuration and click App settings.
  3. Under SDK installation, copy the dev key shown in the field.

Initialize the plugin

To initialize the plugin:

  1. In app.js, import the following:
    import appsFlyer from 'react-native-appsflyer';
  2. Call the initSDK method using these parameters:
Parameter Type Description
options Object SDK configuration
onSuccess Function Returns callback object
onError Function Returns callback object

Options

Name Type Default Description
devKey string   AppsFlyer dev key
appId string   [iOS only] Apple Application ID
isDebug boolean false [Optional] Debug mode

Example: Initialize the plugin

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import appsFlyer from 'react-native-appsflyer';

appsFlyer.initSdk(
  {
    devKey: 'K2***********99',
    isDebug: false, // set to true if you want to see data in the logs 
    appId: '4*******4', // iOS app id
  },
  (result) => {
    console.log(result);
  },
  (error) => {
    console.error(error);
  }
);

Test installs

You've built your app, now it's time to test the plugin. For testing scenarios and instructions, see SDK integration testing.

Core APIs

Measure the quality of your users by recording in-app events and revenue, and give them a better user experience with deep linking.

This tab has instructions for developers, but marketer input is essential as they:

  • Decide which in-app events need to be recorded to measure user quality.
  • Access AppsFlyer dashboards to set up OneLink for deep linking.

Record in-app events

Recommended practice! Define the events you want to record.

In-app events offer insight into app activities. For example, record in-app events to measure KPI such as ROI (Return on Investment) and LTV (Lifetime Value).

There are several ways to record in-app events; this article sets out the most common way which is to send events via the SDK. The In-app events overview guide details other ways to record in-app events.

If an app belongs to a certain vertical such as travel, gaming, eCommerce, etc., then see the full list of recommended in-app events per vertical.

Names and parameters

To record in-app events, use this list of recommended event names and parameters.

Recommended practice! Use event names and parameters for the following reasons:

  • Standard naming: AppsFlyer can automatically map events to SRNs such as Facebook, Google, Twitter, and Snapchat.
  • Backward compatibility: No issue arises if AppsFlyer changes an event name or parameter as your implementation is backward compatible.

Record in-app events

Use the logEvent method to record in-app events.

logEvent Parameters

Parameter Type Description
eventName String Custom event name is presented in your dashboard.
See the event list here.
eventValue Object Event details

Example

const eventName = "af_add_to_cart";
const eventName = "af_add_to_cart";
const eventValues = {
  af_content_id: "id123",
};
appsFlyer.logEvent(
  eventName,
  eventValues,
  (res) => {
    console.log(res);
  },
  (err) => {
    console.error(err);
  }
);

Record revenue

Send revenue with any in-app event by using the af_revenue event parameter.

  • Populate af_revenue with any numeric value, positive or negative.
  • af_revenue is the only event parameter considered as real revenue in raw data reports and on the dashboard. Click here for more details.

Learn more about currency settings, display, and currency conversion.

Consider these currency code factors when sending events with revenue:

  • Default currency: USD
  • Set currency codes as a 3 character ISO 4217 code.
  • Revenue values cannot contain comma separators, currency symbols, or text.
    Example revenue event: 1234.56

Example: Record an in-app event with revenue

const eventName = "purchase";
const eventValues = {
   "af_content_id": "id123",
   "af_currency":"USD",
   "af_revenue": "2"
};

 appsFlyer.logEvent(eventName, eventValues, (error, result) => {
   if (error) {
     console.error(error);
   } else {
     //...
   }
 });

Record negative revenue

Sometimes it is necessary to record negative revenue, such as when giving a user a refund on a purchase.

const eventName = "refund";
const eventValues = {
   "af_content_id": "id123",
   "af_currency":"USD",
   "af_revenue": "-2" // The revenue value is preceded by a minus sign.
};

 appsFlyer.logEvent(eventName, eventValues, (error, result) => {
   if (error) {
     console.error(error);
   } else {
     //...
   }
 });

In-app event considerations

  • Event name: up to 45 characters
  • Event value: up to 1000 characters; if longer, it can be truncated
  • Non-English characters are supported from iOS and Android versions 4.81.1 (or in-app events and other SDK API)
  • Pricing and revenue:
    • Only use numbers and decimals such as 5 or 5.2
    • Up to 5 numbers after the decimal such as 5.12345

In-app purchase validation

See In-app purchase validation to learn more about this feature.

In-app purchase validation is available in the React Native plugin via validateAndLogInAppPurchase.

Deep link with OneLink

Set up deep linking in two stages:

  1. Get conversion data in React Native.
  2. Set up the app to support deep linking.

Set up an app to support deep linking

  1. Implement onInstallConversionData and onAppOpenAttribution in your React Native project.
  2. Set up an app to support deep linking. Follow the instructions for each OS:

Get conversion data

Access user attribution data for every new install:

Code samples:

Using class Using hooks
import React, {Component} from 'react';
import {AppState, Platform, StyleSheet, Text, View, Button} from 'react-native';
import appsFlyer from 'react-native-appsflyer';

const options = {
devKey: "********",
isDebug: true,
onInstallConversionData : true
};

if (Platform.OS === 'ios') {
options.appId = "123456789";
}
this.onInstallConversionDataCanceller = appsFlyer.onInstallConversionData(
      data => {
	console.log("GCD");
        console.log(data);  
              
      }
    );

    this.onAppOpenAttributionCanceller = appsFlyer.onAppOpenAttribution(
      data => {
        console.log("OAOA");
        console.log(data);        
      }
    );
   appsFlyer.initSdk(options, (result) => {
      	console.log(result);
      }, (error) => {
      	console.error(error);
      }
    );
type Props = {};
export default class App extends Component<Props> {

componentWillUnmount() {
 // Optionaly remove listeners for deep link data if you no longer need them after componentWillUnmount
 if (onInstallConversionDataCanceller) {
 onInstallConversionDataCanceller();
 console.log('unregister onInstallConversionDataCanceller');
 onInstallConversionDataCanceller = null;
 }
 if (onAppOpenAttributionCanceller) {
 onAppOpenAttributionCanceller();
 console.log('unregister onAppOpenAttributionCanceller');
 onAppOpenAttributionCanceller = null;
 } 

Additional APIs

Attribution

Measure uninstalls

Measure the uninstall rate of users coming from different sources. This significant KPI helps you analyze and optimize your campaigns. Read about uninstall measurement instructions.

AndroidiOS

Two ways to set up uninstall measurement in Android:

Natively through Android studio Through React Native
Follow the instruction here.

Set additional custom data

To integrate on the SDK level with external partner platforms (including Segment, Adobe, and Urban Airship), it is necessary to use the setAdditionalData API.

Only use this API if the partner's integration article specifically states the setAdditionalData API is needed.

appsFlyer.setAdditionalData(
  {
    val1: 'data1',
    val2: false,
    val3: 23,
  },
  (res) => {
    //...
  }
);

Sessions

Custom time between sessions

Not available in React Native plugin. Developer instructions are here.

Background sessions for utility apps

Not available in the React Native plugin. See instructions for Android.

Owned media

Record push notifications

For more information on push notification measurement, read here.

User invite attribution

If you allow existing app users to invite their friends and contacts to become new users, this can be a key growth factor for your app.

With AppsFlyer, you can attribute and record installs that originate from user invites within your app.

There are two steps:

  1. Set OneLink ID.
  2. Generate invite link.

Set OneLink ID

setAppInviteOneLinkID(oneLinkID, callback)

Generate invite link

appsFlyer.generateInviteLink(
 {
   channel: 'gmail',
   campaign: 'myCampaign',
   customerID: '1234',
   userParams: {
     myParam: 'newUser',
     anotherParam: 'fromWeb',
     amount: 1,
   },
 },
 (link) => {
   console.log(link);
 },
 (err) => {
   console.log(err);
 }
);

Cross-promotion attribution

Not available in the React Native plugin. Developer documentation is here.

 

User identifiers

Get AppsFlyer ID

An AppsFlyer ID is created for every new install of an app. You can use the AppsFlyer ID for various purposes:

  • Send server-to-server in-app events.
  • Match the AppsFlyer ID with user records in your back-end systems.
  • Map entries when merging data from pull and push API.

Use this API to obtain a unique AppsFlyer ID:

appsFlyer.getAppsFlyerUID((err, appsFlyerUID) => {
  if (err) {
    console.error(err);
  } else {
    console.log('on getAppsFlyerUID: ' + appsFlyerUID);
  }
});

Set customer user ID

Set your own unique customer user ID (CUID) and cross-reference it with a unique AppsFlyer ID.

Unique CUID:

  • Appear in AppsFlyer raw data CSV reports.
  • Can be used in postback APIs to cross-reference with internal IDs.

To set your CUID, use:

appsFlyer.setCustomerUserId('some_user_id', (res) => {
  //..
});

Recommended practice! Set the CUID early in the app flow—it is only associated with events reported after its setup.

Call setCustomerUserId before calling trackAppLaunch

  • Recorded events will be associated with the CUID.
  • Related data will appear in the raw data reports for installs and events.
  • If set later, then the CUID will only be associated with events recorded after setting the CUID.

User privacy

Opt-out

Different scenarios, such as legal and privacy compliance issues, may lead to a decision to opt-out and stop all SDK tracking. Best practice! Follow the exact instructions for the scenario relevant to your app.

To stop tracking:

  • Call isStopTracking and set to true.
stopTracking(isStopTracking, callback)
  • SDK stops functioning and no longer communicates with AppsFlyer servers.

To reactivate tracking: Call isStopTrackingIn and set to false.

Anonymize user data

Not available in the React Native plugin. See instructions for each OS:

Exclude partners from getting data

In some cases, advertisers may want to stop sharing user-level data with ad networks/partners for specific users. Reasons for this include: 

  • Privacy policies such as CCPA or GDPR
  • User opt-out mechanisms
  • Competition with some partners (ad networks, 3rd parties)

Data sharing with partners is controlled via the setSharingFilterForPartners method:

These filtering methods are supported as of SDK V5.4.1.

The filtering method must be called every time the SDK is initialized and affects the whole session. If it takes time to determine whether you need to set the sharing filters, then delay the SDK initialization. 

When the method is activated before the first trackAppLaunch call:

  • Users from SRNs are attributed as Organic, and their data is not shared with integrated partners.
  • Users from click ad networks (non-SRNs) are attributed correctly in AppsFlyer, but not shared with the ad networks via postbacks, APIs, raw data reports, or by any other method.

Currently, uninstall data can't be filtered using these methods. However, you can stop sending Uninstall events to partners using their setup pages in AppsFlyer. 

Was this article helpful?