# Revenue

> Track in-app purchases and custom payments with the Grovs Android SDK.

Source: https://docs.grovs.io/docs/sdk/android/revenue

Log purchases to attribute revenue to links and campaigns, and see ARPU, LTV and product and platform breakdowns in the dashboard.

Revenue tracking is in **beta**. Currency conversion rates may show minor discrepancies.

Self-hosted: revenue tracking needs the Enterprise edition (`GROVS_EE=true`). A Community edition backend has no purchase endpoint.

## Setup

### 1. Enable revenue tracking in the dashboard

1. In the [Grovs dashboard](https://app.grovs.io), go to **Analytics → Revenue**.
2. Click **Enable Revenue Tracking**. Only instance admins can turn it on or off.

Revenue is collected only while this setting is on. See [Revenue](https://docs.grovs.io/docs/revenue) for the dashboard and [Goals](https://docs.grovs.io/docs/revenue/goals) for revenue goals.

### 2. Configure Google Play Real-Time Notifications

> **Warning:** **Required.** In-app purchase tracking doesn't work without this step. Grovs gets transaction data through Google Play Real-Time Developer Notifications.

#### Option A: Automatic setup (recommended)

A script from the Grovs dashboard configures Google Cloud for you: service account, API enablement and Pub/Sub. It's safe to re-run; existing resources are imported and updated, not duplicated.

1. In the Grovs dashboard, go to **Developers → Android Setup → Revenue**.
2. Click **Download Script** to get `grovs_android_gcloud_setup.sh`.
3. Open [Google Cloud Shell](https://shell.cloud.google.com).
4. Upload the script: **⋮** menu in the Cloud Shell toolbar → **Upload**, then select the file.
5. Run it:
   ```bash
   chmod +x grovs_android_gcloud_setup.sh
   ./grovs_android_gcloud_setup.sh
   ```
6. Pick one of your Google Cloud projects, or create one.
7. Note the service account email and the `play-api-key.json` file it outputs. You need both below.

#### Option B: Manual setup

1. In the [Google Cloud Console](https://console.cloud.google.com), create a **Pub/Sub topic** for your app.
2. Create a **service account** with access to the Android Publisher API.
3. Download the service account's **JSON key file**.

### 3. Complete the connection

These steps apply to both options.

#### Upload the key to Grovs

Under **Developers → Android Setup → Revenue**, upload the **JSON key file** (`play-api-key.json` from the script, or your manual key).

#### Invite the service account to Google Play Console

1. In the [Google Play Console](https://play.google.com/console), go to **Users and permissions**.
2. Click **Invite new users** and enter the service account email (shown in the Grovs dashboard or printed by the script).
3. Grant all three permissions:
   - **View app information and download bulk reports** (read-only)
   - **View financial data, orders, and cancellation survey responses**
   - **Manage orders and subscriptions**
4. Click **Invite user** and confirm.

Permissions can take up to 24 hours to propagate, so revenue may not appear right away.

#### Enable Real-Time Developer Notifications

1. In the [Google Play Console](https://play.google.com/console), open your app → **Monetization setup** → **Google Play Billing** → **Real-time developer notifications**.
2. Paste the **Notifications endpoint** URL from the Grovs dashboard.
3. Enable these notification types:
   - **Subscription notifications:** recurring purchases
   - **Voided purchase notifications:** refunds and chargebacks
   - **One-time product notifications:** needed if you sell one-time (non-subscription) products
4. Send a **test notification** to verify the connection.

Already handle Google Play notifications on your server? Forward the events to the Grovs endpoint URL instead.

## Logging purchases

Use `logInAppPurchase` for Google Play Billing and `logCustomPurchase` for any other payment flow.

### Google Play purchases

Pass the purchase's `originalJson`:

```kotlin
// After a successful purchase via Google Play Billing Library
billingClient.launchBillingFlow(activity, billingFlowParams)

// In your PurchasesUpdatedListener
override fun onPurchasesUpdated(billingResult: BillingResult, purchases: List<Purchase>?) {
    if (billingResult.responseCode == BillingClient.BillingResponseCode.OK && purchases != null) {
        for (purchase in purchases) {
            Grovs.logInAppPurchase(purchase.originalJson)
        }
    }
}
```

The SDK reads the product ID and purchase token from the JSON. Grovs verifies the purchase through the Google Play Developer API with your service account and fills in price and currency. Real-Time Developer Notifications then keep renewals, cancellations and refunds current. The backend de-duplicates on purchase token, so logging twice never double-counts.

Purchases are stored on the device and sent once the SDK authenticates, so offline purchases aren't lost. While install attribution resolves, purchases are held so they credit the link that drove the install. See [Install attribution timing](https://docs.grovs.io/docs/sdk/android/deep-linking#install-attribution-timing).

### Custom purchases

For purchases through your own server, Stripe or any non-Play Store system:

```kotlin
Grovs.logCustomPurchase(
    type = PaymentEventType.BUY,
    priceInCents = 999,       // $9.99
    currency = "USD",
    productId = "premium_monthly"
)
```

**Parameters:**

| Parameter      | Type               | Description                                                                                                       |
| -------------- | ------------------ | ----------------------------------------------------------------------------------------------------------------- |
| `type`         | `PaymentEventType` | `BUY`, `CANCEL`, or `REFUND`                                                                                      |
| `priceInCents` | `Int`              | Amount in cents (e.g. 999 for $9.99)                                                                              |
| `currency`     | `String`           | ISO 4217 currency code (e.g. `"USD"`, `"EUR"`)                                                                    |
| `productId`    | `String`           | Your product identifier                                                                                           |
| `startDate`    | `InstantCompat?`   | Transaction date. Defaults to now. Build one with `InstantCompat.ofEpochMilli(...)` or `InstantCompat.parse(...)` |

### Tracking cancellations and refunds

Log cancellations and refunds with `CANCEL` and `REFUND`:

```kotlin
// Log a cancellation
Grovs.logCustomPurchase(
    type = PaymentEventType.CANCEL,
    priceInCents = 999,
    currency = "USD",
    productId = "premium_monthly"
)

// Log a refund
Grovs.logCustomPurchase(
    type = PaymentEventType.REFUND,
    priceInCents = 999,
    currency = "USD",
    productId = "premium_monthly"
)
```

Google Play cancellations and refunds are detected automatically through Real-Time Notifications.

## Dashboard metrics

| Metric                              | Meaning                                    |
| ----------------------------------- | ------------------------------------------ |
| **Total Revenue**                   | Aggregate revenue with currency conversion |
| **ARPU**                            | Average revenue per user                   |
| **ARPPU**                           | Average revenue per paying user            |
| **LTV**                             | Lifetime value per product                 |
| **Units Sold**                      | Total purchases                            |
| **First-time vs. Repeat Purchases** | New vs. returning customers                |
| **Cancellations**                   | Cancelled transactions                     |

Filter every metric by date range, platform and product.
