Skip to content

Latest commit

 

History

History
914 lines (729 loc) · 29.8 KB

API.md

File metadata and controls

914 lines (729 loc) · 29.8 KB

API

Types

Methods


parameter type description
appsFlyerOptions Map SDK configuration

options

                                                                                                    |
Setting Type Description
devKey String Your application's devKey provided by AppsFlyer (required)
appId String Your application's App ID (required for iOS only) that you configured in your AppsFlyer dashboard
showDebug bool Debug mode - set to true for testing only, do not release to production with this parameter set to true!
timeToWaitForATTUserAuthorization double Delays the SDK start for x seconds until the user either accepts the consent dialog, declines it, or the timer runs out.
appInviteOneLink String The OneLink template ID that is used to generate a User Invite, this is not a required field in the AppsFlyerOptions, you may choose to set it later via the appropriate API.
disableAdvertisingIdentifier bool Opt-out of the collection of Advertising Identifiers, which include OAID, AAID, GAID and IDFA.
disableCollectASA bool Opt-out of the Apple Search Ads attributions.
manualStart bool Prevents from the SDK from sending the launch request after using appsFlyer.initSdk(...). When using this property, the apps needs to manually trigger the appsFlyer.startSdk() API to report the app launch.

Example:

import 'package:appsflyer_sdk/appsflyer_sdk.dart';
//..

Map appsFlyerOptions = { "afDevKey": afDevKey,
                "afAppId": appId,
                "showDebug": true};

AppsflyerSdk appsflyerSdk = AppsflyerSdk(appsFlyerOptions);

Or you can use AppsFlyerOptions class instead

AppsflyerSdk(Map options)
parameter type description
appsFlyerOptions AppsFlyerOptions SDK configuration

Example:

import 'package:appsflyer_sdk/appsflyer_sdk.dart';
//..

final AppsFlyerOptions options = AppsFlyerOptions(afDevKey: "af dev key",
                                                  showDebug: true,
                                                  appId: "123456789");

Once AppsflyerSdk object is created, you can call initSdk method.


parameter type description
monetizationNetwork String
mediationNetwork String value must be taken from AFMediationNetwork
currencyIso4217Code String
revenue double
additionalParameters Map<String, dynamic>?

an enumeration that includes the supported mediation networks by AppsFlyer.

networks
ironSource
applovinMax
googleAdMob
fyber
appodeal
admost
topon
tradplus
yandex
chartboost
unity
toponPte
customMediation
directMonetizationNetwork

initialize the SDK, using the options initialized from the constructor| Return response object with the field status

Example:

import 'package:appsflyer_sdk/appsflyer_sdk.dart';
//..

AppsflyerSdk _appsflyerSdk = AppsflyerSdk({...});

await _appsflyerSdk.initSdk(   
  registerConversionDataCallback: true, 
  registerOnAppOpenAttributionCallback: true, 
  registerOnDeepLinkingCallback: true)

In version 6.13.0 of the appslfyer-flutter-plugin SDK we added the option of splitting between the initialization stage and start stage. All you need to do is add the property manualStart: true to the init object, and later call appsFlyer.startSdk() whenever you decide. If this property is set to false or doesn’t exist, the sdk will start after calling appsFlyer.initSdk(...).

_appsflyerSdk.startSDK();

  • Trigger callback when onAppOpenAttribution is activated on the native side

Example:

_appsflyerSdk.onAppOpenAttribution((res) {
      print("res: " + res.toString());
    });
  • Trigger callback when onInstallConversionData is activated on the native side

Example:

    _appsflyerSdk.onInstallConversionData((res) {
      print("res: " + res.toString());
    });
  • Trigger callback when onDeepLinking is activated on the native side

Example:

    _appsflyerSdk.onDeepLinking((res) {
      print("res: " + res.toString());
    });

  • These in-app events help you to understand how loyal users discover your app, and attribute them to specific campaigns/media-sources. Please take the time define the event/s you want to measure to allow you to send ROI (Return on Investment) and LTV (Lifetime Value).
  • The logEvent method allows you to send in-app events to AppsFlyer analytics. This method allows you to add events dynamically by adding them directly to the application code.
parameter type description
eventName String custom event name, is presented in your dashboard. See the Event list HERE
eventValues Map event details

Example:

Future<bool?> logEvent(String eventName, Map? eventValues) async {
    bool? result;
    try {
        result = await appsflyerSdk.logEvent(eventName, eventValues);
    } on Exception catch (e) {}
    print("Result logEvent: $result");
}

Other functionalities:

anonymizeUser(shouldAnonymize)

