### Full AppsFlyer Purchase Connector Setup and Event Handling Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_PurchaseConnector.md This example demonstrates the complete setup of the AppsFlyer Purchase Connector, including configuration, event listener registration for Android and iOS, and starting transaction observation. It also includes cleanup logic for event listeners. ```javascript import appsFlyer, { StoreKitVersion, AppsFlyerPurchaseConnector, AppsFlyerPurchaseConnectorConfig, } from 'react-native-appsflyer'; const purchaseConnectorConfig = AppsFlyerPurchaseConnectorConfig.setConfig({ logSubscriptions: true, logInApps: true, sandbox: true, storeKitVersion: StoreKitVersion.SK2 }); AppsFlyerPurchaseConnector.create(purchaseConnectorConfig); const handleValidationSuccess = (validationResult) => { console.log('>> ValidationSuccess: ', validationResult); }; const handleValidationFailure = (validationResult) => { console.log('>> ValidationFailure: ', validationResult); } const handleSubscriptionValidationSuccess = (subscriptionValidationResult) => { console.log('>> handleSubscriptionValidationSuccess: ', subscriptionValidationResult); }; const handleSubscriptionValidationFailure = (subscriptionValidationResult) => { console.log('>> handleSubscriptionValidationFailure: ', subscriptionValidationResult); } const handleOnReceivePurchaseRevenueValidationInfo = (validationInfo, error) => { if (error) { console.error("Error during purchase validation:", error); } else { console.log("Validation Info:", validationInfo); } } useEffect(() => { let validationSuccessListener; let validationFailureListener; let subscriptionValidationSuccessListener; let subscriptionValidationFailureListener; let purchaseRevenueValidationListener; if (Platform.OS === 'android') { validationSuccessListener = AppsFlyerPurchaseConnector.onInAppValidationResultSuccess(handleValidationSuccess); validationFailureListener = AppsFlyerPurchaseConnector.onInAppValidationResultFailure(handleValidationFailure); subscriptionValidationSuccessListener = AppsFlyerPurchaseConnector.onSubscriptionValidationResultSuccess(handleSubscriptionValidationSuccess); subscriptionValidationFailureListener = AppsFlyerPurchaseConnector.onSubscriptionValidationResultFailure(handleSubscriptionValidationFailure); } else { console.log('>> Creating purchaseRevenueValidationListener '); purchaseRevenueValidationListener = AppsFlyerPurchaseConnector.OnReceivePurchaseRevenueValidationInfo(handleOnReceivePurchaseRevenueValidationInfo); } // Cleanup function return () => { if (Platform.OS === 'android') { if (validationSuccessListener) validationSuccessListener.remove(); if (validationFailureListener) validationFailureListener.remove(); if (subscriptionValidationSuccessListener) subscriptionValidationSuccessListener.remove(); if (subscriptionValidationFailureListener) subscriptionValidationFailureListener.remove(); } else { if (purchaseRevenueValidationListener) purchaseRevenueValidationListener.remove(); } }; }, []); AppsFlyerPurchaseConnector.startObservingTransactions(); //AppsFlyerPurchaseConnector.stopObservingTransactions(); ``` -------------------------------- ### JSON Legacy Method: Setup Listeners, Initialize, and Start SDK Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_PushNotification.md For the JSON Legacy Method, set up listeners for install conversion data and deep links before initializing and starting the SDK. The SDK automatically detects the 'af' object in the payload. ```jsx // 1. Set up listeners (BEFORE init) appsFlyer.onInstallConversionData((data) => { console.log('Install conversion data:', data); }); appsFlyer.onDeepLink((data) => { console.log('Deep link data:', data); }); // 2. Initialize and start SDK appsFlyer.initSdk({ devKey: 'YOUR_DEV_KEY', isDebug: true, appId: 'YOUR_APP_ID', }); appsFlyer.startSdk(); // 3. Handle push data the same way // The SDK will automatically detect the 'af' object in the payload ``` -------------------------------- ### Complete AppsFlyer Push Integration Example Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_PushNotification.md This comprehensive example demonstrates setting up attribution and deep link handlers, configuring push notification deep link paths, initializing and starting the AppsFlyer SDK, and handling both background and foreground push messages. ```jsx import React, { useEffect } from 'react'; import appsFlyer from 'react-native-appsflyer'; import messaging from '@react-native-firebase/messaging'; const AppsflyerPushIntegration = () => { useEffect(() => { // 1. Set up attribution and deep link handlers (BEFORE init) appsFlyer.onInstallConversionData((data) => { console.log('Conversion data:', data); }); appsFlyer.onDeepLink((data) => { console.log('Deep link:', data); }); // 2. Configure push notification deep link path (BEFORE init) appsFlyer.addPushNotificationDeepLinkPath( ['af_push_link'], // Adjust based on your payload structure (success) => console.log('Push path configured'), (error) => console.error('Push path error:', error) ); // 3. Initialize AppsFlyer SDK (AFTER listeners and config) appsFlyer.initSdk({ devKey: 'YOUR_DEV_KEY', isDebug: true, appId: 'YOUR_APP_ID', }); // 4. Start AppsFlyer (AFTER init) appsFlyer.startSdk(); // 5. Set up push notification handlers const handlePushData = (payload) => { appsFlyer.sendPushNotificationData( payload, (error) => console.error('Push data error:', error) ); }; // Background messages messaging().setBackgroundMessageHandler(async (message) => { handlePushData(message.data); }); // Foreground messages const unsubscribe = messaging().onMessage(async (message) => { handlePushData(message.data); }); // Notification opened from background messaging().onNotificationOpenedApp((message) => { handlePushData(message.data); }); }, []); return null; // This is just a setup component }; export default AppsflyerPushIntegration; ``` -------------------------------- ### Install with autolinking Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_Installation.md Standard installation method using npm and CocoaPods. ```bash $ npm install react-native-appsflyer --save $ cd ios && pod install ``` -------------------------------- ### Initialize SDK for Manual Start Source: https://context7.com/appsflyersdk/appsflyer-react-native-plugin/llms.txt Initializes the SDK with `manualStart` set to true, allowing for delayed SDK activation. The SDK will not start until `startSdk()` is explicitly called. ```javascript import appsFlyer from 'react-native-appsflyer'; // Initialize with manual start enabled appsFlyer.initSdk( { devKey: 'YOUR_DEV_KEY', appId: '123456789', isDebug: true, onInstallConversionDataListener: true, onDeepLinkListener: true, manualStart: true, // Delay SDK start }, () => console.log('SDK init complete, not started yet'), (err) => console.error(err) ); ``` -------------------------------- ### Install Dependencies Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/demos/appsflyer-expo-app/README.md Run this command in the root directory of the application to install required packages. ```bash yarn install ``` -------------------------------- ### Platform-Specific Purchase Data Source Setup Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_PurchaseConnector.md Implement platform-specific logic to set the correct purchase revenue or subscription data sources. This example handles iOS StoreKit1, iOS StoreKit2, and Android data sources. ```javascript import { Platform } from 'react-native'; import { AppsFlyerPurchaseConnector } from 'react-native-appsflyer'; const setupPurchaseDataSources = () => { if (Platform.OS === 'ios') { // iOS StoreKit1 data source AppsFlyerPurchaseConnector.setPurchaseRevenueDataSource({ additionalParameters: { user_id: '12345', user_type: 'premium', purchase_source: 'app_store' } }); // iOS StoreKit2 data source (iOS 15.0+) AppsFlyerPurchaseConnector.setPurchaseRevenueDataSourceStoreKit2({ additionalParameters: { user_id: '12345', user_type: 'premium', purchase_source: 'app_store' } }); } else if (Platform.OS === 'android') { // Android subscription data source AppsFlyerPurchaseConnector.setSubscriptionPurchaseEventDataSource({ additionalParameters: { user_id: '12345', user_type: 'premium', purchase_source: 'play_store' } }); // Android in-app purchase data source AppsFlyerPurchaseConnector.setInAppPurchaseEventDataSource({ additionalParameters: { user_id: '12345', user_type: 'premium', purchase_source: 'play_store' } }); } }; ``` -------------------------------- ### Initialize and Start AppsFlyer SDK (React Native) Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_PushNotification.md Initialize the AppsFlyer SDK with your developer key and app ID (for iOS), and then start the SDK. This should be done after setting up all listeners and configurations. ```jsx // Initialize AppsFlyer (AFTER setting up listeners) appsFlyer.initSdk({ devKey: 'YOUR_DEV_KEY', isDebug: true, appId: 'YOUR_APP_ID', // iOS only }); // Start AppsFlyer (AFTER init) appsFlyer.startSdk(); ``` -------------------------------- ### Install Expo Dev Client Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_ExpoInstallation.md Install the expo-dev-client package to manage development builds. Refer to Expo documentation for more details. ```bash expo install expo-dev-client ``` -------------------------------- ### Install without autolinking Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_Installation.md Legacy installation method using react-native link. ```bash $ npm install react-native-appsflyer --save $ react-native link react-native-appsflyer ``` -------------------------------- ### Start SDK Manually Source: https://context7.com/appsflyersdk/appsflyer-react-native-plugin/llms.txt Call this method after `initSdk` with `manualStart: true` to begin SDK operations, typically after obtaining user consent. ```javascript // Later, after user consent or other conditions const onUserConsent = () => { appsFlyer.startSdk(); console.log('SDK started after user consent'); }; ``` -------------------------------- ### initSdk Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_Integration.md Initializes the AppsFlyer SDK to track installations, sessions, and updates. ```APIDOC ## initSdk ### Description Initializes the AppsFlyer SDK to enable detection of installations, sessions, and updates. ### Parameters #### Request Body - **devKey** (string) - Required - Your application devKey provided by AppsFlyer. - **appId** (string) - Optional (iOS only) - The App ID configured in your AppsFlyer dashboard. - **isDebug** (boolean) - Optional - Set to true for testing purposes. - **onInstallConversionDataListener** (boolean) - Optional - Set listener for GCD response (default=true). - **onDeepLinkListener** (boolean) - Optional - Set listener for UDL response (default=false). - **timeToWaitForATTUserAuthorization** (number) - Optional - Time in seconds to wait for user authorization to access app-related data. ### Request Example { "devKey": "K2***********99", "isDebug": false, "appId": "41*****44", "onInstallConversionDataListener": true, "onDeepLinkListener": true, "timeToWaitForATTUserAuthorization": 10 } ``` -------------------------------- ### Install AppsFlyer React Native Plugin Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_ExpoInstallation.md Install the react-native-appsflyer package using expo install. ```bash expo install react-native-appsflyer ``` -------------------------------- ### Verify iOS Launch Event Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_Testing.md Example of a successful launch event log entry in the iOS console. ```text <~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~~+~> <~+~ SEND Start: https://launches.appsflyer.com/api/v6.4/iosevent?app_id=7xXxXxX1&buildnumber=6.4.4 <~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~~+~> { launch event payload } // Just an example of a JSON. you will see the full payload ``` -------------------------------- ### AppsFlyer SDK Initialization and Core APIs Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_API.md APIs for initializing the SDK, starting its operation, and core event logging. ```APIDOC ## initSdk ### Description Initializes the AppsFlyer SDK. ### Method Not specified (typically called once during app initialization) ### Endpoint N/A (SDK method) ## startSdk ### Description Starts the AppsFlyer SDK. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## logEvent ### Description Logs a custom in-app event. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## setCustomerUserId ### Description Sets a custom user ID for tracking. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## stop ### Description Stops the AppsFlyer SDK. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## setAppInviteOneLinkID ### Description Sets the One Link ID for app invites. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## setAdditionalData ### Description Sets additional data to be sent with SDK events. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## setResolveDeepLinkURLs ### Description Sets URLs to resolve deep links. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## setOneLinkCustomDomains ### Description Sets custom domains for One Link. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## setCurrencyCode ### Description Sets the currency code for in-app events. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## logLocation ### Description Logs the user's location. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## anonymizeUser ### Description Anonymizes the user's data. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## getAppsFlyerUID ### Description Retrieves the AppsFlyer unique ID. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## setHost ### Description Sets a custom host for SDK communication. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## setUserEmails *Soon to be deprecated* ### Description Sets user emails (soon to be deprecated). ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## generateInviteLink ### Description Generates an invite link. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## setSharingFilterForAllPartners ### Description Sets a sharing filter for all partners. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## setSharingFilter ### Description Sets a sharing filter. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## setSharingFilterForPartners ### Description Sets a sharing filter for specific partners. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## validateAndLogInAppPurchase ### Description Validates and logs an in-app purchase. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## validateAndLogInAppPurchaseV2 ### Description Validates and logs an in-app purchase (version 2). ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## updateServerUninstallToken ### Description Updates the server uninstall token. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## sendPushNotificationData ### Description Sends push notification data. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## addPushNotificationDeepLinkPath ### Description Adds a path for push notification deep linking. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## appendParametersToDeepLinkingURL ### Description Appends parameters to deep linking URLs. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## disableAdvertisingIdentifier ### Description Disables advertising identifier collection. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## enableTCFDataCollection ### Description Enables TCF data collection. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## setConsentData ### Description Sets consent data. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ## logAdRevenue ### Description Logs ad revenue. ### Method Not specified (SDK method) ### Endpoint N/A (SDK method) ``` -------------------------------- ### Initialize Purchase Connector and Observe Transactions Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_PurchaseConnector.md Demonstrates the correct sequence for initializing the AppsFlyer Purchase Connector, setting data sources, and starting transaction observation. Use `sandbox: true` for testing. ```javascript // 1. Create the connector // StoreKit1 (default) AppsFlyerPurchaseConnector.create({ logSubscriptions: true, logInApps: true, sandbox: __DEV__, // storeKitVersion: StoreKitVersion.SK1 // Optional - defaults to SK1 }); // OR for StoreKit2 (iOS 15.0+) // AppsFlyerPurchaseConnector.create({ // logSubscriptions: true, // logInApps: true, // sandbox: __DEV__, // storeKitVersion: StoreKitVersion.SK2 // }); // 2. Set up data sources setupPurchaseDataSources(); // 3. Start observing transactions await AppsFlyerPurchaseConnector.startObservingTransactions(); ``` -------------------------------- ### Verify Android Launch Event Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_Testing.md Example of a successful launch event log entry in the Android logcat. ```text I/AppsFlyer_6.4.3: url: https://launches.appsflyer.com/api/v6.4/androidevent?app_id=com.aXxXxt.rxXxXxt&buildnumber=6.4.3 I/AppsFlyer_6.4.3: data: { launch event payload } // Just an example of a JSON. you will see the full payload ``` -------------------------------- ### Initialize and Manually Start AppsFlyer SDK Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_API.md Initialize the AppsFlyer SDK with manualStart set to true, then call startSdk() later to send the launch request. This allows for controlling when the SDK reports the app launch. ```javascript const option = { isDebug: true, devKey: 'UsxXxXxed', appId: '75xXxXxXxXx11', onInstallConversionDataListener: true, onDeepLinkListener: true, timeToWaitForATTUserAuthorization: 5, manualStart: true, // <--- for manual start. }; appsFlyer.initSdk( option, () => { if (!option.manualStart) { console.warn('AppsFlyer SDK started!'); } else { console.warn('AppsFlyer SDK init, didn\'t send launch yet'); } }, err => { // handle error }, ); //... // app flow //... appsFlyer.startSdk(); // <--- Here we send launch ``` -------------------------------- ### Start Observing Transactions with StoreKit1/StoreKit2 Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_PurchaseConnector.md Initiates the AppsFlyer SDK and configures the purchase connector to observe new billing transactions, including subscriptions and in-app purchases. Ensure `startSdk()` is called prior to this. For StoreKit2, specify `storeKitVersion: StoreKitVersion.SK2`. ```javascript import appsFlyer, { AppsFlyerPurchaseConnector, AppsFlyerPurchaseConnectorConfig, StoreKitVersion, } from 'react-native-appsflyer'; appsFlyer.startSdk(); // StoreKit1 example (default behavior) const purchaseConnectorConfig: PurchaseConnectorConfig = AppsFlyerPurchaseConnectorConfig.setConfig({ logSubscriptions: true, logInApps: true, sandbox: true, // storeKitVersion: StoreKitVersion.SK1 // Optional - SK1 is default }); // StoreKit2 example (iOS 15.0+) // const purchaseConnectorConfig: PurchaseConnectorConfig = AppsFlyerPurchaseConnectorConfig.setConfig({ // logSubscriptions: true, // logInApps: true, // sandbox: true, // storeKitVersion: StoreKitVersion.SK2 // }); //Create the object AppsFlyerPurchaseConnector.create(purchaseConnectorConfig); //Start listening to transactions AppsFlyerPurchaseConnector.startObservingTransactions(); ``` -------------------------------- ### Initialize AppsFlyer SDK Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_API.md Initialize the AppsFlyer SDK with your devKey and appID. Set listeners for conversion data and deep links, and configure ATT user authorization and manual start. ```javascript 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, appId: '41*****44', onInstallConversionDataListener: false, //Optional onDeepLinkListener: true, //Optional timeToWaitForATTUserAuthorization: 10, //for iOS 14.5 manualStart: true, //Optional }, (res) => { console.log(res); }, (err) => { console.error(err); } ); ``` -------------------------------- ### Initialize AppsFlyer SDK Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_Integration.md Initialize the SDK with your application's devKey and other relevant settings. Ensure `isDebug` is set to `false` in production. This configuration enables tracking of installations, sessions, and updates. ```javascript import appsFlyer from 'react-native-appsflyer'; appsFlyer.initSdk( { devKey: 'K2***********99', isDebug: false, appId: '41*****44', onInstallConversionDataListener: true, //Optional onDeepLinkListener: true, //Optional timeToWaitForATTUserAuthorization: 10 //for iOS 14.5 }, (result) => { console.log(result); }, (error) => { console.error(error); } ); ``` -------------------------------- ### onDeepLink Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_API.md Handles Universal Dynamic Link (UDL) data. Requires prior setup and SDK initialization. ```APIDOC ## POST /appsflyersdk/appsflyer-react-native-plugin/onDeepLink ### Description Listens for Universal Dynamic Link (UDL) data. Refer to the AppsFlyer documentation for deep link integration details. ### Method POST ### Endpoint /appsflyersdk/appsflyer-react-native-plugin/onDeepLink ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **callback** (function) - Required - The function to be called with UDL data. ### Request Example ```javascript const onDeepLinkCanceller = appsFlyer.onDeepLink(res => { if (res?.deepLinkStatus !== 'NOT_FOUND') { const DLValue = res?.data.deep_link_value; const mediaSrc = res?.data.media_source; const param1 = res?.data.af_sub1; console.log(JSON.stringify(res?.data, null, 2)); } }) appsFlyer.initSdk(/*...*/); ``` ### Response #### Success Response (200) - **data** (object) - Contains UDL data, potentially including `deep_link_value`, `media_source`, `af_sub1`, etc. - **deepLinkStatus** (string) - Indicates the status of the deep link (e.g., 'NOT_FOUND'). #### Response Example ```json { "data": { "deep_link_value": "your_deep_link_value", "media_source": "your_media_source", "af_sub1": "your_af_sub1_value" }, "deepLinkStatus": "FOUND" } ``` ``` -------------------------------- ### onAppOpenAttribution Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_API.md Handles deep link attribution data. Requires prior setup and SDK initialization. ```APIDOC ## POST /appsflyersdk/appsflyer-react-native-plugin/onAppOpenAttribution ### Description Listens for attribution data related to deep links. Refer to the AppsFlyer documentation for deep link integration details. ### Method POST ### Endpoint /appsflyersdk/appsflyer-react-native-plugin/onAppOpenAttribution ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **callback** (function) - Required - The function to be called with attribution data. ### Request Example ```javascript const onAppOpenAttributionCanceller = appsFlyer.onAppOpenAttribution((res) => { console.log(res); }); appsFlyer.initSdk(/*...*/); ``` ### Response #### Success Response (200) - **(object)** - Contains attribution data. Specific fields depend on the deep link implementation. #### Response Example None provided. ``` -------------------------------- ### Initialize AppsFlyer SDK with Deep Link Listener Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_UnifiedDeepLink.md Initialize the AppsFlyer SDK, ensuring `onDeepLinkListener` is set to `true` to enable the `onDeepLink` callbacks. This setup should occur after the `onDeepLink` listener is defined. ```javascript appsFlyer.initSdk( { devKey: 'K2***********99', isDebug: false, appId: '41*****44', onInstallConversionDataListener: true, onDeepLinkListener: true // --> you must set the onDeepLinkListener to true to get onDeepLink callbacks }, (result) => { console.log(result); }, (error) => { console.error(error); } ); ``` -------------------------------- ### Set Up Listeners and Push Configuration (React Native) Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_PushNotification.md Configure AppsFlyer listeners for install conversion data and deep links, and set the push notification deep link path before initializing the SDK. Adjust the path array based on your payload structure. ```jsx import appsFlyer from 'react-native-appsflyer'; // 1. Handle conversions and attribution (BEFORE init) appsFlyer.onInstallConversionData((data) => { console.log('Install conversion data:', data); }); // 2. Handle deep links (BEFORE init) appsFlyer.onDeepLink((data) => { console.log('Deep link data:', data); }); // 3. Configure push notification deep link path (BEFORE init) // For simple structure: ["af_push_link"] // For nested structure: ["data", "appsflyer", "testing", "link"] appsFlyer.addPushNotificationDeepLinkPath( ['af_push_link'], // Adjust based on your payload structure (success) => { console.log('Push notification path added successfully:', success); }, (error) => { console.error('Error adding push notification path:', error); } ); ``` -------------------------------- ### Enable TCF data collection with CMP Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_CMP.md Configures the SDK to retrieve consent data from a TCF-compliant CMP and demonstrates the manual start flow. ```javascript useEffect(() => { const option = { isDebug: true, devKey: 'UxXxXxXxXd', onInstallConversionDataListener: true, onDeepLinkListener: true, timeToWaitForATTUserAuthorization: 10, manualStart: true, // <-- Manual start }; // TCF data collection appsFlyer.enableTCFDataCollection(true); //init appsflyer appsFlyer.initSdk( option, res => { console.log(res); }, err => { console.log(err); }, ); ... // CMP Pseudocode if (cmpManager.hasConsent()) { appsFlyer.startSdk(); } else { cmpManager.presentConsentDialog(res => { appsFlyer.startSdk(); }); } },[]) ``` -------------------------------- ### Configure Android Manifest for Merge Conflicts Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_EspIntegration.md Example of using the tools namespace to resolve manifest merger conflicts. ```xml ``` -------------------------------- ### Verify iOS Response Code Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_Testing.md Example of a successful HTTP response log entry in the iOS console. ```text Result: { data = {length = 64, bytes = 0x7b226f6c 5f696422 3a224476 5769222c ... 696e6b2e 6d65227d }; dataStr = "{\"oxXxXxd\":\"DXxXxi\",\"oXxXer\":ss,\"olXxXxain\":\"xXxXxXx\"}"; retries = 2; statusCode = 200; // ~~> success! taskIdentifier = 4; } ``` -------------------------------- ### Start Observing Transactions Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_PurchaseConnector.md Activates a listener that automatically observes new billing transactions, including subscriptions and in-app purchases. ```APIDOC ## AppsFlyerPurchaseConnector.startObservingTransactions() ### Description Activates a listener that automatically observes new billing transactions. This includes new and existing subscriptions and new in-app purchases. It should be called after `appsFlyer.startSdk()` and after creating the connector instance. ### Request Example ```javascript const purchaseConnectorConfig = AppsFlyerPurchaseConnectorConfig.setConfig({ logSubscriptions: true, logInApps: true, sandbox: true }); AppsFlyerPurchaseConnector.create(purchaseConnectorConfig); AppsFlyerPurchaseConnector.startObservingTransactions(); ``` ``` -------------------------------- ### Register Conversion Data Listener Source: https://context7.com/appsflyersdk/appsflyer-react-native-plugin/llms.txt Register listeners for install conversion data and failures before initializing the SDK. Ensure listeners are cleaned up when the component unmounts. ```javascript import appsFlyer from 'react-native-appsflyer'; // Register conversion data listener BEFORE initSdk const onInstallConversionDataCanceller = appsFlyer.onInstallConversionData( (res) => { const isFirstLaunch = JSON.parse(res.data.is_first_launch); if (isFirstLaunch) { if (res.data.af_status === 'Non-organic') { const mediaSource = res.data.media_source; const campaign = res.data.campaign; console.log('Non-organic install from:', mediaSource, campaign); // Handle deferred deep link based on campaign data } else { console.log('Organic install'); } } else { console.log('Not first launch'); } } ); // Register failure listener const onInstallFailureCanceller = appsFlyer.onInstallConversionFailure( (res) => { console.error('Conversion data error:', res.data); } ); // Initialize SDK after registering listeners appsFlyer.initSdk({ devKey: 'YOUR_DEV_KEY', appId: '123456789', onInstallConversionDataListener: true, }); // Cleanup listeners when component unmounts // onInstallConversionDataCanceller(); // onInstallFailureCanceller(); ``` -------------------------------- ### performOnDeepLinking Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_API.md Enables manual triggering of deep link resolution. This method allows apps that are delaying the call to `appsFlyer.startSdk()` to resolve deep links before the SDK starts. ```APIDOC ## performOnDeepLinking ### Description Enables manual triggering of deep link resolution. This method allows apps that are delaying the call to `appsFlyer.startSdk()` to resolve deep links before the SDK starts. This API will trigger the `appsFlyer.onDeepLink` callback. ### Method `performOnDeepLinking()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript // Let's say we want the resolve a deeplink and get the deeplink params when the user clicks on it but delay the actual 'start' of the sdk (not sending launch to appsflyer). const option = { isDebug: true, devKey: 'UsxXxXxed', appId: '75xXxXxXxXx11', onInstallConversionDataListener: true, onDeepLinkListener: true, manualStart: true, // <--- for manual start. }; const onDeepLink = appsFlyer.onDeepLink(res => { if (res.deepLinkStatus == 'FOUND') { // here we will get the deeplink params after resolving it. // more flow... } }); appsFlyer.initSdk( option, () => { if (!option.manualStart) { console.warn('AppsFlyer SDK started!'); } else { console.warn('AppsFlyer SDK init, didn\'t send launch yet'); } }, () => {}, // Error callback ); if (Platform.OS == 'android') { appsFlyer.performOnDeepLinking(); } // more app flow... appsFlyer.startSdk(); // <--- Here we send launch ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### OneLink Method: Session Payload Example Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_PushNotification.md When using the OneLink method, the session payload will contain 'af_deeplink' and meta information about the payload key. ```json { "af_deeplink": "https://yourapp.onelink.me/", "meta": { "payloadKey": [["af_push_link"]] } } ``` -------------------------------- ### Full app.json Example for Expo Deep Linking Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_ExpoDeepLinkIntegration.md This JSON configuration is for the `app.json` file in an Expo project. It includes settings for AppsFlyer integration, such as plugins, URI schemes, and platform-specific configurations for Android and iOS deep linking. ```json { "expo": { "name": "expoAppsFlyer", "slug": "expoAppsFlyer", "version": "1.0.0", "orientation": "portrait", "icon": "./assets/atom.png", "plugins": [ [ "react-native-appsflyer", { "shouldUseStrictMode": true } // <<-- only for strict mode ] ], "splash": { "image": "./assets/splash.png", "resizeMode": "contain", "backgroundColor": "#ffffff" }, "updates": { "fallbackToCacheTimeout": 0 }, "assetBundlePatterns": ["**/*"], "scheme": "my-own-scheme", // <<-- uri scheme as configured on AF dashboard "ios": { "supportsTablet": true, "bundleIdentifier": "com.appsflyer.expoaftest", "associatedDomains": ["applinks:expotest.onelink.me"] // <<-- important in order to use universal links }, "android": { "adaptiveIcon": { "foregroundImage": "./assets/adaptive-icon.png", "backgroundColor": "#FFFFFF" }, "package": "com.af.expotest", "intentFilters": [ { "action": "VIEW", "data": [ { "scheme": "https", "host": "expotest.onelink.me", // <<-- important for android App Links "pathPrefix": "/DvWi" // <<-- set your onelink template id } ], "category": ["BROWSABLE", "DEFAULT"] }, { "action": "VIEW", "data": [ { "scheme": "my-own-scheme" // <<-- uri scheme as configured on AF dashboard } ], "category": ["BROWSABLE", "DEFAULT"] } ] }, "web": { "favicon": "./assets/favicon.png" } } } ``` -------------------------------- ### Configure and Generate User Invite Links Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_UserInvite.md Sets the OneLink template ID and generates a custom invite link. Ensure setAppInviteOneLinkID is called before the SDK start method. ```javascript // set the template ID before you generate a link. Without it UserInvite won't work. appsFlyer.setAppInviteOneLinkID('scVs', null); // set the user invite params appsFlyer.generateInviteLink( { channel: 'gmail', campaign: 'myCampaign', customerID: '1234', userParams: { deep_link_value : 'value', // deep link param deep_link_sub1 : 'sub1', // deep link param custom_param : 'custom', brandDomain:'myexample.com' }, }, (link) => { console.log(link); }, (err) => { console.log(err); } ); ``` -------------------------------- ### startSdk Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_API.md Manually triggers the SDK launch request when manualStart is enabled in the initSdk configuration. ```APIDOC ## startSdk ### Description Triggers the SDK to send the launch request. This is used when manualStart is set to true in the initSdk configuration. ### Request Example ```javascript appsFlyer.startSdk(); ``` ``` -------------------------------- ### Set Customer User ID Source: https://context7.com/appsflyersdk/appsflyer-react-native-plugin/llms.txt Set a custom user ID for cross-referencing. Call before SDK start for install attribution or anytime for event attribution. ```javascript import appsFlyer from 'react-native-appsflyer'; // Set customer user ID before SDK start for install attribution appsFlyer.setCustomerUserId('user_12345', (res) => { console.log('Customer ID set:', res); }); // Initialize SDK after setting customer ID appsFlyer.initSdk({ devKey: 'YOUR_DEV_KEY', appId: '123456789', }); // Or set after login for event attribution const onUserLogin = (userId) => { appsFlyer.setCustomerUserId(userId, (res) => { console.log('Customer ID updated after login'); }); }; ``` -------------------------------- ### Initialize AppsFlyer SDK with Callbacks Source: https://context7.com/appsflyersdk/appsflyer-react-native-plugin/llms.txt Basic SDK initialization using callbacks. Ensure `devKey` is replaced with your actual key. `isDebug` should be false in production. `appId` is required for iOS. ```javascript import appsFlyer from 'react-native-appsflyer'; // Basic SDK initialization with callbacks appsFlyer.initSdk( { devKey: 'YOUR_DEV_KEY', isDebug: true, // Set to false in production appId: '123456789', // iOS App Store ID onInstallConversionDataListener: true, // Enable conversion data onDeepLinkListener: true, // Enable unified deep linking timeToWaitForATTUserAuthorization: 10, // iOS 14.5+ ATT timeout manualStart: false, // Set true to delay SDK start }, (result) => { console.log('SDK initialized successfully:', result); }, (error) => { console.error('SDK initialization failed:', error); } ); ``` -------------------------------- ### Initialize AppsFlyer SDK with Promises Source: https://context7.com/appsflyersdk/appsflyer-react-native-plugin/llms.txt Promise-based SDK initialization. Handles success and errors using async/await. Replace `YOUR_DEV_KEY` with your actual developer key. ```javascript const initSDK = async () => { try { const result = await appsFlyer.initSdk({ devKey: 'YOUR_DEV_KEY', isDebug: false, appId: '123456789', onInstallConversionDataListener: true, onDeepLinkListener: true, }); console.log('SDK initialized:', result); } catch (error) { console.error('SDK error:', error); } }; ``` -------------------------------- ### Configure PurchaseConnector with StoreKit1 (Default) Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_PurchaseConnector.md Sets up the PurchaseConnector configuration using StoreKit1, which is the default if storeKitVersion is not specified. Ensure sandbox is set to false for production. ```javascript import appsFlyer, { AppsFlyerPurchaseConnector, AppsFlyerPurchaseConnectorConfig, StoreKitVersion, } from 'react-native-appsflyer'; // Example 1: StoreKit1 (default if storeKitVersion is not specified) const purchaseConnectorConfig: PurchaseConnectorConfig = AppsFlyerPurchaseConnectorConfig.setConfig({ logSubscriptions: true, logInApps: true, sandbox: true, // storeKitVersion defaults to StoreKit1 if not specified }); ``` -------------------------------- ### Retrieve AppsFlyer UID Source: https://context7.com/appsflyersdk/appsflyer-react-native-plugin/llms.txt Fetch the unique device ID assigned by AppsFlyer for the current installation. ```javascript import appsFlyer from 'react-native-appsflyer'; appsFlyer.getAppsFlyerUID((err, appsFlyerUID) => { if (err) { console.error('Error getting UID:', err); } else { console.log('AppsFlyer UID:', appsFlyerUID); // Use UID for server-side integration } }); ``` -------------------------------- ### Run Android and iOS Builds Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/demos/appsflyer-expo-app/README.md Commands to launch the application on Android and iOS platforms respectively. ```bash npm run android ``` ```bash npm run ios ``` -------------------------------- ### getAppsFlyerUID Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_API.md Retrieves AppsFlyer's unique device ID, which is created for every new install of an app. ```APIDOC ## getAppsFlyerUID ### Description Retrieves AppsFlyer's unique device ID, which is created for every new install of an app. ### Method JavaScript (Function Call) ### Endpoint N/A (Client-side SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | parameter | type | description | | ----------| ----------| ------------------ | | callback | function | returns `(error, appsFlyerUID)` | ### Request Example ```javascript appsFlyer.getAppsFlyerUID((err, appsFlyerUID) => { if (err) { console.error(err); } else { console.log('on getAppsFlyerUID: ' + appsFlyerUID); } }); ``` ### Response #### Success Response Callback function returning the AppsFlyer Unique Device ID. #### Response Example ```javascript // appsFlyerUID: "1646777777777-777777777" ``` #### Error Response Callback function returning an error object if the UID cannot be retrieved. #### Error Response Example ```javascript // error: { message: "Error retrieving UID" } ``` ``` -------------------------------- ### setAppInviteOneLinkID Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_UserInvite.md Configures the OneLink ID used for user invites. This must be called before the SDK start method. ```APIDOC ## setAppInviteOneLinkID(oneLinkID, callback) ### Description Sets the OneLink ID that should be used for the User-Invite-API. The generated invite link will use this ID as the base. ### Parameters - **oneLinkID** (string) - Required - The OneLink ID template. - **callback** (function) - Optional - Success callback function. ``` -------------------------------- ### Verify Android Response Code Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_Testing.md Example of a successful HTTP response log entry in the Android logcat. ```text I/AppsFlyer_6.4.3: response code: 200 // ~~> success! ``` -------------------------------- ### Create PurchaseConnector Instance Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_PurchaseConnector.md Initializes the PurchaseConnector instance with the provided configuration. Subsequent calls to create will return the existing instance. ```javascript //Create the object AppsFlyerPurchaseConnector.create(purchaseConnectorConfig); ``` -------------------------------- ### Retrieve AppsFlyer Unique ID Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_API.md Fetches the unique device ID generated by AppsFlyer upon app installation. ```javascript appsFlyer.getAppsFlyerUID((err, appsFlyerUID) => { if (err) { console.error(err); } else { console.log('on getAppsFlyerUID: ' + appsFlyerUID); } }); ``` -------------------------------- ### initSdk Source: https://github.com/appsflyersdk/appsflyer-react-native-plugin/blob/master/Docs/RN_API.md Initializes the AppsFlyer SDK with the provided configuration options, including devKey and appID. ```APIDOC ## initSdk ### Description Initializes the AppsFlyer SDK with the devKey and appID. The dev key is required for all apps and the appID is required only for iOS. ### Parameters #### Request Body - **options** (json) - Required - Configuration object containing devKey, appId, isDebug, onInstallConversionDataListener, onDeepLinkListener, timeToWaitForATTUserAuthorization, and manualStart. - **success** (function) - Required - Success callback function. - **error** (function) - Required - Error callback function. ### Request Example ```javascript appsFlyer.initSdk({ devKey: 'K2***********99', isDebug: false, appId: '41*****44', onInstallConversionDataListener: false, onDeepLinkListener: true, timeToWaitForATTUserAuthorization: 10, manualStart: true }, (res) => { console.log(res); }, (err) => { console.error(err); }); ``` ```