---
title: "AppMetrica"
description: "Tích hợp AppMetrica với Adapty để phân tích gói đăng ký chuyên sâu."
---

[AppMetrica](https://appmetrica.yandex.com/about) là công cụ phân tích miễn phí giúp bạn theo dõi hành vi người dùng và phân tích hiệu suất ứng dụng di động theo thời gian thực. Bằng cách tích hợp AppMetrica với Adapty, bạn có thể hiểu sâu hơn về các chỉ số gói đăng ký và mức độ tương tác của người dùng.

## Cách thiết lập tích hợp AppMetrica \{#how-to-set-up-appmetrica-integration\}

Thiết lập tích hợp AppMetrica gồm hai bước chính:

1. Cấu hình tích hợp trong Adapty Dashboard
2. Thiết lập tích hợp trong code của ứng dụng

### Cấu hình trên dashboard \{#dashboard-configuration\}

Để thiết lập tích hợp AppMetrica:

1. Mở [danh sách ứng dụng AppMetrica](https://appmetrica.yandex.ru/application/list)
2. Chọn ứng dụng bạn muốn theo dõi
3. Vào **Settings > Main** và sao chép **Application ID** và **Post API key**

  <img src="/assets/shared/img/appmetrica.webp"
  style={{
    border: '1px solid #727272', /* border width and color */
    width: '700px', /* image width */
    display: 'block', /* for alignment */
    margin: '0 auto' /* center alignment */
  }}
/>

4. Vào [Integrations > AppMetrica](https://app.adapty.io/integrations/appmetrica) trong Adapty Dashboard
5. Dán thông tin xác thực AppMetrica của bạn vào.

  <img src="/assets/shared/img/appmetrica_creds.webp"
  style={{
    border: '1px solid #727272', /* border width and color */
    width: '700px', /* image width */
    display: 'block', /* for alignment */
    margin: '0 auto' /* center alignment */
  }}
/>

### Sự kiện và thẻ \{#events-and-tags\}

Adapty cho phép bạn gửi ba nhóm sự kiện tới AppMetrica. Bạn có thể bật các sự kiện cần theo dõi hiệu suất ứng dụng. Xem danh sách đầy đủ các sự kiện có sẵn trong [tài liệu về sự kiện](events).

:::note
AppMetrica đồng bộ sự kiện mỗi 4 giờ, vì vậy có thể có độ trễ trước khi sự kiện xuất hiện trên dashboard của bạn.
:::

  <img src="/assets/shared/img/6ed2d88-CleanShot_2023-08-18_at_14.59.042x.webp"
  style={{
    border: '1px solid #727272', /* border width and color */
    width: '700px', /* image width */
    display: 'block', /* for alignment */
    margin: '0 auto' /* center alignment */
  }}
/>

:::tip
Chúng tôi khuyến nghị sử dụng tên sự kiện mặc định của Adapty để đảm bảo tính nhất quán, nhưng bạn có thể tùy chỉnh chúng để phù hợp với thiết lập phân tích hiện có của mình.
:::

### Cài đặt doanh thu \{#revenue-settings\}

Mặc định, Adapty gửi dữ liệu doanh thu dưới dạng thuộc tính trong các sự kiện, hiển thị trong báo cáo Events của AppMetrica. Bạn có thể cấu hình cách tính toán và hiển thị dữ liệu doanh thu này:

- **Tính toán doanh thu**: Chọn cách tính giá trị doanh thu để phù hợp với nhu cầu báo cáo tài chính của bạn:
  - **Doanh thu gộp**: Hiển thị tổng doanh thu trước khi trừ bất kỳ khoản nào, hữu ích để theo dõi tổng số tiền khách hàng thanh toán
  - **Doanh thu sau khi trừ hoa hồng cửa hàng**: Hiển thị doanh thu sau khi đã trừ phí App Store/Play Store, giúp bạn theo dõi thu nhập thực tế
  - **Doanh thu sau khi trừ hoa hồng cửa hàng và thuế**: Hiển thị doanh thu ròng sau khi trừ cả phí cửa hàng và thuế áp dụng, cho bức tranh chính xác nhất về thu nhập của bạn

- **Báo cáo theo tiền tệ của người dùng**: Khi bật, doanh số được báo cáo theo tiền tệ địa phương của người dùng, giúp phân tích doanh thu theo khu vực dễ dàng hơn. Khi tắt, tất cả doanh số được quy đổi sang USD để báo cáo nhất quán trên các thị trường khác nhau.

- **Gửi sự kiện doanh thu**: Bật tùy chọn này để dữ liệu doanh thu xuất hiện không chỉ trong báo cáo Events mà còn trong báo cáo [In-app and ad revenue](https://appmetrica.yandex.com/docs/en/mobile-reports/revenue-report) của AppMetrica. Đảm bảo bạn không gửi doanh thu từ bất kỳ nguồn nào khác, vì điều này có thể dẫn đến trùng lặp dữ liệu.

- **Loại trừ sự kiện lịch sử**: Khi bật, Adapty sẽ không gửi các sự kiện xảy ra trước khi người dùng cài đặt ứng dụng có tích hợp Adapty SDK. Điều này giúp tránh trùng lặp dữ liệu nếu bạn đã gửi sự kiện tới analytics trước khi tích hợp Adapty.

  <img src="/assets/shared/img/appmetrica_revenue.webp"
  style={{
    border: '1px solid #727272', /* border width and color */
    width: '700px', /* image width */
    display: 'block', /* for alignment */
    margin: '0 auto' /* center alignment */
  }}
/>

### Cấu hình SDK \{#sdk-configuration\}

Để bật tích hợp AppMetrica trong ứng dụng, bạn cần thiết lập hai mã định danh:

1. `appmetrica_device_id`: Bắt buộc để tích hợp cơ bản
2. `appmetrica_profile_id`: Tùy chọn, nhưng được khuyến nghị nếu ứng dụng có chức năng đăng ký tài khoản người dùng

Sử dụng phương thức `setIntegrationIdentifier()` để thiết lập các giá trị này. Cách triển khai cho từng nền tảng:

---
no_index: true
---

import Callout from '../../../components/Callout.astro';

<Callout type="note">
Các SDK bên thứ ba tạo user ID theo cách bất đồng bộ. ID có thể chưa sẵn sàng khi `Adapty.activate()` chạy. Nếu **Customer User ID** của bạn đến từ một trong các SDK này, hãy gọi `Adapty.activate()` mà không truyền ID đó. Khi ID đã có, gọi `setIntegrationIdentifier()`, sau đó gọi `identify()` với CUID.
</Callout>

<Tabs groupId="current-os" queryString>
<TabItem value="Swift" label="iOS (Swift)" default>

**Thiết lập appmetrica_device_id**

```swift showLineNumbers
AppMetrica.requestStartupIdentifiers(on: nil) { ids, error in
  if let error {
    // handle AppMetrica error    
    return
  }

  guard let deviceIDHash = ids?[.deviceIDHashKey] as? String else {
    // handle AppMetrica error
    return
  }

  Task {
    do {
      try await Adapty.setIntegrationIdentifier(
        key: "appmetrica_device_id",
        value: deviceIDHash
      )
    } catch {
      // handle the error
    }
  }
}
```

**Thiết lập appmetrica_profile_id**

```swift showLineNumbers
do {
  try await Adapty.setIntegrationIdentifier(
    key: "appmetrica_profile_id",
    value: "YOUR_APPMETRICA_PROFILE_ID"
  )
} catch {
  // handle the error
}
```
</TabItem>
<TabItem value="kotlin" label="Android (Kotlin)" default>

**Thiết lập appmetrica_device_id**

```kotlin showLineNumbers 
val startupParamsCallback = object: StartupParamsCallback {
    override fun onReceive(result: StartupParamsCallback.Result?) {
        val deviceIdHash = result?.deviceIdHash ?: return

        Adapty.setIntegrationIdentifier("appmetrica_device_id", deviceIdHash) { error ->
            if (error != null) {
                // handle the error
            }
        }
    }

    override fun onRequestError(
        reason: StartupParamsCallback.Reason,
        result: StartupParamsCallback.Result?
    ) {
        //handle the error
    }
}

AppMetrica.requestStartupParams(context, startupParamsCallback, listOf(StartupParamsCallback.APPMETRICA_DEVICE_ID_HASH))
```

**Thiết lập appmetrica_profile_id**

```kotlin showLineNumbers
val startupParamsCallback = object: StartupParamsCallback {
    override fun onReceive(result: StartupParamsCallback.Result?) {
        val deviceIdHash = result?.deviceIdHash ?: return

        Adapty.setIntegrationIdentifier("appmetrica_device_id", deviceIdHash) { error ->
            if (error != null) {
                // handle the error
            }
        }
        
        Adapty.setIntegrationIdentifier("appmetrica_profile_id", "YOUR_ADAPTY_CUSTOMER_USER_ID") { error ->
            if (error != null) {
                // handle the error
            }
        }
    }

    override fun onRequestError(
        reason: StartupParamsCallback.Reason,
        result: StartupParamsCallback.Result?
    ) {
        //handle the error
    }
}

AppMetrica.requestStartupParams(context, startupParamsCallback, listOf(StartupParamsCallback.APPMETRICA_DEVICE_ID_HASH))
```
</TabItem>
<TabItem value="Flutter" label="Flutter (Dart)" default>

**Thiết lập appmetrica_device_id**

```javascript showLineNumbers

final startupParams = await AppMetrica.requestStartupParams([AppMetricaStartupParams.deviceIdHashKey]);
final deviceIdHash = startupParams.result?.deviceIdHash;

if (deviceIdHash != null) {
  try {
    await Adapty().setIntegrationIdentifier(
        key: "appmetrica_device_id", 
        value: deviceIdHash,
    );
  } on AdaptyError catch (adaptyError) {
    // handle the error
  } catch (e) {
    // handle the error
  }
}
```

**Thiết lập appmetrica_profile_id**

```javascript showLineNumbers

try {
    await Adapty().setIntegrationIdentifier(
        key: "appmetrica_profile_id", 
        value: "YOUR_APPMETRICA_PROFILE_ID",
    );
} on AdaptyError catch (adaptyError) {
    // handle the error
} catch (e) {
    // handle the error
}
```
</TabItem>
<TabItem value="Unity" label="Unity (C#)" default>

**Thiết lập appmetrica_device_id**

```csharp showLineNumbers
using AdaptySDK;
using Io.AppMetrica;

AppMetrica.RequestStartupParams(
    (result, errorReason) => {
        string deviceIdHash = result.DeviceIdHash;

        if (deviceIdHash != null) {
            Adapty.SetIntegrationIdentifier(
                "appmetrica_device_id",
                deviceIdHash,
                (error) => {
                    // handle the error
                });
          }
      },
      new List<string>() { StartupParamsKey.AppMetricaDeviceIDHash }
);
```

**Thiết lập appmetrica_profile_id**

```csharp showLineNumbers
Adapty.SetIntegrationIdentifier(
  "appmetrica_profile_id",
  "YOUR_APPMETRICA_PROFILE_ID",
  (error) => {
    // handle the error
});
```
</TabItem>
<TabItem value="RN" label="React Native (TS)" default>

**Thiết lập appmetrica_device_id**

```typescript showLineNumbers

// ...
const startupParamsCallback = async (
  params?: StartupParams,
  reason?: StartupParamsReason
) => {
  const deviceIdHash = params?.deviceIdHash
  if (deviceIdHash) {
    try {
      await adapty.setIntegrationIdentifier("appmetrica_device_id", deviceIdHash);
    } catch (error) {
      // handle `AdaptyError`
    }
  }
}

AppMetrica.requestStartupParams(startupParamsCallback, [DEVICE_ID_HASH_KEY])
```

**Thiết lập appmetrica_profile_id**

```typescript showLineNumbers

try {
  await adapty.setIntegrationIdentifier("appmetrica_profile_id", 'YOUR_ADAPTY_CUSTOMER_USER_ID');
} catch (error) {
  // handle `AdaptyError`
}
```
</TabItem>
</Tabs>

## Cấu trúc sự kiện AppMetrica \{#appmetrica-event-structure\}

Adapty gửi sự kiện tới AppMetrica qua các POST request với các tham số được truyền dưới dạng query parameter. Với mỗi sự kiện Adapty, AppMetrica nhận tới **hai request riêng biệt**:

1. **Sự kiện profile** (luôn được gửi): Chứa metadata của sự kiện
2. **Sự kiện doanh thu** (tùy chọn): Chứa dữ liệu doanh thu nếu tùy chọn "Gửi sự kiện doanh thu" được bật trong Adapty Dashboard

### Yêu cầu sự kiện profile \{#profile-event-request\}

Gửi tới: `https://api.appmetrica.yandex.ru/logs/v1/import/events`

Ví dụ URL với query parameter:

```
POST https://api.appmetrica.yandex.ru/logs/v1/import/events?post_api_key=your_key&application_id=your_app_id&event_name=subscription_renewed&event_timestamp=1709294400&event_json=%7B%22vendor_product_id%22%3A%22yearly.premium%22...%7D&os_name=ios&ios_ifa=00000000-0000-0000-0000-000000000000&ios_ifv=12345678-1234-1234-1234-123456789012&profile_id=user_12345&session_type=foreground
```

Query parameter:

| Tham số                | Kiểu   | Mô tả                                                                                                                                                          |
|:-----------------------|:-------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `post_api_key`         | String | Post API Key AppMetrica của bạn.                                                                                                                               |
| `application_id`       | String | Application ID AppMetrica của bạn.                                                                                                                             |
| `event_name`           | String | Tên sự kiện (được ánh xạ từ sự kiện Adapty).                                                                                                                   |
| `event_timestamp`      | Long   | Timestamp UNIX của sự kiện tính bằng giây. Bị giới hạn về 7 ngày gần nhất nếu cũ hơn.                                                                         |
| `event_json`           | String | Chuỗi JSON được URL-encoded chứa tất cả các [trường sự kiện](webhook-event-types-and-fields#for-most-event-types) có sẵn. Chỉ bao gồm các trường không null. |
| `os_name`              | String | "ios" hoặc "android".                                                                                                                                          |
| `profile_id`           | String | AppMetrica Profile ID (nếu đã thiết lập), nếu không thì Customer User ID (nếu có).                                                                            |
| `appmetrica_device_id` | String | AppMetrica Device ID Hash. Chỉ được gửi nếu `profile_id` không có sẵn.                                                                                        |
| `session_type`         | String | Luôn là "foreground".                                                                                                                                          |
| `ios_ifa`              | String | **Chỉ iOS**. ID for Advertisers.                                                                                                                               |
| `ios_ifv`              | String | **Chỉ iOS**. ID for Vendors.                                                                                                                                   |
| `google_aid`           | String | **Chỉ Android**. Google Advertising ID.                                                                                                                        |

### Yêu cầu sự kiện doanh thu (Tùy chọn) \{#revenue-event-request-optional\}

Gửi tới: `https://api.appmetrica.yandex.ru/logs/v1/import/revenue`

Request này chỉ được gửi khi tùy chọn "Gửi sự kiện doanh thu" được bật trong cài đặt tích hợp Adapty Dashboard của bạn.

Ví dụ URL với query parameter:

```
POST https://api.appmetrica.yandex.ru/logs/v1/import/revenue?post_api_key=your_key&application_id=your_app_id&revenue_event_type=subscription_renewed&price=9.99&currency=USD&product_id=yearly.premium&quantity=1&transaction_id=GPA.3383...&payload=%7B%22vendor_product_id%22%3A%22yearly.premium%22...%7D&os_name=ios&ios_ifa=00000000-0000-0000-0000-000000000000&profile_id=user_12345&session_type=foreground
```

Query parameter:

| Tham số              | Kiểu    | Mô tả                                                                                                                                                                                      |
|:---------------------|:--------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `post_api_key`       | String  | Post API Key AppMetrica của bạn.                                                                                                                                                           |
| `application_id`     | String  | Application ID AppMetrica của bạn.                                                                                                                                                         |
| `revenue_event_type` | String  | Loại sự kiện doanh thu (ví dụ: "subscription_renewed", "refund", "intro_started"). Xem [ánh xạ sự kiện AppMetrica](#revenue-event-type-mapping).                                           |
| `price`              | Float   | Giá trị doanh thu (dựa trên cài đặt tính toán doanh thu của bạn).                                                                                                                         |
| `currency`           | String  | Mã tiền tệ (ví dụ: "USD").                                                                                                                                                                 |
| `product_id`         | String  | Product ID từ cửa hàng.                                                                                                                                                                    |
| `quantity`           | Integer | Luôn là 1.                                                                                                                                                                                 |
| `transaction_id`     | String  | Store Transaction ID.                                                                                                                                                                      |
| `payload`            | String  | Chuỗi JSON được URL-encoded chứa thông tin chi tiết sự kiện. Tự động cắt bớt nếu vượt quá 30KB bằng cách xóa các trường tùy chọn theo thứ tự ưu tiên để giữ lại dữ liệu quan trọng nhất. |
| `os_name`            | String  | "ios" hoặc "android".                                                                                                                                                                      |
| `profile_id`         | String  | AppMetrica Profile ID (nếu đã thiết lập), nếu không thì Customer User ID (nếu có).                                                                                                        |
| `appmetrica_device_id` | String  | AppMetrica Device ID Hash. Chỉ được gửi nếu `profile_id` không có sẵn.                                                                                                                    |
| `session_type`       | String  | Luôn là "foreground".                                                                                                                                                                      |
| `ios_ifa`            | String  | **Chỉ iOS**. ID for Advertisers.                                                                                                                                                           |
| `ios_ifv`            | String  | **Chỉ iOS**. ID for Vendors.                                                                                                                                                               |
| `google_aid`         | String  | **Chỉ Android**. Google Advertising ID.                                                                                                                                                    |