It is possible to anonymize specific user identifiers within AppsFlyer analytics.
This complies with both the latest privacy requirements (GDPR, COPPA) and Facebook's data and privacy policies. To anonymize an app user.

parameter type description
shouldAnonymize boolean True if want Anonymize user Data (default value is false).

Example:

appsFlyerSdk.anonymizeUser(true);

setUserEmails(List<String> emails, [EmailCryptType cryptType])

Set the user emails with the given encryption (EmailCryptTypeNone, EmailCryptTypeSHA256). the default encryption is EmailCryptTypeNone.

Example:

appsFlyerSdk.setUserEmails(
       ["a@a.com", "b@b.com"], EmailCryptType.EmailCryptTypeSHA256);

void setMinTimeBetweenSessions(int seconds) You can set the minimum time between session (the default is 5 seconds)

appsFlyerSdk.setMinTimeBetweenSessions(3)

void stop(bool isStopped) You can stop sending events to Appsflyer by using this method.

Example:

widget.appsFlyerSdk.stop(true);

void setCurrencyCode(String currencyCode)

Example:

appsFlyerSdk.setCurrencyCode("currencyCode");

void setIsUpdate(bool isUpdate)

Example:

appsFlyerSdk.setIsUpdate(true);

void enableUninstallTracking(String senderId)

Example:

appsFlyerSdk.enableUninstallTracking("senderId");

void setImeiData(String imei)

Example:

appsFlyerSdk.setImeiData("imei");

void setAndroidIdData(String androidIdData)

Example:

appsFlyerSdk.setAndroidIdData("androidId");

void enableLocationCollection(bool flag)

Removed as of v6.8.0

Example:

appsFlyerSdk.enableLocationCollection(true);

enableTCFDataCollection(bool shouldCollect)

The enableTCFDataCollection method is employed to control the automatic collection of the Transparency and Consent Framework (TCF) data. By setting this flag to true, the system is instructed to automatically collect TCF data. Conversely, setting it to false prevents such data collection.

Example:

appsFlyerSdk.enableTCFDataCollection(true);

setConsentData(Map<String, Object> consentData)

The AppsflyerConsent object helps manage user consent settings. By using the setConsentData we able to manually collect the TCF data. You can create an instance for users subject to GDPR or otherwise:

  1. Users subjected to GDPR:
var forGdpr = AppsFlyerConsent.forGDPRUser(
    hasConsentForDataUsage: true, 
    hasConsentForAdsPersonalization: true
);
_appsflyerSdk.setConsentData(forGdpr);
  1. Users not subject to GDPR:
var nonGdpr = AppsFlyerConsent.nonGDPRUser();
_appsflyerSdk.setConsentData(nonGdpr);

The _appsflyerSdk handles consent data with setConsentData method, where you can pass the desired AppsflyerConsent instance.


To reflect TCF data in the conversion (first launch) payload, it's crucial to configure enableTCFDataCollection or setConsentData between the SDK initialization and start phase. Follow the example provided:

// Set AppsFlyerOption - make sure to set manualStart to true
final AppsFlyerOptions options = AppsFlyerOptions(
        afDevKey: dotenv.env["DEV_KEY"]!,
        appId: dotenv.env["APP_ID"]!,
        showDebug: true,
        timeToWaitForATTUserAuthorization: 15,
        manualStart: true);
_appsflyerSdk = AppsflyerSdk(options);

// Init the AppsFlyer SDK
_appsflyerSdk.initSdk(
    registerConversionDataCallback: true,
    registerOnAppOpenAttributionCallback: true,
    registerOnDeepLinkingCallback: true);

// Set configurations to the SDK
// Enable TCF Data Collection
_appsflyerSdk.enableTCFDataCollection(true);

// Set Consent Data
// If user is subject to GDPR
// var forGdpr = AppsFlyerConsent.forGDPRUser(hasConsentForDataUsage: true, hasConsentForAdsPersonalization: true);
// _appsflyerSdk.setConsentData(forGdpr);

// If user is not subject to GDPR
var nonGdpr = AppsFlyerConsent.nonGDPRUser();
_appsflyerSdk.setConsentData(nonGdpr);

// Here we start a session
_appsflyerSdk.startSDK(); 

Following this sequence ensures that the consent configurations take effect before the AppsFlyer SDK starts, providing accurate consent data in the first launch payload. Note: You need to use either enableTCFDataCollection or setConsentData if you use both of them our backend will prioritize the provided consent data from setConsentData.


void setCustomerUserId(String userId)

What is customer user id?

Example:

