AppsFlyer SDK Integration - Unity

Official_unity_logo.png

Current Unity SDK Version:  v4.16.0
Compatible with Android SDK v4.8.6 and iOS SDK v4.8.2

1. Overview

AppsFlyer's SDK provides mobile app installation and event tracking functionality for Android, iOS, Windows Phone and many other mobile development platforms.

You can track installs, updates and sessions and also track post-installs events (including in-app purchases, game levels, etc.) to evaluate ROI and user engagement levels.

Mobile apps, that are developed on the Unity platform, can enjoy integrating AppsFlyer's SDK once and tracking both Android and iOS generated apps. The following guide details how to integrate AppsFlyer's SDK into your Unity code for your iOS and Android apps.

 Note

AppsFlyer supports integration with Unity OS version 5 and above

 Important!

Google Play Install Referrer API is supported starting from Unity Plugin v 4.16.0. If you want to use the new Referrer API, update the plugin to version 4.16.0 or above.

2. Quick Start

2.1 Downloading AppsFlyer’s Unity Plugin

You can find the plugin on Github here: https://github.com/AppsFlyerSDK/Unity

Set out below are the integration instructions for using AppsFlyer’s Unity Plugin.

2.2 Installing the Plugin

Set out below are the installation instructions for the AppsFlyer's plugin:

  1. Import the AppsFlyerUnityPlugin.unitypackage into your Unity project.
  2. Go to Assets >> Import Package >> Custom Package
  3. Select AppsFlyerUnityPlugin.unitypackage file.

2.3 Mandatory Setup for Android and iOS

Android Setup


Setting the AF receiver and permissions to the AndroidManifest.xml:

// receiver should be inside the <application> tag
<receiver android:name="com.appsflyer.MultipleInstallBroadcastReceiver" android:exported="true">
<intent-filter>
<action android:name="com.android.vending.INSTALL_REFERRER" />
</intent-filter>
</receiver>
//Mandatory permission:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />


Setting the Required Permissions

The AndroidManifest.xml includes the following permission:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- Optional : -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />


Setting the BroadcastReceiver in AndroidManifest.xml

The following two options are available for implementing the install referrer broadcast receiver:

Using a Single Broadcast Receiver Using a Multiple Broadcast Receiver

If you do not have a receiver listening on the INSTALL_REFERRER, in the AndroidManifest.xml, add the following receiver within the application tag:

<receiver android:name="com.appsflyer.SingleInstallBroadcastReceiver" android:exported="true">
    <intent-filter>
         <action android:name="com.android.vending.INSTALL_REFERRER" />
     </intent-filter>
</receiver>
iOS Setup

Linked Frameworks and Libraries


After building the project in Unity for xCode, you must add Security.Framework to xCode's Linked Frameworks and Libraries if the framework was not added previously.


iOS Apple Search Ads

Add the following:

AdSupport.framework
AppsFlyer collects IDFA only if you include this framework. Failure to add this framework means that you cannot track Facebook, Twitter and most other ad networks.
iAd.framework

Adding this framework to your app project is highly recommended, since it is mandatory for tracking Apple Search Ads.

3. SDK Initialization

In your Start / Init methods add the following code:

Unity Plugin 4.15.1 and above Unity Plugin 4.14.3 and below
void Start () {
/* Mandatory - set your AppsFlyer’s Developer key. */
AppsFlyer.setAppsFlyerKey ("YOUR_APPSFLYER_DEV_KEY_HERE");
/* For detailed logging */
/* AppsFlyer.setIsDebug (true); */
#if UNITY_IOS
/* Mandatory - set your apple app ID
NOTE: You should enter the number only and not the "ID" prefix */
AppsFlyer.setAppID ("YOUR_APP_ID_HERE");
AppsFlyer.trackAppLaunch ();
#elif UNITY_ANDROID
/* Mandatory - set your Android package name */
AppsFlyer.setAppID ("YOUR_ANDROID_PACKAGE_NAME_HERE");
/* For getting the conversion data in Android, you need to add the "AppsFlyerTrackerCallbacks" listener.*/
AppsFlyer.init ("YOUR_DEV_KEY","AppsFlyerTrackerCallbacks");
#endif
}

 Important!

  • For Android, AppsFlyer.init includes calling trackAppLaunch. Therefore, do not call trackAppLaunch in the Android build of the Unity plugin.
  • In iOS, the conversion data response is triggered in the AppsFlyerTrackerCallbacks.cs class.

4. Tracking In-App Events

In-App Events provide insight on what is happening in your app. It is recommended to take the time and define the events you want to measure to allow you to track ROI (Return on Investment) and LTV (Lifetime Value).

