Ссылка на репозиторий
GitHub

Интеграция SDK AppsFlyer в Unity Steam

AppsFlyer позволяет маркетологам игровых приложений принимать оптимальные решения, предоставляя высокоэффективные инструменты для кросс-платформенной атрибуции.

Для атрибуции игры в игру должен быть интегрирован SDK AppsFlyer, который записывает первое открытие, последовательные сессии и внутренние события приложения. Например, события покупки.
Мы рекомендуем использовать этот пример приложения в качестве справки по интеграции SDK AppsFlyer в свою игру для Unity Steam.

Note: The sample code that follows is supported in a both Windows & Mac environment.


Prerequisites

  • Unity Engine.
  • SDK Steamworks, интегрированный в ваш проект Unity.
  • Установленный клиент Steam с активным пользователем. Примечание: должен работать для тестирования.

AppsflyerSteamModule — интерфейс

AppsflyerSteamModule.cs в папке сцен содержит необходимый код и логику для подключения к серверам AppsFlyer и передачи отчетов по событиям.

AppsflyerSteamModule

This method receives your API key, Steam app ID, the parent MonoBehaviour and a sandbox mode flag (optional, false by default) and initializes the AppsFlyer Module.

Сигнатура метода

AppsflyerSteamModule(
   string DEV_KEY,
   string STEAM_APP_ID,
   MonoBehaviour mono,
   bool isSandbox = false,
   bool collectSteamUid = true
)

Аргументы

  • string DEV_KEY: получите у маркетолога или AppsFlyer HQ.
  • string STEAM_APP_ID: находится в SteamDB.
  • MonoBehaviour mono: the parent MonoBehaviour.
  • bool isSandbox: Whether to activate sandbox mode. False by default. This option is for debugging. With the sandbox mode, AppsFlyer dashboard does not show the data.
  • bool collectSteamUid: Whether to collect Steam UID or not. True by default.

Usage:

// for regular init
AppsflyerSteamModule afm = new AppsflyerSteamModule(DEV_KEY, STEAM_APP_ID, this);

// for init in sandbox mode (reports the events to the sandbox endpoint)
AppsflyerSteamModule afm = new AppsflyerSteamModule(DEV_KEY, STEAM_APP_ID, this, true);

// for init without reporting steam_uid
AppsflyerSteamModule afm = new AppsflyerSteamModule(DEV_KEY, STEAM_APP_ID, this, false, false);

Start

Данный метод передает запросы «first open/session» в AppsFlyer.

Сигнатура метода

void Start(bool skipFirst = false)

Аргументы

  • bool skipFirst: Determines whether or not to skip first open events and send session events. The value is false by default. If true , first open events are skipped and session events are sent. See example

Usage:

// without the flag
afm.Start();

// with the flag
bool skipFirst = [SOME_CONDITION];
afm.Start(skipFirst);

Stop

This method stops the SDK from functioning and communicating with AppsFlyer servers. It's used when implementing user opt-in/opt-out.

Сигнатура метода

void Stop()

Usage:

// Starting the SDK
afm.Start();
// ...
// Stopping the SDK, preventing further communication with AppsFlyer
afm.Stop();

LogEvent

Этот метод получает имя события и объект JSON и отправляет внутреннее событие приложения в AppsFlyer.

Сигнатура метода

void LogEvent(
      string event_name,
      Dictionary<string, object> event_parameters,
      Dictionary<string, object> event_custom_parameters = null
   )

Arguments:

  • string event_name: the name of the event.
  • Dictionary<string, object> event_parameters: dictionary object which contains the predefined event parameters.
  • Dictionary<string, object> event_custom_parameters: (non-mandatory): dictionary object which contains the any custom event parameters.

Usage:

// set event name
string event_name = "af_purchase";
// set event values
Dictionary<string, object> event_parameters = new Dictionary<string, object>();
event_parameters.Add("af_currency", "USD");
event_parameters.Add("af_revenue", 12.12);
// send logEvent request
afm.LogEvent(event_name, event_parameters);

// send logEvent request with custom params
Dictionary<string, object> event_custom_parameters = new Dictionary<string, object>();
event_custom_parameters.Add("goodsName", "新人邀约购物日");
afm.LogEvent(event_name, event_parameters, event_custom_parameters);

GetAppsFlyerUID

Получение от AppsFlyer уникального идентификатора устройства. SDK генерирует уникальный идентификатор устройства AppsFlyer при установке приложения. При запуске SDK этот идентификатор записывается как идентификатор первой установки приложения.