appsFlyerSdk.setCustomerUserId("id");

void setCustomerIdAndLogSession(String userId) Android only!

What is customer user id?

Example:

appsFlyerSdk.setCustomerIdAndLogSession("id");

void waitForCustomerUserId(bool wait) Android only

You can set this function to true if you don't want to log events without setting customer id first.

Example:

appsFlyerSdk.waitForCustomerUserId(true);
appsFlyerSdk.setCustomerIdAndLogSession("id");

void setAdditionalData(Map additionalData)

Example:

var data = {"key1": "value1", "key2": "value2"};
appsFlyerSdk.setAdditionalData(data);

void setCollectAndroidId(bool isCollect)

Example:

appsFlyerSdk.setCollectAndroidId(true);

void setCollectIMEI(bool isCollect)
NOTE: Make sure to add <uses-permission android:name="android.permission.READ_PHONE_STATE" /> in the AndroidManifest and request these permissions in the runtime in order for the SDK to be able to collect IMEI

Example:

appsFlyerSdk.setCollectIMEI(false);

void setHost(String hostPrefix, String hostName) You can change the default host (appsflyer) by using this function

Example:

appsFlyerSdk.setHost("pref", "my-host");

Future<String> getHostName()

Example:

appsFlyerSdk.getHostName().then((name) {
         print("Host name: ${name}");
       });

Future<String> getHostPrefix()

Example:

appsFlyerSdk.getHostPrefix().then((name) {
         print("Host prefix: ${name}");
       });

void updateServerUninstallToken(String token)

Example:

appsFlyerSdk.updateServerUninstallToken("token");

Validate Purchase

Android:

Future<dynamic> validateAndLogInAppAndroidPurchase( String publicKey, String signature, String purchaseData, String price, String currency, Map<String, String>? additionalParameters)

Example:

appsFlyerSdk.validateAndLogInAppAndroidPurchase(
           "publicKey",
           "signature",
           "purchaseData",
           "price",
           "currency",
           {"fs": "fs"});

iOS:

Future<dynamic> validateAndLogInAppIosPurchase( String productIdentifier, String price, String currency, String transactionId, Map<String, String> additionalParameters)

Example:

appsFlyerSdk.validateAndLogInAppIosPurchase(
           "productIdentifier",
           "price",
           "currency",
           "transactionId",
           {"fs": "fs"});

Purchase validation sandbox mode for iOS:

void useReceiptValidationSandbox(bool isSandboxEnabled)

Example:

appsFlyerSdk.useReceiptValidationSandbox(true);

Purchase validation callback

void onPurchaseValidation(Function callback)

Example:

appsflyerSdk.onPurchaseValidation((res){
  print("res: " + res.toString());
});

void setPushNotification(bool isEnabled)[DEPRECATED]

Example:

appsFlyerSdk.setPushNotification(true);

void sendPushNotificationData(Map? userInfo)

Push-notification campaigns are used to create fast re-engagements with existing users.

Learn more

For Android: AppsFlyer SDK uses the activity in order to process the push payload. Make sure you call this api when the app's activity is available (NOT dead state).

Example:

final Map userInfo = {
            "af":{
                "c": "test_campaign",
                "is_retargeting": true,
                "pid": "push_provider_int",
            },
            "aps":{
                "alert": "Get 5000 Coins",
                "badge": "37",
                "sound": "default"
            }
        };

appsFlyerSdk.sendPushNotificationData(userInfo);

void addPushNotificationDeepLinkPath(List<String> deeplinkPath)

Example:

appsFlyerSdk.addPushNotificationDeepLinkPath(["deeply", "nested", "deep_link"]);

This call matches the following payload structure:

{
  "deeply": {
      "nested": {
          "deep_link": "https://yourdeeplink2.onelink.me"
      }
  }
}

