### Basic Setup for Integrated Approach (v6.17.1+) Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/purchase-connector.md Initialize and configure the AppsFlyer SDK and Purchase Connector, then start observing transactions. Ensure to set sandbox mode for testing and configure StoreKit version and automatic logging options. ```csharp using UnityEngine; using AppsFlyerSDK; public class AppsFlyerObjectScript : MonoBehaviour, IAppsFlyerConversionData, IAppsFlyerPurchaseValidation, IAppsFlyerPurchaseRevenueDataSource, IAppsFlyerPurchaseRevenueDataSourceStoreKit2 { [Header("AppsFlyer Settings")] public string devKey = "YOUR_DEV_KEY"; public string appID = "YOUR_APP_ID"; public bool isDebug = true; public bool getConversionData = true; void Start() { // 1. Initialize AppsFlyer SDK AppsFlyer.initSDK(devKey, appID, getConversionData ? this : null); AppsFlyer.setIsDebug(isDebug); // 2. Initialize Purchase Connector AppsFlyerPurchaseConnector.init(this, Store.GOOGLE); // 3. Configure Purchase Connector ConfigurePurchaseConnector(); // 4. Build and start observing AppsFlyerPurchaseConnector.build(); AppsFlyerPurchaseConnector.startObservingTransactions(); // 5. Start AppsFlyer SDK AppsFlyer.startSDK(); } private void ConfigurePurchaseConnector() { // Set sandbox mode for testing AppsFlyerPurchaseConnector.setIsSandbox(true); // Configure StoreKit version (iOS only) - SK1 is the default AppsFlyerPurchaseConnector.setStoreKitVersion(StoreKitVersion.SK2); // Enable automatic logging for subscriptions and in-app purchases AppsFlyerPurchaseConnector.setAutoLogPurchaseRevenue( AppsFlyerAutoLogPurchaseRevenueOptions.AppsFlyerAutoLogPurchaseRevenueOptionsAutoRenewableSubscriptions, AppsFlyerAutoLogPurchaseRevenueOptions.AppsFlyerAutoLogPurchaseRevenueOptionsInAppPurchases ); // Enable purchase validation callbacks AppsFlyerPurchaseConnector.setPurchaseRevenueValidationListeners(true); // Set data sources for additional parameters (iOS) - SK1 AppsFlyerPurchaseConnector.setPurchaseRevenueDataSource(this); // Set data sources for additional parameters (iOS) - SK2 AppsFlyerPurchaseConnector.setPurchaseRevenueDataSourceStoreKit2(this); } } ``` -------------------------------- ### Initialize and Start AppsFlyer SDK for User Invites Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/UserInvite.md Initialize the AppsFlyer SDK with your dev key and app ID, set the one-link ID for user invites, and then start the SDK. This setup is typically done in the Start method of a MonoBehaviour. ```csharp public class AppsFlyerObjectScript : MonoBehaviour , IAppsFlyerConversionData, IAppsFlyerUserInvite { void Start() { //... AppsFlyer.initSDK("devkey", "appID"); AppsFlyer.setAppInviteOneLinkID("XXXX"); //set up the one link ID for the user invite AppsFlyer.startSDK(); } //... public void generateAppsFlyerLink() { Dictionary parameters = new Dictionary(); parameters.Add("channel", "some_channel"); parameters.Add("campaign", "some_campaign"); parameters.Add("additional_param1", "some_param1"); parameters.Add("additional_param2", "some_param2"); // other params //parameters.Add("referrerName", "some_referrerName"); //parameters.Add("referrerImageUrl", "some_referrerImageUrl"); //parameters.Add("customerID", "some_customerID"); //parameters.Add("baseDeepLink", "some_baseDeepLink"); //parameters.Add("brandDomain", "some_brandDomain"); AppsFlyer.generateUserInviteLink(parameters, this); } ... public void onInviteLinkGenerated(string link) { AppsFlyer.AFLog("onInviteLinkGenerated", link); } public void onInviteLinkGeneratedFailure(string error) { AppsFlyer.AFLog("onInviteLinkGeneratedFailure", error); } public void onOpenStoreLinkGenerated(string link) { AppsFlyer.AFLog("onOpenStoreLinkGenerated", link); } } ``` -------------------------------- ### Integrated Approach (v6.17.1+) Basic Setup Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/purchase-connector.md This code snippet demonstrates the basic setup for the AppsFlyer Purchase Connector using the integrated approach in Unity, including SDK initialization, connector configuration, and transaction observation. ```APIDOC ## Integrated Approach (v6.17.1+) Basic Setup This code snippet demonstrates the basic setup for the AppsFlyer Purchase Connector using the integrated approach in Unity, including SDK initialization, connector configuration, and transaction observation. ### MonoBehaviour Implementation Your MonoBehaviour class must implement the following interfaces: ```csharp using AppsFlyerSDK; public class AppsFlyerObjectScript : MonoBehaviour, IAppsFlyerConversionData, IAppsFlyerPurchaseValidation, IAppsFlyerPurchaseRevenueDataSource, IAppsFlyerPurchaseRevenueDataSourceStoreKit2 { // Implementation goes here } ``` ### Initialization and Configuration ```csharp using UnityEngine; using AppsFlyerSDK; public class AppsFlyerObjectScript : MonoBehaviour, IAppsFlyerConversionData, IAppsFlyerPurchaseValidation, IAppsFlyerPurchaseRevenueDataSource, IAppsFlyerPurchaseRevenueDataSourceStoreKit2 { [Header("AppsFlyer Settings")] public string devKey = "YOUR_DEV_KEY"; public string appID = "YOUR_APP_ID"; public bool isDebug = true; public bool getConversionData = true; void Start() { // 1. Initialize AppsFlyer SDK AppsFlyer.initSDK(devKey, appID, getConversionData ? this : null); AppsFlyer.setIsDebug(isDebug); // 2. Initialize Purchase Connector AppsFlyerPurchaseConnector.init(this, Store.GOOGLE); // 3. Configure Purchase Connector ConfigurePurchaseConnector(); // 4. Build and start observing AppsFlyerPurchaseConnector.build(); AppsFlyerPurchaseConnector.startObservingTransactions(); // 5. Start AppsFlyer SDK AppsFlyer.startSDK(); } private void ConfigurePurchaseConnector() { // Set sandbox mode for testing AppsFlyerPurchaseConnector.setIsSandbox(true); // Configure StoreKit version (iOS only) - SK1 is the default AppsFlyerPurchaseConnector.setStoreKitVersion(StoreKitVersion.SK2); // Enable automatic logging for subscriptions and in-app purchases AppsFlyerPurchaseConnector.setAutoLogPurchaseRevenue( AppsFlyerAutoLogPurchaseRevenueOptions.AppsFlyerAutoLogPurchaseRevenueOptionsAutoRenewableSubscriptions, AppsFlyerAutoLogPurchaseRevenueOptions.AppsFlyerAutoLogPurchaseRevenueOptionsInAppPurchases ); // Enable purchase validation callbacks AppsFlyerPurchaseConnector.setPurchaseRevenueValidationListeners(true); // Set data sources for additional parameters (iOS) - SK1 AppsFlyerPurchaseConnector.setPurchaseRevenueDataSource(this); // Set data sources for additional parameters (iOS) - SK2 AppsFlyerPurchaseConnector.setPurchaseRevenueDataSourceStoreKit2(this); } } ``` -------------------------------- ### startSDK Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Starts the AppsFlyer SDK, enabling session tracking and recording of background/foreground transitions. ```APIDOC ## startSDK ### Description Once this API is invoked, the SDK will start, sessions will be immediately sent, and all background foreground transitions will record a session. ### Method Signature `void startSDK()` ### Request Example ```csharp AppsFlyer.startSDK(); ``` ``` -------------------------------- ### attributeAndOpenStore Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Attributes the install and opens the app store. This method is available for Android and iOS. ```APIDOC ## attributeAndOpenStore ### Description Attributes the app install and then opens the relevant app store page. ### Method Not specified (assumed to be a method call within the Unity plugin). ### Endpoint N/A (SDK method) ### Parameters None explicitly documented for this method signature. ``` -------------------------------- ### startSDK Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Starts the AppsFlyer SDK. This method is available for Android, iOS, and Windows. ```APIDOC ## startSDK ### Description Starts the AppsFlyer SDK. This method should be called after initialization. ### Method Not specified (assumed to be a method call within the Unity plugin). ### Endpoint N/A (SDK method) ### Parameters None explicitly documented for this method signature. ### Request Example ```csharp AppsFlyer.startSDK(); ``` ### Response None explicitly documented. ``` -------------------------------- ### Build and Complete Setup Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/purchase-connector.md Builds the Purchase Connector with all the specified configurations. This method should be called after all initialization and configuration steps are completed. ```APIDOC ## Build and Complete Setup ### Description Builds the Purchase Connector with all the specified configurations. This method should be called after all initialization and configuration steps are completed. ### Method `AppsFlyerPurchaseConnector.build()` ``` -------------------------------- ### Start AppsFlyer SDK Session Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Starts the AppsFlyer SDK, initiating session tracking and recording foreground/background transitions. ```csharp AppsFlyer.startSDK(); ``` -------------------------------- ### setCustomerIdAndStartSDK Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Sets the customer ID and starts the SDK. This method is available for Android only. ```APIDOC ## setCustomerIdAndStartSDK ### Description Sets a customer identifier and then initializes and starts the AppsFlyer SDK. ### Method Not specified (assumed to be a method call within the Unity plugin). ### Endpoint N/A (SDK method) ### Parameters - **customerId** (string) - Required - The customer identifier. ``` -------------------------------- ### Attach AppsFlyer Script and Initialize SDK Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/BasicIntegration.md Attach the 'AppsFlyer.cs' script to your game object and add this code before calling startSDK(). This sets up the SDK initialization and starts the session. ```csharp void Start() { AppsFlyer.OnRequestResponse += AppsFlyerOnRequestResponse; AppsFlyer.initSDK(devKey, appID, this); AppsFlyer.startSDK(); } void AppsFlyerOnRequestResponse(object sender, EventArgs e) { var args = e as AppsFlyerRequestEventArgs; AppsFlyer.AFLog("AppsFlyerOnRequestResponse", " status code " + args.statusCode); } ``` -------------------------------- ### Initialize and Configure AppsFlyer Purchase Connector in Unity Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/purchase-connector.md This script demonstrates the complete initialization and configuration process for the AppsFlyer SDK and Purchase Connector in a Unity project. It includes setting up the SDK, initializing the connector with the correct store, configuring options like sandbox mode and auto-logging, and starting transaction observation. ```csharp using UnityEngine; using AppsFlyerSDK; using AppsFlyerConnector; public class AppsFlyerObjectScript : MonoBehaviour, IAppsFlyerConversionData, IAppsFlyerPurchaseValidation, IAppsFlyerPurchaseRevenueDataSource { [Header("AppsFlyer Settings")] public string devKey = "YOUR_DEV_KEY"; public string appID = "YOUR_APP_ID"; public bool isDebug = true; public bool getConversionData = true; void Start() { // 1. Initialize AppsFlyer SDK AppsFlyer.initSDK(devKey, appID, getConversionData ? this : null); AppsFlyer.setIsDebug(isDebug); // 2. Initialize Purchase Connector (using AppsFlyerConnector namespace) AppsFlyerPurchaseConnector.init(this, AppsFlyerConnector.Store.GOOGLE); // 3. Configure Purchase Connector ConfigurePurchaseConnector(); // 4. Build and start observing AppsFlyerPurchaseConnector.build(); AppsFlyerPurchaseConnector.startObservingTransactions(); // 5. Start AppsFlyer SDK AppsFlyer.startSDK(); } private void ConfigurePurchaseConnector() { // Set sandbox mode for testing AppsFlyerPurchaseConnector.setIsSandbox(true); // Enable automatic logging for subscriptions and in-app purchases AppsFlyerPurchaseConnector.setAutoLogPurchaseRevenue( AppsFlyerAutoLogPurchaseRevenueOptions.AppsFlyerAutoLogPurchaseRevenueOptionsAutoRenewableSubscriptions, AppsFlyerAutoLogPurchaseRevenueOptions.AppsFlyerAutoLogPurchaseRevenueOptionsInAppPurchases ); // Enable purchase validation callbacks AppsFlyerPurchaseConnector.setPurchaseRevenueValidationListeners(true); } } ``` -------------------------------- ### Start and Stop Transaction Observation Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/purchase-connector.md Starts or stops the observation of purchase transactions. Ensure observation is started to capture purchase events. ```csharp // Start observing transactions AppsFlyerPurchaseConnector.startObservingTransactions(); // Stop observing transactions AppsFlyerPurchaseConnector.stopObservingTransactions(); ``` -------------------------------- ### Set Preinstall Attribution Details Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Specify details for preinstall attribution, including the media source, campaign name, and site ID. This helps attribute installs that occur before the app is available on app stores. ```csharp #if UNITY_ANDROID && !UNITY_EDITOR AppsFlyer.setPreinstallAttribution("mediaSource", "campaign", "siteId"); #endif ``` -------------------------------- ### Initialize AdRevenue Connector (SDK 6.14.2 and below) Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/ad-revenue-unity.md For SDK versions 6.14.2 and below, initialize the AppsFlyer SDK before initializing the AdRevenue connector. This example shows initialization within a Unity MonoBehaviour. ```csharp using AppsFlyerSDK; public class AppsFlyerObjectScript : MonoBehaviour { void Start() { AppsFlyerAdRevenue.start(); /* AppsFlyerAdRevenue.setIsDebug(true); */ } } ``` -------------------------------- ### Initialize SDK and Handle Deep Links Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/UnifiedDeepLink.md This C# code snippet demonstrates how to initialize the AppsFlyer SDK, register for deep link events, and start the SDK. It also includes the implementation for the OnDeepLink event handler, which processes both deferred and direct deep links, logging their status and extracting parameters based on the platform. ```csharp using AppsFlyerSDK; public class AppsFlyerObjectScript : MonoBehaviour { void Start() { AppsFlyer.initSDK("devkey", "appID", this); AppsFlyer.OnDeepLinkReceived += OnDeepLink; AppsFlyer.startSDK(); } void OnDeepLink(object sender, EventArgs args) { var deepLinkEventArgs = args as DeepLinkEventsArgs; switch (deepLinkEventArgs.status) { case DeepLinkStatus.FOUND: if (deepLinkEventArgs.isDeferred()) { AppsFlyer.AFLog("OnDeepLink", "This is a deferred deep link"); } else { AppsFlyer.AFLog("OnDeepLink", "This is a direct deep link"); } // deepLinkParamsDictionary contains all the deep link parameters as keys Dictionary deepLinkParamsDictionary = null; #if UNITY_IOS && !UNITY_EDITOR if (deepLinkEventArgs.deepLink.ContainsKey("click_event") && deepLinkEventArgs.deepLink["click_event"] != null) { deepLinkParamsDictionary = deepLinkEventArgs.deepLink["click_event"] as Dictionary; } #elif UNITY_ANDROID && !UNITY_EDITOR deepLinkParamsDictionary = deepLinkEventArgs.deepLink; #endif break; case DeepLinkStatus.NOT_FOUND: AppsFlyer.AFLog("OnDeepLink", "Deep link not found"); break; default: AppsFlyer.AFLog("OnDeepLink", "Deep link error"); break; } } } ``` -------------------------------- ### Request Tracking Authorization (Unity Ads) Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/BasicIntegration.md This example shows how to request tracking authorization from the user using the Unity Ads package. It checks the current status before prompting. ```csharp using Unity.Advertisement.IosSupport; /* ... */ if (ATTrackingStatusBinding.GetAuthorizationTrackingStatus() == ATTrackingStatusBinding.AuthorizationTrackingStatus.NOT_DETERMINED) { ATTrackingStatusBinding.RequestAuthorizationTracking(); } /* ... */ ``` -------------------------------- ### Set Customer ID and Start SDK Activity Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Call this method after `waitForCustomerUserId` to provide the customer user ID and initiate normal SDK operation. This triggers the SDK to begin its normal activity. ```csharp #if UNITY_ANDROID && !UNITY_EDITOR AppsFlyer.setCustomerIdStartSDK("id"); #endif ``` -------------------------------- ### iOS API Call Before 6.6.0 Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/Introduction.md Example of calling an iOS-specific API before version 6.6.0, requiring platform-specific preprocessor directives. ```csharp #if UNITY_IOS && !UNITY_EDITOR AppsFlyeriOS.waitForATTUserAuthorizationWithTimeoutInterval(60); #endif ``` -------------------------------- ### Enable TCF Data Collection (Unity) Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/DMAConsent.md Instruct the SDK to collect TCF data from the device before starting the SDK. This is used when integrating with a CMP. ```csharp using AppsFlyerSDK; using UnityEngine; public class DMAConsentCmpFlow : MonoBehaviour { [SerializeField] string devKey = "AF_DEV_KEY"; [SerializeField] string appId = "com.example.app"; // empty on Android void Start() { AppsFlyer.initSDK(devKey, appId); AppsFlyer.enableTCFDataCollection(true); // collect TCF strings from device // Pseudocode for your CMP flow: if (CmpManager.HasConsentReady()) { AppsFlyer.startSDK(); } else { CmpManager.ShowDialog(onUserDecided: () => { // CMP indicates consent data now stored in device prefs AppsFlyer.startSDK(); }); } } } ``` -------------------------------- ### AppsFlyerAdRevenue API Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/ad-revenue-unity.md Provides details on the `start` and `setIsDebug` methods for the Ad Revenue Connector. ```APIDOC ### Ad revenue connector API #### `start` `public static void start()` Start sending AdRevenue data to AppsFlyer. _Example:_ ```java using AppsFlyerSDK; void Start() { AppsFlyerAdRevenue.start(); } ``` #### `setIsDebug` `public static void setIsDebug(bool isDebug)` Set to true to view debug logs. (development only!) | parameter | type | description | | --------- | ---- | ------------------------------- | | isDebug | bool | set to true in development only | _Example:_ ```java AppsFlyerAdRevenue.setIsDebug(true); ``` **Note:** This API will only set the debug logs for iOS. For Android the debug logs are controlled by the native SDK. To turn on the debug logs on Android call `AppsFlyer.setIsDebug(true);` ``` -------------------------------- ### Delay SDK Initialization Until Customer User ID is Set Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Use this method to ensure the SDK does not start functioning until a customer user ID is provided. All subsequent SDK calls will be discarded until the ID is set. ```csharp #if UNITY_ANDROID && !UNITY_EDITOR AppsFlyer.waitForCustomerUserId(true); #endif ``` -------------------------------- ### Start AdRevenue Connector (SDK 6.14.2 and below) Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/ad-revenue-unity.md Call this method to begin sending AdRevenue data to AppsFlyer when using the AdRevenue connector for older SDK versions. ```csharp using AppsFlyerSDK; void Start() { AppsFlyerAdRevenue.start(); } ``` -------------------------------- ### Register Conversion Data Listener Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Allows real-time access to user attribution data for new installs. Implement the IAppsFlyerConversionData interface to receive callbacks. ```csharp AppsFlyer.getConversionData(gameObject.name); ``` -------------------------------- ### Initialize SDK Manually in Unity Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/BasicIntegration.md Use this code to manually initialize the AppsFlyer SDK in your Unity project. Ensure it's called in the Start method of a script attached to a game object. ```csharp using AppsFlyerSDK; public class AppsFlyerObjectScript : MonoBehaviour { void Start() { AppsFlyer.initSDK("devkey", "appID"); AppsFlyer.startSDK(); } } ``` -------------------------------- ### Manually Set AF_STORE Value Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Allows you to manually set the AF_STORE value. This can be used to attribute installs from specific sources. ```csharp #if UNITY_ANDROID && !UNITY_EDITOR AppsFlyer.setOutOfStore("sourceName"); #endif ``` -------------------------------- ### In-App Purchase Validation Example (Unity C#) Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/InAppEvents.md This C# script demonstrates how to process and validate in-app purchases within a Unity application using the AppsFlyer SDK. It handles receipt parsing and calls the appropriate validation methods for iOS and Android platforms. ```csharp using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Purchasing; using AppsFlyerSDK; public class AppsFlyerObject : MonoBehaviour, IAppsFlyerValidateAndLog { public static string kProductIDConsumable = "com.test.cons"; void Start() { AppsFlyer.initSDK("devKey", "appId"); AppsFlyer.startSDK(); } public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args) { string prodID = args.purchasedProduct.definition.id; string transactionID = args.purchasedProduct.transactionID; var recptToJSON = (Dictionary)AFMiniJSON.Json.Deserialize(args.purchasedProduct.receipt); var receiptPayload = (Dictionary)AFMiniJSON.Json.Deserialize((string)recptToJSON["Payload"]); if (String.Equals(prodID, kProductIDConsumable, StringComparison.Ordinal)) { var purchaseAdditionalDetails = new Dictionary { { "paywall", "123" } }; #if UNITY_IOS if (isSandbox) { AppsFlyeriOS.setUseReceiptValidationSandbox(true); } AFSDKPurchaseDetailsIOS details = AFSDKPurchaseDetailsIOS.Init( prodID, transactionID, AFSDKPurchaseType.OneTimePurchase); AppsFlyer.validateAndSendInAppPurchase(details, purchaseAdditionalDetails, this); #elif UNITY_ANDROID var purchaseData = (string)receiptPayload["json"]; var purchaseDataJson = (Dictionary)AFMiniJSON.Json.Deserialize(purchaseData); string purchaseToken = (string)purchaseDataJson["purchaseToken"]; AFPurchaseDetailsAndroid details = new AFPurchaseDetailsAndroid( AFPurchaseType.OneTimePurchase, purchaseToken, prodID); AppsFlyer.validateAndSendInAppPurchase(details, purchaseAdditionalDetails, this); #endif } return PurchaseProcessingResult.Complete; } public void onValidateAndLogComplete(string result) { AppsFlyer.AFLog("onValidateAndLogComplete", result); Dictionary validateAndLogDataDictionary = AppsFlyer.CallbackStringToDictionary(result); // On iOS: Check the response dictionary to determine if validation was successful // Validation failures are returned here, not in onValidateAndLogFailure } public void onValidateAndLogFailure(string error) { AppsFlyer.AFLog("onValidateAndLogFailure", error); Dictionary validateAndLogErrorDictionary = AppsFlyer.CallbackStringToDictionary(error); // On iOS: This is only called for actual errors (network errors, invalid parameters, etc.) // Validation failures come through onValidateAndLogComplete instead } } ``` -------------------------------- ### Handle Conversion Data Success Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Callback function executed when conversion data is successfully received. This data contains information about the install, such as organic/non-organic status. ```csharp public void onConversionDataSuccess(string conversionData) { AppsFlyer.AFLog("onConversionDataSuccess", conversionData); Dictionary conversionDataDictionary = AppsFlyer.CallbackStringToDictionary(conversionData); // add deferred deeplink logic here } ``` -------------------------------- ### Enable TCF Data Collection in Unity Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/DMAConsent.md Call `AppsFlyer.enableTCFDataCollection(true|false)` before `startSDK()` to automatically collect TCF strings. Ensure this is set prior to the initial SDK start. ```csharp AppsFlyer.enableTCFDataCollection(true|false) ``` -------------------------------- ### iOS API Call After 6.6.0 Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/Introduction.md Example of calling an iOS-specific API after version 6.6.0, where platform-specific preprocessor directives are no longer needed for common APIs. ```csharp #if UNITY_IOS && !UNITY_EDITOR AppsFlyer.waitForATTUserAuthorizationWithTimeoutInterval(60); #endif ``` -------------------------------- ### Get AppsFlyer Unique ID Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Retrieves the unique AppsFlyer device ID generated for each new app install. ```csharp string uid = AppsFlyer.getAppsFlyerId(); ``` -------------------------------- ### Get Current AF_STORE Value Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Retrieves the current value of the AF_STORE parameter. This is useful for understanding the source of app installs. ```csharp #if UNITY_ANDROID && !UNITY_EDITOR string af_store = AppsFlyer.getOutOfStore(); #endif ``` -------------------------------- ### Initialize Ad Revenue Connector (SDK 6.14.2 and below) Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/ad-revenue-unity.md For older SDK versions (6.14.2 and below), this section details how to set up and use the Ad Revenue Connector via Unity Package Manager or by importing a custom package. ```APIDOC ## [LEGACY] Log ad revenue (for SDK 6.14.2 and below) For SDK v6.14.2 and below - the AdRevenue Connector should be used along side the AppsFlyer SDK to send Ad Revenue data to AppsFlyer. ### Using Unity Package 1. Clone or download [the Ad revenue connector](https://github.com/AppsFlyerSDK/appsflyer-unity-adrevenue-generic-connector/tree/main) repository. 2. Import the Adrevenue Unity package into your Unity project (To learn how to import to Unity refer to the [Unity documentation](https://docs.unity3d.com/Manual/AssetPackages.html)). 1. In Unity, go to **Assets** > **Import Package** > **Custom Package** 2. From the repository root select the `appsflyer-unity-adrevenue-plugin-x.x.x.unitypackage` file. ### Using Unity Package Manager 1. Add the dependency in your `manifest.json` file: ```json "appsflyer-unity-adrevenue-generic-connector": "https://github.com/AppsFlyerSDK/appsflyer-unity-adrevenue-generic-connector.git#upm" ``` 2. If you haven't already done so, download the [External Dependency Manager for Unity](https://github.com/googlesamples/unity-jar-resolver) to be able to resolve our Android / iOS dependencies. **Note:** To choose a specific version and not the latest, you can replace the `upm` with the specific version tag, `v6.9.4-upm` for example. ### Initialize the connector Make sure to initialize the AppsFlyer SDK before initializing the connector. ```java using AppsFlyerSDK; public class AppsFlyerObjectScript : MonoBehaviour { void Start() { AppsFlyerAdRevenue.start(); /* AppsFlyerAdRevenue.setIsDebug(true); */ } } ``` ``` -------------------------------- ### Initialize SDK: Old vs. New API Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/MigrationGuide.md Compares the old and new methods for initializing the AppsFlyer SDK, including variations for handling deep linking and conversion data. ```csharp // Old API's AppsFlyer.setAppsFlyerKey(string key); AppsFlyer.trackAppLaunch(); AppsFlyer.setAppID(string appleAppId); AppsFlyer.getConversionData (); AppsFlyer.init(string devKey); AppsFlyer.init(string devKey, string callbackObject); AppsFlyer.loadConversionData(string callbackObject); // New API's AppsFlyer.initSDK(string key, string app_id); // without deeplinking/conversion data AppsFlyer.initSDK(string key, string app_id, MonoBehaviour gameObject); // with deeplinking/conversion data AppsFlyer.startSDK(); ``` -------------------------------- ### Initialize and Configure AppsFlyer Purchase Connector Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/purchase-connector.md This snippet demonstrates the initialization and configuration of the AppsFlyer Purchase Connector within a Unity script. It includes setting up the SDK, configuring the store, sandbox mode, auto-log options, and data sources. Ensure to remove `setIsSandbox(true)` for production environments. ```csharp using System.Collections.Generic; using UnityEngine; using AppsFlyerSDK; public class AppsFlyerObjectScript : MonoBehaviour, IAppsFlyerConversionData, IAppsFlyerPurchaseValidation, IAppsFlyerPurchaseRevenueDataSource, IAppsFlyerPurchaseRevenueDataSourceStoreKit2 { [Header("AppsFlyer Configuration")] public string devKey = "YOUR_DEV_KEY"; public string appID = "YOUR_APP_ID"; public string UWPAppID = "YOUR_UWP_APP_ID"; public string macOSAppID = "YOUR_MACOS_APP_ID"; public bool isDebug = true; public bool getConversionData = true; void Start() { // 1. Initialize AppsFlyer SDK #if UNITY_WSA_10_0 && !UNITY_EDITOR AppsFlyer.initSDK(devKey, UWPAppID, getConversionData ? this : null); #elif UNITY_STANDALONE_OSX && !UNITY_EDITOR AppsFlyer.initSDK(devKey, macOSAppID, getConversionData ? this : null); #else AppsFlyer.initSDK(devKey, appID, getConversionData ? this : null); #endif AppsFlyer.setIsDebug(isDebug); // 2. Initialize and configure Purchase Connector AppsFlyerPurchaseConnector.init(this, Store.GOOGLE); AppsFlyerPurchaseConnector.setStoreKitVersion(StoreKitVersion.SK2); AppsFlyerPurchaseConnector.setIsSandbox(true); // Remove for production AppsFlyerPurchaseConnector.setAutoLogPurchaseRevenue( AppsFlyerAutoLogPurchaseRevenueOptions.AppsFlyerAutoLogPurchaseRevenueOptionsAutoRenewableSubscriptions, AppsFlyerAutoLogPurchaseRevenueOptions.AppsFlyerAutoLogPurchaseRevenueOptionsInAppPurchases ); AppsFlyerPurchaseConnector.setPurchaseRevenueValidationListeners(true); AppsFlyerPurchaseConnector.setPurchaseRevenueDataSource(this); AppsFlyerPurchaseConnector.setPurchaseRevenueDataSourceStoreKit2(this); // 3. Build and start AppsFlyerPurchaseConnector.build(); AppsFlyerPurchaseConnector.startObservingTransactions(); // 4. Start AppsFlyer SDK AppsFlyer.startSDK(); Debug.Log("AppsFlyer SDK + Purchase Connector initialized successfully"); } // --- Purchase Revenue Data Sources --- public Dictionary PurchaseRevenueAdditionalParametersForProducts( HashSet products, HashSet transactions) { return new Dictionary { ["storekit_version"] = "1.0", ["additional_param"] = "sk1_value", ["product_count"] = products.Count, ["transaction_count"] = transactions.Count }; } public Dictionary PurchaseRevenueAdditionalParametersStoreKit2ForProducts( HashSet products, HashSet transactions) { return new Dictionary { ["storekit_version"] = "2.0", ["additional_param"] = "sk2_value", ["product_count"] = products.Count, ["transaction_count"] = transactions.Count }; } // --- Purchase Validation Callbacks --- public void didReceivePurchaseRevenueValidationInfo(string validationInfo) { AppsFlyer.AFLog("didReceivePurchaseRevenueValidationInfo", validationInfo); Debug.Log("Purchase validation success: " + validationInfo); // Parse and handle validation info var dict = AFMiniJSON.Json.Deserialize(validationInfo) as Dictionary; #if UNITY_ANDROID if (dict.ContainsKey("productPurchase")) { Debug.Log("Android in-app purchase validated"); } else if (dict.ContainsKey("subscriptionPurchase")) { Debug.Log("Android subscription validated"); } #endif } public void didReceivePurchaseRevenueError(string error) { AppsFlyer.AFLog("didReceivePurchaseRevenueError", error); Debug.LogError("Purchase validation error: " + error); } // --- Conversion Data Callbacks --- public void onConversionDataSuccess(string conversionData) { AppsFlyer.AFLog("onConversionDataSuccess", conversionData); var dict = AppsFlyer.CallbackStringToDictionary(conversionData); // Handle deferred deep linking } public void onConversionDataFail(string error) { AppsFlyer.AFLog("onConversionDataFail", error); } public void onAppOpenAttribution(string attributionData) { AppsFlyer.AFLog("onAppOpenAttribution", attributionData); var dict = AppsFlyer.CallbackStringToDictionary(attributionData); // Handle direct deep linking } public void onAppOpenAttributionFailure(string error) { AppsFlyer.AFLog("onAppOpenAttributionFailure", error); } } ``` -------------------------------- ### Transaction Observation Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/purchase-connector.md Starts and stops the observation of purchase transactions. Ensure this is called after initialization and configuration. ```APIDOC ## Transaction Observation ### Description Starts and stops the observation of purchase transactions. Ensure this is called after initialization and configuration. ### Methods #### Start Observing `AppsFlyerPurchaseConnector.startObservingTransactions()` #### Stop Observing `AppsFlyerPurchaseConnector.stopObservingTransactions()` ``` -------------------------------- ### Get AppsFlyer SDK Version Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Retrieves the version of the AppsFlyer SDK currently used in the application. ```csharp string version = AppsFlyer.getSdkVersion(); ``` -------------------------------- ### getAppsFlyerId Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Retrieves AppsFlyer's Unique Device ID, which is created for every new install of an app. ```APIDOC ## getAppsFlyerId ### Description Retrieves AppsFlyer's Unique Device ID, which is created for every new install of an app. ### Method `string getAppsFlyerId()` ### Parameters None ### Request Example ```csharp string uid = AppsFlyer.getAppsFlyerId(); ``` ### Response #### Success Response - **uid** (string) - AppsFlyer's Unique Device ID #### Response Example ```json { "uid": "1234567890" } ``` ``` -------------------------------- ### Set Sandbox Mode Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/purchase-connector.md Enable sandbox mode for testing purchases. Remember to disable this before releasing to production. ```csharp AppsFlyerPurchaseConnector.setIsSandbox(true); ``` -------------------------------- ### Get Facebook Attribution ID Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Retrieves the Facebook attribution ID if available. This method is specific to Android builds. ```csharp #if UNITY_ANDROID && !UNITY_EDITOR string attributionId = AppsFlyer.getAttributionId(); #endif ``` -------------------------------- ### Check if App is Pre-Installed Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Determines if the application was pre-installed by the manufacturer. This is a boolean indicator for preinstall attribution. ```csharp #if UNITY_ANDROID && !UNITY_EDITOR if (AppsFlyer.isPreInstalledApp()) { } #endif ``` -------------------------------- ### Initialize AppsFlyer SDK and Purchase Connector Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/purchase-connector.md Initializes the AppsFlyer SDK and the Purchase Connector. Ensure to set the correct App IDs for different platforms and configure sandbox mode for testing. Auto-logging for subscriptions and in-app purchases should be enabled for production. ```csharp using System.Collections.Generic; using UnityEngine; using AppsFlyerSDK; using AppsFlyerConnector; public class AppsFlyerObjectScript : MonoBehaviour, IAppsFlyerConversionData, IAppsFlyerPurchaseValidation, IAppsFlyerPurchaseRevenueDataSource, IAppsFlyerPurchaseRevenueDataSourceStoreKit2 { [Header("AppsFlyer Configuration")] public string devKey = "YOUR_DEV_KEY"; public string appID = "YOUR_APP_ID"; public string UWPAppID = "YOUR_UWP_APP_ID"; public string macOSAppID = "YOUR_MACOS_APP_ID"; public bool isDebug = true; public bool getConversionData = true; void Start() { // 1. Initialize AppsFlyer SDK #if UNITY_WSA_10_0 && !UNITY_EDITOR AppsFlyer.initSDK(devKey, UWPAppID, getConversionData ? this : null); #elif UNITY_STANDALONE_OSX && !UNITY_EDITOR AppsFlyer.initSDK(devKey, macOSAppID, getConversionData ? this : null); #else AppsFlyer.initSDK(devKey, appID, getConversionData ? this : null); #endif AppsFlyer.setIsDebug(isDebug); // 2. Initialize and configure Purchase Connector (using separate repository approach) AppsFlyerPurchaseConnector.init(this, AppsFlyerConnector.Store.GOOGLE); AppsFlyerPurchaseConnector.setIsSandbox(true); // Remove for production AppsFlyerPurchaseConnector.setAutoLogPurchaseRevenue( AppsFlyerAutoLogPurchaseRevenueOptions.AppsFlyerAutoLogPurchaseRevenueOptionsAutoRenewableSubscriptions, AppsFlyerAutoLogPurchaseRevenueOptions.AppsFlyerAutoLogPurchaseRevenueOptionsInAppPurchases ); AppsFlyerPurchaseConnector.setPurchaseRevenueValidationListeners(true); // 3. Build and start AppsFlyerPurchaseConnector.build(); AppsFlyerPurchaseConnector.startObservingTransactions(); // 4. Start AppsFlyer SDK AppsFlyer.startSDK(); Debug.Log("AppsFlyer SDK + Purchase Connector (separate repository) initialized successfully"); } // --- Purchase Revenue Data Sources --- public Dictionary PurchaseRevenueAdditionalParametersForProducts( HashSet products, HashSet transactions) { return new Dictionary { ["implementation_type"] = "separate_repository", ["additional_param"] = "value", ["product_count"] = products.Count, ["transaction_count"] = transactions.Count }; } public Dictionary PurchaseRevenueAdditionalParametersStoreKit2ForProducts( HashSet products, HashSet transactions) { // Note: StoreKit 2 support depends on Purchase Connector version return new Dictionary { ["implementation_type"] = "separate_repository_sk2", ["additional_param"] = "sk2_value", ["product_count"] = products.Count, ["transaction_count"] = transactions.Count }; } // --- Purchase Validation Callbacks --- public void didReceivePurchaseRevenueValidationInfo(string validationInfo) { AppsFlyer.AFLog("didReceivePurchaseRevenueValidationInfo", validationInfo); Debug.Log("Purchase validation success: " + validationInfo); // Parse and handle validation info var dict = AFMiniJSON.Json.Deserialize(validationInfo) as Dictionary; #if UNITY_ANDROID if (dict.ContainsKey("productPurchase")) { Debug.Log("Android in-app purchase validated"); } else if (dict.ContainsKey("subscriptionPurchase")) { Debug.Log("Android subscription validated"); } #endif } public void didReceivePurchaseRevenueError(string error) { AppsFlyer.AFLog("didReceivePurchaseRevenueError", error); Debug.LogError("Purchase validation error: " + error); } // --- Conversion Data Callbacks --- public void onConversionDataSuccess(string conversionData) { AppsFlyer.AFLog("onConversionDataSuccess", conversionData); var dict = AppsFlyer.CallbackStringToDictionary(conversionData); // Handle deferred deep linking } public void onConversionDataFail(string error) { AppsFlyer.AFLog("onConversionDataFail", error); } public void onAppOpenAttribution(string attributionData) { AppsFlyer.AFLog("onAppOpenAttribution", attributionData); var dict = AppsFlyer.CallbackStringToDictionary(attributionData); // Handle direct deep linking } public void onAppOpenAttributionFailure(string error) { AppsFlyer.AFLog("onAppOpenAttributionFailure", error); } } ``` -------------------------------- ### onConversionDataSuccess Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Callback function that is triggered when conversion data is successfully received. This data contains information about the install, such as organic/non-organic status. ```APIDOC ## onConversionDataSuccess ### Description Callback function that is triggered when conversion data is successfully received. This data contains information about the install, such as organic/non-organic status. ### Method `public void onConversionDataSuccess(string conversionData)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **conversionData** (string) - JSON string of the returned conversion data ### Request Example ```c# public void onConversionDataSuccess(string conversionData) { AppsFlyer.AFLog("onConversionDataSuccess", conversionData); Dictionary conversionDataDictionary = AppsFlyer.CallbackStringToDictionary(conversionData); // add deferred deeplink logic here } ``` ### Response None ### Response Example None ``` -------------------------------- ### Initialization Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/purchase-connector.md Initializes the Purchase Connector with the appropriate store type. This should be called early in your application's lifecycle. ```APIDOC ## Initialization ### Description Initializes the Purchase Connector with the appropriate store type. This should be called early in your application's lifecycle. ### Method `AppsFlyerPurchaseConnector.init(this, Store.GOOGLE)` ### Parameters - **this** (object) - The current Unity MonoBehaviour instance. - **Store.GOOGLE** (AppsFlyerConnector.Store) - Specifies the store as Google Play. ``` -------------------------------- ### Enable TCF Data Collection Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/DMAConsent.md Automatically collect and send TCF (Transparency and Consent Framework) strings. This should be called before starting the SDK. ```APIDOC ## enableTCFDataCollection ### Description Enables or disables the automatic collection of TCF strings for DMA compliance. ### Method Signature `AppsFlyer.enableTCFDataCollection(bool enable)` ### Parameters - **enable** (bool) - Required - Set to `true` to enable TCF data collection, `false` to disable. ### Notes Call this method **before** `AppsFlyer.startSDK()` to ensure the first session includes the correct consent signals. ``` -------------------------------- ### Initialize Purchase Connector with Store Type Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/purchase-connector.md Initializes the Purchase Connector, specifying the target store. Ensure the correct store enum is passed. ```csharp // Initialize Purchase Connector with store type AppsFlyerPurchaseConnector.init(this, Store.GOOGLE); ``` -------------------------------- ### Attribute and Open Store Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Attributes a click and launches the app store's app page. Implement the IAppsFlyerUserInvite interface to receive callbacks. ```csharp Dictionary parameters = new Dictionary(); parameters.Add("af_sub1", "val"); parameters.Add("custom_param", "val2"); AppsFlyer.attributeAndOpenStore("123456789", "test campaign", parameters, this); ``` -------------------------------- ### Build Purchase Connector Configuration Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/purchase-connector.md Builds the Purchase Connector with all previously configured settings. This must be called after all configuration methods. ```csharp // Build the Purchase Connector with all configurations AppsFlyerPurchaseConnector.build(); ``` -------------------------------- ### Set Additional Data Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Adds custom data, primarily for integrations with platforms like Segment, Adobe, and Urban Airship. Use only when specified in integration guides. ```csharp Dictionary customData = new Dictionary(); customData.Add("custom1", "someData"); AppsFlyer.setAdditionalData(customData); ``` -------------------------------- ### initSDK Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Initializes the AppsFlyer SDK. This method is available for Android, iOS, and Windows. ```APIDOC ## initSDK ### Description Initializes the AppsFlyer SDK. This is a crucial first step before calling other SDK methods. ### Method Not specified (assumed to be a method call within the Unity plugin). ### Endpoint N/A (SDK method) ### Parameters None explicitly documented for this method signature. ### Request Example ```csharp AppsFlyer.initSDK(); ``` ### Response None explicitly documented. ``` -------------------------------- ### attributeAndOpenStore Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Attributes the click and launches the app store's app page. Callbacks can be received by implementing the IAppsFlyerUserInvite interface. ```APIDOC ## attributeAndOpenStore ### Description Attributes the click and launches the app store's app page. Callbacks can be received by implementing the IAppsFlyerUserInvite interface. ### Method `void attributeAndOpenStore(string appID, string campaign, Dictionary userParams, MonoBehaviour gameObject)` ### Parameters #### Path Parameters - `appID` (string) - Required - - `campaign` (string) - Required - - `userParams` (Dictionary) - Required - - `gameObject` (MonoBehaviour) - Required - game object with the IAppsFlyerUserInvite interface ### Request Example ```csharp Dictionary parameters = new Dictionary(); parameters.Add("af_sub1", "val"); parameters.Add("custom_param", "val2"); AppsFlyer.attributeAndOpenStore("123456789", "test campaign", parameters, this); ``` ``` -------------------------------- ### Handle Open URL for Deep Linking Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Manually track deep linking by calling this method with the URL, source application, and annotation. This is an alternative if the default `continueUserActivity` and `onOpenURL` methods do not cover your deep linking needs. ```csharp #if UNITY_IOS && !UNITY_EDITOR AppsFlyer.handleOpenUrl(string url, string sourceApplication, string annotation); #endif ``` -------------------------------- ### Use Uninstall Sandbox (iOS) Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Set this flag to test uninstall on Apple's environment (production or sandbox). The default value is false. This is an iOS-only setting. ```csharp #if UNITY_IOS && !UNITY_EDITOR AppsFlyer.setUseUninstallSandbox(true); #endif ``` -------------------------------- ### setPreinstallAttribution Source: https://github.com/appsflyersdk/appsflyer-unity-plugin/blob/master/docs/API.md Specifies the media source, campaign, and site ID for preinstall attribution. ```APIDOC ## setPreinstallAttribution ### Description Specify the manufacturer or media source name to which the preinstall is attributed. ### Method `void setPreinstallAttribution(string mediaSource, string campaign, string siteId)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **mediaSource** (string) - Required - Manufacturer or media source name for preinstall attribution. - **campaign** (string) - Required - Campaign name for preinstall attribution. - **siteId** (string) - Required - Site ID for preinstall attribution. ### Request Example ```csharp #if UNITY_ANDROID && !UNITY_EDITOR AppsFlyer.setPreinstallAttribution("mediaSource", "campaign", "siteId"); #endif ``` ### Response None ```