# Connect Adapty

> Receive Adapty purchase, renewal, refund and subscription events through an authenticated webhook.

Source: https://metricraven.com/docs/adapty  
Markdown: https://metricraven.com/docs/adapty.md  
Section: Revenue

Adapty sends App Store, Google Play and web purchases, renewals, refunds and subscription changes to a webhook. Each request carries an Authorization header with a value MetricRaven generates. A custom user attribute links each purchase to the visit that brought the customer.

## Set up the webhook

1. **Open Settings → Integrations → Adapty**

   Choose **Set up Adapty**. To connect Adapty's sandbox instead, turn on [Test mode](https://metricraven.com/docs/adapty#test-mode) first.

2. **Copy the webhook URL and Authorization header value**

   The value is shown once. Save it before leaving the page.

3. **Open the webhook integration in Adapty**

   In the Adapty dashboard, open **Integrations → Webhook** and turn on the integration.

4. **Paste the URL and the header value**

   For live purchases, paste the URL as the **Production endpoint URL** and the value as the **Authorization header value for production endpoint**. On a Test mode connection, use the **Sandbox endpoint URL** and **Authorization header value for sandbox endpoint** instead. Adapty requires a Production endpoint URL even then: use your live site's URL and value, or the same test URL and value (a Test mode connection ignores Production events). Paste the value as is; MetricRaven also accepts it with a `Bearer` prefix.

5. **Turn on Send user attributes**

   Without it, Adapty leaves out `user_attributes`, and purchases can't carry the visitor ID (see [Link app purchases to visitors](https://metricraven.com/docs/adapty#link-users)).