User Invite

  1. First define the Onelink ID (find it in the AppsFlyer dashboard in the onelink section:

Future<void> setAppInviteOneLinkID(String oneLinkID, Function callback)

  1. Set the AppsFlyerInviteLinkParams class to set the query params in the user invite link:
class AppsFlyerInviteLinkParams {
  final String channel;
  final String campaign;
  final String referrerName;
  final String referreImageUrl;
  final String customerID;
  final String baseDeepLink;
  final String brandDomain;
}
  1. Call the generateInviteLink API to generate the user invite link. Use the success and error callbacks for handling.

void generateInviteLink(AppsFlyerInviteLinkParams parameters, Function success, Function error)

Example:

appsFlyerSdk.setAppInviteOneLinkID('OnelinkID', 
(res){ 
  print("setAppInviteOneLinkID callback: $res"); 
});

AppsFlyerInviteLinkParams inviteLinkParams = new AppsFlyerInviteLinkParams(
      channel: "",
      referrerName: "",
      baseDeepLink: "",
      brandDomain: "",
      customerID: "",
      referreImageUrl: "",
      campaign: "",
      customParams: {"key":"value"}
);

appsFlyerSdk.generateInviteLink(inviteLinkParams, 
  (result){ 
    print(result); 
  }, 
  (error){ 
    print(error);
  }
);

void enableFacebookDeferredApplinks(bool isEnabled)

Please make sure the relevant Facebook dependecies are added to the project!

For more information check the following article: https://support.appsflyer.com/hc/en-us/articles/207033826-Facebook-Ads-setup-guide#advanced-using-facebook-ads-appsflyer-sdks-for-deferred-deep-linking

Example:

appsFlyerSdk.enableFacebookDeferredApplinks(true);

void disableSKAdNetwork(bool isEnabled)

Use this API in order to disable the SK Ad network (request will be sent but the rules won't be returned).

Example:

appsFlyerSdk.disableSKAdNetwork(true);

Future<String?> getAppsFlyerUID() async

Use this API in order to get the AppsFlyer ID.

Example:

appsFlyerSdk.getAppsFlyerUID().then((AppsFlyerId) {
  print("AppsFlyer ID: ${AppsFlyerId}");
});

void setCurrentDeviceLanguage(string language)

Use this API in order to set the language

Example:

appsFlyerSdk.setCurrentDeviceLanguage("en");

void setSharingFilterForPartners(List<String> partners)

setSharingFilter & setSharingFilterForAllPartners APIs were deprecated!

Use setSharingFilterForPartners instead.

Used by advertisers to exclude specified networks/integrated partners from getting data. Learn more here

Example:

appsFlyerSdk.setSharingFilterForPartners([]);                                        // Reset list (default)
appsFlyerSdk.setSharingFilterForPartners(null);                                      // Reset list (default)
appsFlyerSdk.setSharingFilterForPartners(['facebook_int']);                          // Single partner
appsFlyerSdk.setSharingFilterForPartners(['facebook_int', 'googleadwords_int']);     // Multiple partners
appsFlyerSdk.setSharingFilterForPartners(['all']);                                   // All partners
appsFlyerSdk.setSharingFilterForPartners(['googleadwords_int', 'all']);              // All partners

void setOneLinkCustomDomain(List<String> brandDomains)

Use this API in order to set branded domains.

Find more information in the following article on branded domains.

Example:

  appsFlyerSdk.setOneLinkCustomDomain(["promotion.greatapp.com","click.greatapp.com","deals.greatapp.com"]);

void setDisableAdvertisingIdentifiers(bool isSetDisableAdvertisingIdentifiersEnable)

Manually enable or disable Advertiser ID in Android & IDFA in iOS

Example:

  appsFlyerSdk.setDisableAdvertisingIdentifiers(true);

void setPartnerData(String partnerId, Map<String, Object> partnerData)

Allows sending custom data for partner integration purposes.

Example:

  Map<String, Object> partnerData = {"puid": "1234", "puid": '5678'};
  appsflyerSdk.setPartnerData("partnerId", partnerData);

void setResolveDeepLinkURLs(List<String> urls)

Advertisers can wrap an AppsFlyer OneLink within another Universal Link. This Universal Link will invoke the app but any deep linking data will not propagate to AppsFlyer.

setResolveDeepLinkURLs enables you to configure the SDK to resolve the wrapped OneLink URLs, so that deep linking can occur correctly.

Example:

  appsflyerSdk.setResolveDeepLinkURLs(["clickdomain.com", "myclickdomain.com", "anotherclickdomain.com"]);

void setOutOfStore(String sourceName)

Android Only!

Specify the alternative app store that the app is downloaded from.

Example:

  if(Platform.isAndroid){
    appsflyerSdk.setOutOfStore("facebook_int");
  }

Future<String?> getOutOfStore()

Android Only!

Get the third-party app store referrer value.

Example:

  if(Platform.isAndroid){
    Future<String> store = appsflyerSdk.getOutOfStore();
    store.then((store) {
      print(store);
    });
  }

void setDisableNetworkData(bool disable)

Android Only!

Use to opt-out of collecting the network operator name (carrier) and sim operator name from the device.

Example:

  if(Platform.isAndroid){
    appsflyerSdk.setDisableNetworkData(true);
  }

void performOnDeepLinking()

Android Only!

Enables manual triggering of deep link resolution. This method allows apps that are delaying the call to appsflyerSdk.startSDK() to resolve deep links before the SDK starts.
Note:
This API will trigger the appsflyerSdk.onDeepLink callback. In the following example, we check if res.deepLinkStatus is equal to “FOUND” inside appsflyerSdk.onDeepLink callback to extract the deeplink parameters.

  void afStart() async {
    // SDK Options
    final AppsFlyerOptions options = AppsFlyerOptions(
        afDevKey: dotenv.env["DEV_KEY"]!,
        appId: dotenv.env["APP_ID"]!,
        showDebug: true,
        timeToWaitForATTUserAuthorization: 15,
        manualStart: true);
    _appsflyerSdk = AppsflyerSdk(options);
    
    // Init of AppsFlyer SDK
    await _appsflyerSdk.initSdk(
        registerConversionDataCallback: true,
        registerOnAppOpenAttributionCallback: true,
        registerOnDeepLinkingCallback: true);

    // Conversion data callback
    _appsflyerSdk.onInstallConversionData((res) {
      print("onInstallConversionData res: " + res.toString());
      setState(() {
        _gcd = res;
      });
    });

    // App open attribution callback
    _appsflyerSdk.onAppOpenAttribution((res) {
      print("onAppOpenAttribution res: " + res.toString());
      setState(() {
        _deepLinkData = res;
      });
    });

    // Deep linking callback
    _appsflyerSdk.onDeepLinking((DeepLinkResult dp) {
      switch (dp.status) {
        case Status.FOUND:
          print(dp.deepLink?.toString());
          print("deep link value: ${dp.deepLink?.deepLinkValue}");
          break;
        case Status.NOT_FOUND:
          print("deep link not found");
          break;
        case Status.ERROR:
          print("deep link error: ${dp.error}");
          break;
        case Status.PARSE_ERROR:
          print("deep link status parsing error");
          break;
      }
      print("onDeepLinking res: " + dp.toString());
      setState(() {
        _deepLinkData = dp.toJson();
      });
    });

    if(Platform.isAndroid){
      _appsflyerSdk.performOnDeepLinking();
    }
    _appsflyerSdk.startSDK();
  }

The logAdRevenue API is designed to simplify the process of logging ad revenue events to AppsFlyer from your Flutter application. This API tracks revenue generated from advertisements, enriching your monetization analytics. Below you will find instructions on how to use this API correctly, along with detailed descriptions and examples for various input scenarios.

Usage:

To use the logAdRevenue method, you must:

  1. Prepare an instance of AdRevenueData with the required information about the ad revenue event.
  2. Call logAdRevenue with the AdRevenueData instance.

AdRevenueData Class AdRevenueData is a data class representing all the relevant information about an ad revenue event:

  • monetizationNetwork: The source network from which the revenue was generated (e.g., AdMob, Unity Ads).
  • mediationNetwork: The mediation platform managing the ad (use AFMediationNetwork enum for supported networks).
  • currencyIso4217Code: The ISO 4217 currency code representing the currency of the revenue amount (e.g., "USD", "EUR").
  • revenue: The amount of revenue generated from the ad.
  • additionalParameters: Additional parameters related to the ad revenue event (optional).

AFMediationNetwork Enum AFMediationNetwork is an enumeration that includes the supported mediation networks by AppsFlyer. It's important to use this enum to ensure you provide a valid network identifier to the logAdRevenue API.

Example:

// Instantiate AdRevenueData with the ad revenue details.
AdRevenueData adRevenueData = AdRevenueData(
  monetizationNetwork: "GoogleAdMob", // Replace with your actual monetization network.
  mediationNetwork: AFMediationNetwork.applovinMax.value, // Use the value from the enum.
  currencyIso4217Code: "USD", 
  revenue: 1.23,
  additionalParameters: {
    // Optional additional parameters can be added here. This is an example, can be discard if not needed.
    'adUnitId': 'ca-app-pub-XXXX/YYYY', 
    'ad_network_click_id': '12345'
  }
);

// Log the ad revenue event.
logAdRevenue(adRevenueData);

Additional Points

  • Mediation network input must be from the provided AFMediationNetwork enum to ensure proper processing by AppsFlyer. For instance, use AFMediationNetwork.googleAdMob.value to denote Google AdMob as the Mediation Network.
  • The additionalParameters map is optional. Use it to pass any extra information you have regarding the ad revenue event; this information could be useful for more refined analytics.
  • Make sure the currencyIso4217Code adheres to the appropriate standard. Misconfigured currency code may result in incorrect revenue tracking.