Сигнатура метода

string GetAppsFlyerUID()

Usage:

AppsflyerSteamModule afm = new AppsflyerSteamModule(DEV_KEY, STEAM_APP_ID, this);
afm.Start();
string af_uid = afm.GetAppsFlyerUID();

SetCustomerUserId

This method sets a customer ID that enables you to cross-reference your unique ID with the AppsFlyer unique ID and other device IDs. Note: You can only use this method before calling Start().
The customer ID is available in raw data reports and in the postbacks sent via API.

Сигнатура метода

void SetCustomerUserId(string cuid)

Arguments:

  • string cuid: Custom user id.

Usage:

AppsflyerSteamModule afm = new AppsflyerSteamModule(DEV_KEY, STEAM_APP_ID, this);
afm.SetCustomerUserId("15667737-366d-4994-ac8b-653fe6b2be4a");
afm.Start();

SetSharingFilterForPartners

This method lets you configure which partners should the SDK exclude from data-sharing. Partners that are excluded with this method will not receive data through postbacks, APIs, raw data reports, or any other means.

Сигнатура метода

public void SetSharingFilterForPartners(List<string> sharingFilter)

Arguments:

  • List<string> sharingFilter: a list of partners to filter. For example: new List<string>() {"partner1_int", "partner2_int"};

Usage:

AppsflyerSteamModule afm = new AppsflyerSteamModule(DEV_KEY, APP_ID, this);

// set the sharing filter
var sharingFilter = new List<string>() {"partner1_int", "partner2_int"};
afm.SetSharingFilterForPartners(sharingFilter);

// start the SDK (send firstopen/session request)
afm.Start();

IsInstallOlderThanDate

This method receives a date string and returns true if the game folder creation date is older than the date string. The date string format is: "2023-03-13T10:00:00+00:00"

Сигнатура метода

bool IsInstallOlderThanDate(string datestring)

Arguments:

  • string datestring: Date string in yyyy-mm-ddThh:mm:ss+hh:mm format.

Usage:

// the creation date in this example is "2023-03-23T08:30:00+00:00"
bool newerDate = afm.IsInstallOlderThanDate("2023-06-13T10:00:00+00:00");
bool olderDate = afm.IsInstallOlderThanDate("2023-02-11T10:00:00+00:00");

// will return true
Debug.Log("newerDate:" + (newerDate ? "true" : "false"));
// will return false
Debug.Log("olderDate:" + (olderDate ? "true" : "false"));

// example usage with skipFirst -
// skipping if the install date is NOT older than the given date
bool IsInstallOlderThanDate = afm.IsInstallOlderThanDate("2023-02-11T10:00:00+00:00");
afm.Start(!IsInstallOlderThanDate);

Запуск примера приложения

  1. Откройте хаб Unity и откройте проект.
  2. Добавьте Steamworks в свой проект Unity. Следуйте инструкциям к SDK Steamworks и добавьте его через менеджер пакетов.
  3. Используйте пример кода в SteamScript.cs и обновите его данными своих DEV_KEY and APP_ID.
  4. Добавьте SteamManager and SteamScript в пустой игровой объект (или воспользуйтесь объектом в папке сцен).
    Request-OK
  5. Запустите пример приложения посредством редактора Unity и убедитесь, что журнал отладки показывает следующее сообщение:
    Request-OK
  6. Через 24 часа дэшборд обновляется и отображает органические и неорганические установки и внутренние события приложения.

Внедрение AppsFlyer в вашу игру для Steam

  1. Добавьте Steamworks в свой проект Unity. Следуйте инструкциям к SDK Steamworks и добавьте его через менеджер пакетов.
  2. Add SteamManager.cs в игровой объект.
  3. Добавьте скрипт из Assets/Scenes/AppsflyerSteamModule.cs в ваше приложение.
  4. Используйте пример кода в Assets/Scenes/SteamScript.cs и обновите его данными своих DEV_KEY and APP_ID.
  5. Инициализируйте SDK.
AppsflyerSteamModule afm = new AppsflyerSteamModule(DEV_KEY, STEAM_APP_ID, this);
  1. Начните интеграцию AppsFlyer.
  2. Подайте отчет о внутренних событиях приложения.

Удаление сохранений Steam Cloud (сброс атрибуции)

  1. Отключите Steam cloud.
  2. Удалите локальные файлы.
  3. Delete the PlayerPrefs data the registry/preferences folder, or use PlayerPrefs.DeleteAll() when testing the attribution in the UnityEditor.
    AF guid & counter in the Windows Registry