6. **Keep the default event names**

   Leave every name under **Events names** as Adapty sets it, such as `subscription_started`. Renamed events are acknowledged but not recorded, and the Adapty panel in MetricRaven shows a warning naming the event. Leave **Exclude historical events** on (Adapty's default).

7. **Click Save**

   Adapty sends an empty request to check the URL, and MetricRaven answers it. The panel shows **Waiting for the first event** until Adapty sends a real event, such as a purchase or a sandbox purchase on a Test mode connection.

## Link app purchases to visitors

MetricRaven links each Adapty purchase to a visit using the first of these that is available:

1. The `metricraven_visitor_id` custom user attribute on the Adapty profile.
2. The `metricraven_user_id` attribute, else the Adapty customer user ID (set with Adapty's `identify`), matched to a visitor you linked with MetricRaven's [Identify API](https://metricraven.com/docs/identify-users).
3. An earlier purchase from the same Adapty profile, so renewals keep the original attribution.
4. The profile email, matched to an email from a server-side or signed [Identify](https://metricraven.com/docs/identify-users) call.

| Custom attribute | Value |
| --- | --- |
| metricraven_visitor_id | The MetricRaven visitor ID of the app install or of the web visit (24 or 32 hex characters). |
| metricraven_user_id | Optional. Your user ID, when the Adapty customer user ID is a different value. |
| metricraven_plan | Optional. A plan name for reports; otherwise the store product ID is used. |

Use the same canonical user ID in Adapty's `identify` and in MetricRaven's `identify`. Then set the visitor ID with `updateProfile`. The MetricRaven [React Native](https://metricraven.com/docs/react-native), [iOS](https://metricraven.com/docs/ios-sdk), [Android](https://metricraven.com/docs/android-sdk) and [Flutter](https://metricraven.com/docs/flutter) SDKs give the visitor ID of the app install. For a website-to-app journey, carry the web visitor ID (`window.analytics.getVisitorId()`) across with your own sign-in or deep-link flow.

```swift title="iOS (Swift)"
// After sign-in: the same user ID you send to MetricRaven's identify.
try await Adapty.identify(user.id)

// The visitor ID of this app install (MetricRaven Swift SDK), or one your web-to-app flow carried over.
if let visitorId = await MetricRaven.shared?.visitorId {
    let params = try AdaptyProfileParameters.Builder()
        .with(customAttribute: visitorId, forKey: "metricraven_visitor_id")
        .build()
    try await Adapty.updateProfile(params: params)
}
```

```kotlin title="Android (Kotlin)"
// After sign-in: the same user ID you send to MetricRaven's identify.
Adapty.identify(user.id) { error -> /* handle the error */ }

// The visitor ID of this app install (MetricRaven Android SDK), or one your web-to-app flow carried over.
MetricRaven.shared?.visitorId?.let { visitorId ->
    val params = AdaptyProfileParameters.Builder()
        .withCustomAttribute("metricraven_visitor_id", visitorId)
        .build()
    Adapty.updateProfile(params) { error -> /* handle the error */ }
}
```

```javascript title="React Native"
import { adapty } from "react-native-adapty";
import { analytics } from "./analytics"; // your createMetricRaven() client

// After sign-in: the same user ID you pass to analytics.identify().
await adapty.identify(user.id);

// The visitor ID of this app install, or one your web-to-app flow carried over.
const visitorId = analytics.getVisitorId();
if (visitorId) {
  await adapty.updateProfile({
    codableCustomAttributes: { metricraven_visitor_id: visitorId },
  });
}
```

```dart title="Flutter"
// package:metricraven: the same user ID in MetricRaven and Adapty.
MetricRaven.identify(user.id, {'email': user.email});
await Adapty().identify(user.id);

// This install's MetricRaven visitor ID (or one your web-to-app flow carried over).
final visitorId = MetricRaven.visitorId;
if (visitorId != null) {
  final builder = AdaptyProfileParametersBuilder()
    ..setCustomStringAttribute(visitorId, 'metricraven_visitor_id');
  await Adapty().updateProfile(builder.build());
}
```

From your server, set the attribute with Adapty's server-side API and your secret API key (Adapty: App settings → General → API keys):

```bash title="Server-side API"
curl --request PATCH 'https://api.adapty.io/api/v2/server-side-api/profile/' \
  --header "Authorization: Api-Key $ADAPTY_SECRET_KEY" \
  --header 'adapty-customer-user-id: YOUR_USER_ID' \
  --header 'Content-Type: application/json' \
  --data '{"custom_attributes":[{"key":"metricraven_visitor_id","value":"VISITOR_ID"}]}'
```

> **Note:** Adapty sends user attributes only when **Send user attributes** is on. Custom attribute values can be up to 50 characters, keys up to 30, and a profile can have up to 30 custom attributes.

> **Verify it works**
>
> After a delivery, the Adapty panel in **Settings → Integrations** shows **Connected**, the number of verified events and the last event type. A production purchase appears in **Revenue**, converted to your reporting currency; with a visitor ID it is credited to that visit's source in **Traffic**.

## Test mode

Every Adapty event carries `environment`: `Sandbox` or `Production`, and Adapty has separate sandbox and production endpoint URLs and Authorization header values. Turn on **Test mode** before **Set up Adapty**, then paste the URL and value into the **Sandbox endpoint URL** and **Authorization header value for sandbox endpoint** fields (Adapty also requires a Production endpoint URL: your live site's, or the same URL and value). A test mode connection records only Sandbox events; a live connection records only Production events. To test and run live at the same time, connect a test site to the sandbox endpoint and your live site to the production endpoint.

- Test payments and subscriptions are stored marked as test data and count in that site's revenue, MRR and subscriptions. The provider's panel shows a **Test mode** badge, and the Revenue tab a **Test mode** notice.
- Test payments don't count toward your plan's monthly events and send no payment alerts.
- The mode is chosen when you connect. Replacing a key or secret keeps it; to switch between test and live, disconnect and connect again. Test data already recorded stays.
- Connect test mode to a separate test website, so test payments never sit next to real revenue. See [Test mode](https://metricraven.com/docs/connect-payment-provider#test-mode).

No test build yet? Adapty's server-side API records a sandbox purchase that is sent to every integration: `POST /api/v2/server-side-api/purchase/set/transaction/` with `"environment": "Sandbox"` for a profile that has `metricraven_visitor_id`. A new transaction ID on the same original transaction is a renewal; the same transaction sent again with `refunded_at` is a refund. A free trial recorded this way sends no `trial_started` event, only its conversion.

## Events

Keep all of these selected in Adapty. Other events are acknowledged and ignored.

| Adapty event | What MetricRaven records |
| --- | --- |
| subscription_started, trial_converted | A payment, and the subscription as active. |
| subscription_renewed | A renewal payment, and the subscription as active. |
| non_subscription_purchase | A one-time payment. |
| subscription_refunded, non_subscription_purchase_refunded | A refund of that purchase. A refunded subscription ends, unless the refund comes from an upgrade. |
| trial_started | The subscription as trialing. |
| subscription_renewal_cancelled, trial_renewal_cancelled | A scheduled cancellation: the subscription stays live until it expires. |
| subscription_renewal_reactivated, trial_renewal_reactivated | The scheduled cancellation is removed. |
| subscription_expired, trial_expired | The subscription as ended. |
| subscription_paused | The subscription as paused (Google Play). |
| billing_issue_detected, entered_grace_period | The subscription as past due. |
| subscription_active, trial_active, subscription_deferred, access_level_updated | Nothing. They are acknowledged and ignored. |

## What MetricRaven records

- Revenue is the price the customer paid (`price_local` in `currency`), before the store's commission. Zero-amount events, such as some Google Play plan changes, are not revenue.
- Refunds reduce the original payment and never exceed it. An ordinary cancellation is not a refund: revenue already paid stays.
- MRR uses the subscription's renewal price without tax, divided by its period. See the [Revenue dashboard](https://metricraven.com/docs/revenue-dashboard#mrr-by-provider).
- Subscription events also record [automatic lifecycle goals](https://metricraven.com/docs/goals-funnels#payment-provider-goals) such as `trial_started`, `trial_converted`, `subscription_cancel_scheduled` and `subscription_ended`, attributed to the linked visitor.

## Paywall events

Adapty's webhooks carry no paywall views or closes. Send them from the app's paywall view events with the SDK: see [Paywall events](https://metricraven.com/docs/paywall-events#app-adapty).

## Troubleshooting

Adapty lists recent deliveries and their status under **Last sent events** on the webhook page, and in the **Event feed** (Last sent events stays empty until the Adapty SDK is installed in your app). Changes to the webhook settings, such as event names, can take a few minutes to reach deliveries.

| Symptom | Check |
| --- | --- |
| Sending failed with 401 | The Authorization header value doesn't match. Paste it again into the field for the same endpoint (production or sandbox), or generate a replacement in MetricRaven and update Adapty. |
| Sending failed with 404 | The webhook URL is wrong, or the Adapty connection was disconnected. Copy the URL from the MetricRaven panel again. |
| Still waiting for the first event | Saving only checks the URL. Make a purchase (or a sandbox purchase on a Test mode connection) to send an event. |
| Events received, but no revenue | Sandbox purchases reach only a Test mode connection, production purchases only a live one. Check which endpoint fields in Adapty hold the MetricRaven URL. |
| Revenue has no source | Turn on Send user attributes and set metricraven_visitor_id, or use the same user ID in Adapty's identify and MetricRaven's identify. |
| Warning about an event name | An event was renamed under Events names in Adapty. Restore the default name. |
| Visitor ID not saved in Adapty | Custom attribute values are limited to 50 characters, keys to 30 and attributes to 30 per profile. Check the error from updateProfile. |

## Details

- Each request must carry the Authorization header value MetricRaven generated, compared in constant time. Requests without it are rejected with `401` and never change revenue. There is no request signature.
- Redelivered events are recognized by their `profile_event_id` and ignored, so Adapty's retries never add a payment twice. MetricRaven answers `200` to every authenticated event, including ignored ones, so Adapty doesn't retry or pause the webhook.
- This connection receives new events. Adapty has no API to list past purchases, so history is not imported.
- Live subscriptions and MRR: State from the webhook's trial, purchase, renewal, cancellation, billing-issue, pause, refund and expiration events. MRR is the subscription's renewal price (original_price_local) without the store's estimated tax, divided by its period (from the purchase and expiration dates), so introductory and promotional prices don't lower it. Adapty has no subscription list to import: a subscription appears with its next event, and its amount with its next paid purchase or renewal. Amounts in other currencies convert at the latest ECB rates. See the [Revenue dashboard](https://metricraven.com/docs/revenue-dashboard#mrr-by-provider).
- If Stripe or Paddle is also connected to this site, Adapty events for purchases made through that store are skipped, so the same payment never counts twice. Don't also forward the same purchases through the Payments API.
- The Authorization header value is stored encrypted, bound to this site, and never shown in reports, share links or logs. Generating a replacement invalidates the old value; update Adapty immediately. Disconnecting deletes it; recorded revenue stays in your reports.