Tracking in-app events is performed by calling trackEvent with event name and value parameters. See In App Events documentation for more details.

 Note

An In-App Event name must be no longer than 45 characters. Events names with more than 45 characters do not appear in the dashboard, but only in the raw Data, Pull and Push APIs.


Tracking Event Example:

System.Collections.Generic.Dictionary<string, string> purchaseEvent = new   
System.Collections.Generic.Dictionary<string, string> ();
purchaseEvent.Add ("af_currency", "USD");
purchaseEvent.Add ("af_revenue", "0.99");
purchaseEvent.Add ("af_quantity", "1");
AppsFlyer.trackRichEvent ("af_purchase", purchaseEvent);

 Note

AppsFlyer supports non-English characters with in-app events, or with any other SDK API, starting from Unity SDK version 4.15.1.

5. Tracking Deeplinking

For Deeplinking, follow the instructions according to your operating system.

Android iOS
Add the following to your manifest file:

<activity android:name="com.appsflyer.GetDeepLinkingActivity" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="your_scheme" />
</intent-filter>
</activity>

6. Tracking Revenue

Use the AFInAppEvents.REVENUE event parameter to count revenue as part of an in-app event. You can populate it with any numeric value, positive or negative.

 Note

AFInAppEvents.REVENUE(equivalent to using af_revenue) is the ONLY event parameter that is counted on AppsFlyer as real revenue on the raw data and dashboard. For more details please click here.

 Example

Revenue In-App Event
AppsFlyer.trackRichEvent(AFInAppEvents.LEVEL_ACHIEVED, new Dictionary<string, string>(){
            {AFInAppEvents.CONTENT_ID, "1234567"},
            {AFInAppEvents.CONTENT_TYPE, "category_a"},
            {AFInAppEvents.REVENUE, "1.99"},
            {AFInAppEvents.CURRENCY, "USD"}
        });

7. Get Conversion Data

AppsFlyer allows you to access the user conversion data in real-time directly at SDK level. It enables you to customize the landing page a user views on the very first app open following a fresh app install.

To load AppsFlyer's conversion data from its servers:

  1. Add an empty GameObject
  2. Attach to it the AppsFlyerTrackerCallbacks.cs which is included in the project (you must name this gameobject AppsFlyerTrackerCallbacks).
Android Unity Plugin > 4.15.1 Android Unity Plugin < 4.14.3 iOS
/*For getting the conversion data in Android, you need to add this listener. to the init() method*/
AppsFlyer.init ("YOUR_DEV_KEY","AppsFlyerTrackerCallbacks");


In Android, you can move the methods from AppsFlyerTrackerCallbacks.cs to another class, and call that class in your listener.

You must use the exact same method namespaces that appear on AppsFlyerTrackerCallbacks.

8. User Identifiers

Get AppsFlyer Device ID

AppsFlyer's unique device ID is created for every new install of an app. Use the following API to obtain AppsFlyer’s Unique ID:

public String getAppsFlyerId();


Usage Example:

string AppsFlyerUID = AppsFlyer.getAppsFlyerId();
Set Customer User ID

Set the User ID as used by the app. 

To set the user ID, call the following method:

AppsFlyer.setCustomerUserID("someId");

 Note

The customerUserID SHOULD be set before the trackAppLaunch/init. It is recommended to set your Customer User ID as soon as possible as it is only associated to events reported after its setup. Customer User ID can also be used to complete integrations with Analytics platforms such as Mixpanel and Swrve.

For more information about the Customer User ID, click here.

Set User Email
Currently unavailable in Unity.
Google Advertising ID

From SDK Version 4.8.0 AppsFlyer automatically collects the google_advertising_id. The requirement to collect the Google Advertising ID is only relevant for SDK versions 4.7.X and below.

IMEI and Android ID

By default, IMEI and Android ID are not collected by the SDK if the OS version is higher than KitKat (4.4) and the app contains Google Play Services.  

To explicitly send these IDs to AppsFlyer, developers can use the following APIs:

AppsFlyer.setAndroidIdData(string)
AppsFlyer.setImeiData(string)


If the app does NOT contain Google Play Services the IMEI and Android ID are collected by the SDK.

Developers can opt-out of collection of IMEI and Android ID by using these APIs:

AppsFlyer.setCollectAndroidID(bool) 
AppsFlyer.setCollectIMEI(bool)

 Warning

At least one device identifier, GAID, Android ID or IMEI, MUST be collected to allow for proper attribution.

IDFA and IDFV

AppsFlyer automatically collects the IDFA (ID For Advertisers) and IDFV (ID For Vendors) if AdSupport.framework is included in the app.

9. Optional Features

Track Uninstalls

For Uninstall, follow the instructions according to your operating system.

