> Documentation index: https://firebase.google.com/docs/analytics/llms.txt

|---|---|
| **Select platform:** | [iOS+](https://firebase.google.com/docs/analytics/ios/measure-in-app-purchases.md.txt) [Android](https://firebase.google.com/docs/analytics/android/measure-in-app-purchases.md.txt) [Unity](https://firebase.google.com/docs/analytics/unity/measure-in-app-purchases.md.txt) |

<br />

In-app purchases (IAP) are digital content or features that you can sell in a
mobile app through the Apple App Store or Google Play so your app doesn't
have to process financial transactions. Examples of in-app purchases include
subscription-based content or special game pieces.

Analytics shows IAP events in the
[In-app purchases report](https://support.google.com/analytics/answer/12923440).

For Unity apps, the Analytics SDK integrates with the Apple App Store on iOS
and Google Play on Android.

In most cases, the Analytics SDK automatically collects IAP events without
requiring API calls in your app. The setup requirements and tracking behavior
depend on the target platform:

- **Android** : Google Play transactions are tracked automatically after linking Google Play. No code changes are required.
- **iOS (StoreKit 1)**: App Store transactions made using StoreKit 1 APIs are tracked automatically. No code changes are required.
- **iOS (StoreKit 2)**: App Store transactions made using StoreKit 2 APIs must be logged manually using the custom Unity API.

## Before you begin

- Set up your Firebase project and your app's codebase as described in
  [Get Started with Google Analytics](https://firebase.google.com/docs/analytics/unity/get-started.md.txt).

- [Link your Firebase project to a Google Analytics 4 property.](https://support.google.com/firebase/answer/9289399)

- Ensure that your app meets these platform-specific setup requirements:

  - **Android** : [Link your Firebase apps to Google Play](https://support.google.com/firebase/answer/6392038).

  - **iOS (StoreKit 1)**: No additional setup is required. StoreKit 1 tracking works automatically.

  - **iOS (StoreKit 2)**: Ensure your app is using the Firebase Unity SDK v13.12.0+ or higher.

- Make sure you're familiar with the in-app purchase APIs by reviewing the
  platform-specific documentation for [Google Play Billing](https://developer.android.com/google/play/billing),
  Apple [StoreKit](https://developer.apple.com/documentation/storekit),
  and [Unity In-App Purchasing](https://docs.unity.com/en-us/iap).

## Implementation

### Android

For Android apps, you can measure IAP events as soon as you
[link to Google Play](https://support.google.com/analytics/answer/11548051).
You don't need to write any custom code in your Unity project
to measure purchases.

### iOS

For iOS apps, the implementation strategy depends on whether your app uses
StoreKit 1 or StoreKit 2:

#### StoreKit 1

If your purchase flow uses StoreKit 1, the Analytics SDK automatically logs IAP
events. You don't need to add any custom code to track these purchases.

#### StoreKit 2

If your purchase flow uses StoreKit 2, you must manually log verified
transactions by passing the transaction identifier string
to `LogAppleTransactionAsync()`.

```c#
using Firebase.Analytics;

// Call this method once you have completed a StoreKit 2 transaction
// and have the transaction identifier.
public void LogPurchase(string transactionId) {
    FirebaseAnalytics.LogAppleTransactionAsync(transactionId).ContinueWith(task => {
        if (task.IsFaulted || task.IsCanceled) {
            Debug.LogError("Failed to log Apple purchase transaction: " + task.Exception);
        } else {
            Debug.Log("Successfully logged Apple purchase transaction");
        }
    });
}
```

##### Retrieve the transaction ID using Unity IAP

If your project uses [Unity's standard In-App Purchasing package](https://docs.unity.com/en-us/iap)
(`UnityEngine.Purchasing`), the method for retrieving the transaction ID depends
on the Unity IAP API version you are using.

###### Confirmation callback using Unity IAP v5.2+

In Unity IAP v5.2 and higher, you can access Apple-specific transaction
information directly from the `Order` object in the confirmation callback. You
can pass either the `OriginalTransactionID` or the current transaction ID to
`LogAppleTransactionAsync()`:

```c#
using UnityEngine.Purchasing;
using Firebase.Analytics;
using Firebase.Extensions;

// Example using Unity IAP v5.2+ Order confirmation
void OnPurchaseConfirmed(Order order) {
    #if UNITY_IOS
    if (order is ConfirmedOrder confirmedOrder) {

        var appleInfo = confirmedOrder.Info.Apple;
        if (appleInfo != null) {

            string transactionId = appleInfo.OriginalTransactionID;

            if (!string.IsNullOrEmpty(transactionId)) {
                // Log the StoreKit 2 transaction with Firebase Analytics
                FirebaseAnalytics.LogAppleTransactionAsync(transactionId).ContinueWithOnMainThread(task => {
                    if (task.IsFaulted || task.IsCanceled) {
                        Debug.LogError($"Failed to log Apple purchase transaction: {task.Exception}");
                    } else {
                        Debug.Log("Successfully logged Apple purchase transaction");
                    }
                });
            } else {
                Debug.LogWarning("Apple OriginalTransactionID is null or empty. Skipping Firebase logging.");
            }
        }
    } else if (order is FailedOrder failedOrder) {
        Debug.Log($"Purchase confirmation bypassed due to failure: {failedOrder.FailureReason}");
    }
    #endif
}
```

###### Legacy `ProcessPurchase` callback

If you are using the legacy `ProcessPurchase` callback, you can extract the
transaction identifier from the purchased product:

```c#
using UnityEngine.Purchasing;
using Firebase.Analytics;
using Firebase.Extensions;

public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args) {
    // Extract the transaction ID from the purchased product
    string transactionId = args.purchasedProduct.transactionID;

    #if UNITY_IOS
    // Log the StoreKit 2 transaction with Firebase Analytics
    FirebaseAnalytics.LogAppleTransactionAsync(transactionId).ContinueWithOnMainThread(task => {
        if (task.IsFaulted || task.IsCanceled) {
            Debug.LogError($"Failed to log Apple purchase transaction: {task.Exception}");
        } else {
            Debug.Log("Successfully logged Apple purchase transaction");
        }
    });
    #endif

    return PurchaseProcessingResult.Complete;
}
```

## Log in-app purchase events manually

If you need to track in-app purchases made outside of the Play Store or App
Store (such as through alternative stores or custom
payment processes, or other marketplaces), you can manually log these
transactions using the `IN_APP_PURCHASE` event.

> [!WARNING]
> **Warning:** To avoid double counting revenue, don't manually log purchases that are already tracked automatically by the Analytics SDK (such as Google Play or standard App Store transactions). Tracked StoreKit 2 transactions logged using `LogAppleTransactionAsync()` are also handled and shouldn't be logged manually again.

```c#
using Firebase.Analytics;

public void LogCustomInAppPurchase(string productName, double value, string currencyCode, int quantity = 1)
{
    FirebaseAnalytics.LogEvent(
        FirebaseAnalytics.EventInAppPurchase,
        new Parameter(FirebaseAnalytics.ParameterProductName, productName),
        new Parameter(FirebaseAnalytics.ParameterValue, value),
        new Parameter(FirebaseAnalytics.ParameterCurrency, currencyCode),
        new Parameter(FirebaseAnalytics.ParameterQuantity, quantity)
    );
}
```