Android - Firebase Android - GCM iOS
1.  Download the Unity Firebase SDK from: https://firebase.google.com/docs/unity/setup
2.  Import FirebaseMessaging.unitypackage into the project.
3.  Import google-services.json into the project (obtained in the Firebase console)

 Note

Manifest receivers should be automatically added by the Unity Firebase SDK.


4.  In the Unity class handling the AppsFlyer code, add the following:
using Firebase.Messaging;
using Firebase.Unity;

5.  Add to the Start() method:
Firebase.Messaging.FirebaseMessaging.TokenReceived += OnTokenReceived;

6.  Add the following method:
public void OnTokenReceived
(object sender, Firebase.Messaging.TokenReceivedEventArgs token) { AppsFlyer.updateServerUninstallToken (token.Token); }

 

 Warning

Users who implement the Unity Firebase SDK should not add the following method call to enableUninstallTracking(“SenderID”) as the Firebase SDK will obtain the sender ID from the google-services.json file we have added earlier. Adding this method might cause a debug warning from Android.

Tracking Push Notifications 

AppsFlyer allows you to measure push notifications as part of a retargeting campaign.

handlePushNotification(Dictionary<string, string> payload)

The data payload should include an object: af with the relevant key-value string:

Example:

\"data\": { \"score\": \"5x1\", \"time\": \"15:10\" , \"af\" : { \"c\" : \"test_campaign\" , \"is_retargeting\" : \"true\" , \"pid\" : \"push_provider_int\" } } }"[with deep-linking] \"data\": { \"score\": \"5x1\", \"time\": \"15:10\", \"click_action\" : \"com.example.someAction\" , 
\"af\" : { \"c\" : \"test_campaign\" , \"is_retargeting\" : \"true\" , \"pid\" : \"push_provider_int\" } } }"

 Note

For more information on push notification measurement, read here.

Cross Promotion Tracking 
Currently unavailable in Unity.
User Invite Tracking
Currently unavailable in Unity.
Set Currency Code 
You can set a global currency code using the API below, in addition to specific currency codes that can be used as part of each in-app event sent to AppsFlyer. The global currency code is used when af_currency

AFInAppEvents.CURRENCY

is not sent as part of an in-app event.

USD is the default value. You can find acceptable ISO currency codes here.

Use the following API to set the currency code:

public void setCurrencyCode(String currencyCode);

Usage Example:

setCurrencyCode(string currencyCode)
In-App Purchase Validation

For In-App Purchase Receipt Validation, follow the instructions according to your operating system.

Android Call Call the Listener (Android Only) iOS
//To get the callbacks
//AppsFlyer.createValidateInAppListener ("AppsFlyerTrackerCallbacks", 
"onInAppBillingSuccess", "onInAppBillingFailure"); AppsFlyer.validateReceipt(string publicKey, string purchaseData,
string signature, string price, string currency, Dictionary additionalParametes);

The validate purchase response is triggered in the AppsFlyerTrackerCallbacks.cs class

Opt Out 
AppsFlyer provides you a method to opt-out specific users from AppsFlyer analytics. This method complies with the latest privacy requirements and complies with Facebook data and privacy policies. Default is false, meaning tracking is enabled by default.

Use this API during the SDK Initialization to explicitly opt-out:

public void setDeviceTrackingDisabled(boolean isDisabled);

Usage Example:

AppsFlyer.setDeviceTrackingDisabled(true);
Tracking can be restarted by calling deviceTrackingDisabled again set to false.

 Warning

Opting out users SEVERELY hurts your attribution information.
Use this option ONLY for regions which legally prevent you from collecting your users' information.
Custom Time Between Sessions
Currently unavailable in Unity.
Background Sessions for Utility Apps

Currently unavailable in Unity.

Track Out-of-Store Apps 

 Note

Google Play is the default store. If you are publishing your app only on Google Play, skip this section.

To track installs out of Google Play, set the channel/store at the app’s AndroidManifest.xml with a unique channel or any store name for each APK. The CHANNEL value is case sensitive.

<Examples:

<meta-data android:name="CHANNEL" android:value="Amazon" />
<meta-data android:name="CHANNEL" android:value="Standalone"/>
<meta-data android:name="CHANNEL" android:value="Verizon" />

 Note

You must configure the CHANNEL value at the AppsFlyer dashboard when setting up the app.

Place the meta-data tag before the </application> tag.

For more details on how to track installs for out-of-store apps, read here.

10. Testing Your Integration

For instructions ton testing your integrations according to your operating system, click Android Testing or iOS Testing.

11. Unity Sample Project

To view a Unity sample project, click here.

Was this article helpful?
0 out of 3 found this helpful

Comments

0 comments

Please sign in to leave a comment.