> For the complete documentation index, see [llms.txt](https://docs.amply.tools/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.amply.tools/recipes/purchases-from-campaigns-in-analytics.md).

# Purchases from campaigns in your analytics

Tag every purchase with the Amply campaign that led to it, so your product analytics (Amplitude, Mixpanel or any other) can split revenue by campaign.

**Use this when** you run paywall, offer or upgrade campaigns and want to see, in the analytics tool your team already reads, which of them bring purchases. **Don't use this when** you only need to know how often a campaign was shown: that is already in the campaign's stats in Amply.

## Goal

A campaign shows an offer. Some users buy straight from it. Others close it and buy ten minutes later from the settings screen. Your analytics sees two purchases and no campaign. This recipe puts the campaign's id and name on the purchase event and sends that event to both Amply and your analytics, so you can segment purchases by campaign and build a funnel from "campaign shown" to "purchased".

There are two ways a purchase meets a campaign:

* **It started from the campaign.** The campaign opened your paywall through a deep link, so the app knows exactly which campaign it was.
* **It happened somewhere else, soon after.** The app asks the SDK for the last campaign touch within a window you choose.

A touch is a campaign being shown to the user, or engaged with (a mini-app finished, or a gated action completed).

Use the first when you have it, and the second for everything else. The last-touch lookup needs SDK 0.15.0+.

## Setup

### In the dashboard

* Nothing new is required. Any deep link campaign already hands your deep link handler the campaign's id and name.
* Optionally put the campaign into the link itself, so the screen it opens can read it from the URL: `yourapp://paywall?amply_campaign_id={@campaign.id}&amply_campaign_name={@campaign.name}`. The SDK fills the values in before your app gets the link (SDK 0.13.0+, see [Managing deeplinks](https://docs.amply.tools/user-guide/managing-deeplinks.md)).

### In the app (engineering hand-off)

1. **Carry the campaign from the link to the paywall.** The deep link handler's `info` carries `campaignId` and `campaignName`. Pass them along with the route, or read them from the link if you put them there.
2. **At purchase time, pick the campaign.** The link's campaign if there was one; otherwise `getLastCampaignTouch(withinMs)`, which returns the campaign that most recently reached this user within the window, or nothing. See the [iOS](https://docs.amply.tools/reference/sdk-ios.md#last-campaign-touch), [Android](https://docs.amply.tools/reference/sdk-android.md#last-campaign-touch) and [React Native](https://docs.amply.tools/reference/sdk-react-native.md#last-campaign-touch) references.
3. **Send one purchase event to both.** Put the campaign on it as `amply_campaign_id` and `amply_campaign_name`, and send the same event to Amply with `track` and to your analytics.

{% tabs %}
{% tab title="iOS (Swift)" %}

```swift
import AmplySDK

let attributionWindowMs: Int64 = 24 * 60 * 60 * 1000   // your choice, up to 30 days

struct CampaignCredit {
    let id: String
    let name: String
    let touch: String   // "link", "shown" or "engaged"

    var properties: [String: Any] {
        ["amply_campaign_id": id, "amply_campaign_name": name, "amply_touch": touch]
    }
}

// 1. A purchase that starts from a campaign: the deep link handler knows the campaign.
final class AppDeepLinkHandler: NSObject, DeepLinkListener {
    func onDeepLink(url: String, info: [String: Any]) -> Bool {
        guard url.hasPrefix("yourapp://paywall") else { return false }
        let credit = (info["campaignId"] as? String).map {
            CampaignCredit(id: $0, name: info["campaignName"] as? String ?? "", touch: "link")
        }
        Router.shared.showPaywall(credit: credit)
        return true
    }
}

// 2. Anywhere else: the campaign that last reached this user, if any.
func campaignCredit(fromLink: CampaignCredit?) async -> CampaignCredit? {
    if let fromLink { return fromLink }
    guard let touch = try? await amply.getLastCampaignTouch(withinMs: attributionWindowMs) else {
        return nil
    }
    return CampaignCredit(id: touch.campaignId, name: touch.campaignName,
                          touch: touch.kind == .engaged ? "engaged" : "shown")
}

// 3. One purchase event, to Amply and to your analytics.
func recordPurchase(sku: String, price: Double, fromLink: CampaignCredit?) async {
    let credit = await campaignCredit(fromLink: fromLink)
    let purchase: [String: Any] = ["sku": sku, "price": price]
    let properties = purchase.merging(credit?.properties ?? [:]) { _, campaign in campaign }
    amply.track(event: "PurchaseCompleted", properties: properties)
    analytics.track("PurchaseCompleted", properties)   // Amplitude, Mixpanel, …
}
```

{% endtab %}

{% tab title="Android (Kotlin)" %}

```kotlin
import tools.amply.sdk.actions.DeepLinkListener

const val ATTRIBUTION_WINDOW_MS = 24 * 60 * 60 * 1000L   // your choice, up to 30 days

data class CampaignCredit(val id: String, val name: String, val touch: String) {
    fun toProperties(): Map<String, Any> =
        mapOf("amply_campaign_id" to id, "amply_campaign_name" to name, "amply_touch" to touch)
}

// 1. A purchase that starts from a campaign: the deep link handler knows the campaign.
class AppDeepLinkHandler(private val router: Router) : DeepLinkListener {
    override fun onDeepLink(url: String, info: Map<String, Any>): Boolean {
        if (!url.startsWith("yourapp://paywall")) return false
        val credit = (info["campaignId"] as? String)?.let { id ->
            CampaignCredit(id, info["campaignName"] as? String ?: "", touch = "link")
        }
        router.showPaywall(credit)
        return true
    }
}

// 2. Anywhere else: the campaign that last reached this user, if any.
suspend fun campaignCredit(fromLink: CampaignCredit?): CampaignCredit? {
    if (fromLink != null) return fromLink
    val touch = amply.getLastCampaignTouch(ATTRIBUTION_WINDOW_MS) ?: return null
    return CampaignCredit(touch.campaignId, touch.campaignName, touch.kind.name.lowercase())
}

// 3. One purchase event, to Amply and to your analytics.
suspend fun recordPurchase(sku: String, price: Double, fromLink: CampaignCredit?) {
    val credit = campaignCredit(fromLink)
    val properties = mapOf("sku" to sku, "price" to price) + credit?.toProperties().orEmpty()
    amply.track("PurchaseCompleted", properties)
    analytics.track("PurchaseCompleted", properties)   // Amplitude, Mixpanel, …
}
```

{% endtab %}

{% tab title="React Native (TS)" %}

```ts
import Amply from '@amplytools/react-native-amply-sdk';

const ATTRIBUTION_WINDOW_MS = 24 * 60 * 60 * 1000; // your choice, up to 30 days

type CampaignCredit = { id: string; name: string; touch: 'link' | 'shown' | 'engaged' };

// 1. A purchase that starts from a campaign: the deep link listener knows the campaign.
//    (Keep the unsubscribe function addDeepLinkListener resolves to, as usual.)
Amply.addDeepLinkListener(event => {
  if (!event.url.startsWith('yourapp://paywall')) return;
  const id = event.info.campaignId;
  const credit: CampaignCredit | undefined =
    typeof id === 'string'
      ? { id, name: String(event.info.campaignName ?? ''), touch: 'link' }
      : undefined;
  navigation.navigate('Paywall', { credit });
});

// 2. Anywhere else: the campaign that last reached this user, if any.
async function campaignCredit(fromLink?: CampaignCredit): Promise<CampaignCredit | undefined> {
  if (fromLink) return fromLink;
  const touch = await Amply.getLastCampaignTouch(ATTRIBUTION_WINDOW_MS);
  return touch ? { id: touch.campaignId, name: touch.campaignName, touch: touch.kind } : undefined;
}

// 3. One purchase event, to Amply and to your analytics.
export async function recordPurchase(sku: string, price: number, fromLink?: CampaignCredit) {
  const credit = await campaignCredit(fromLink);
  const properties = {
    sku,
    price,
    ...(credit && {
      amply_campaign_id: credit.id,
      amply_campaign_name: credit.name,
      amply_touch: credit.touch,
    }),
  };
  await Amply.track({ name: 'PurchaseCompleted', properties });
  analytics.track('PurchaseCompleted', properties); // Amplitude, Mixpanel, …
}
```

{% endtab %}
{% endtabs %}

`amply_touch` is optional. It tells purchases that **started from** a campaign (`link`) apart from purchases made after a campaign was **shown** or **engaged** with. See the [reference](https://docs.amply.tools/reference/sdk-ios.md#last-campaign-touch) for exactly what counts as engaged.

### Forward Amply's campaign events for funnels

For a funnel "campaign shown → purchased", your analytics also needs the shows. Forward `CampaignShown` from the system-events listener, and `CampaignResolved` if you want the outcome of mini-apps and gated actions. Both carry the campaign's id and name (SDK 0.15.0+). Use the same property names as on the purchase, so one filter selects the campaign at every step. See [Events](https://docs.amply.tools/reference/events.md) for every property.

{% hint style="warning" %}
On iOS and Android the SDK keeps **one** system-events listener: setting a new one replaces the one before. If your app already sets one, add these lines to that listener instead of registering a second.
{% endhint %}

{% tabs %}
{% tab title="iOS (Swift)" %}

```swift
final class AmplyToAnalytics: NSObject, SystemEventsListener {
    func onEvent(event: EventInterface) {
        guard event.name == "CampaignShown" || event.name == "CampaignResolved" else { return }
        analytics.track("Amply\(event.name)", [
            "amply_campaign_id": event.properties["campaignId"] ?? "",
            "amply_campaign_name": event.properties["campaignName"] ?? "",
            "amply_result": event.properties["result"] ?? "shown",
        ])
    }
}

// Keep both alive for as long as the app runs.
let amplyToAnalytics = AmplyToAnalytics()
let systemEventsToken = amply.setSystemEventsListener(listener: amplyToAnalytics)
```

{% endtab %}

{% tab title="Android (Kotlin)" %}

```kotlin
class AmplyToAnalytics : SystemEventsListener {
    override fun onEvent(event: EventInterface) {
        if (event.name != "CampaignShown" && event.name != "CampaignResolved") return
        analytics.track("Amply${event.name}", mapOf(
            "amply_campaign_id" to (event.properties["campaignId"] ?: ""),
            "amply_campaign_name" to (event.properties["campaignName"] ?: ""),
            "amply_result" to (event.properties["result"] ?: "shown"),
        ))
    }
}

// Keep the token: it is what detaches the listener later.
val systemEventsToken = amply.setSystemEventsListener(AmplyToAnalytics())
```

{% endtab %}

{% tab title="React Native (TS)" %}

```ts
const unsubscribe = await Amply.addSystemEventListener(event => {
  if (event.name !== 'CampaignShown' && event.name !== 'CampaignResolved') return;
  analytics.track(`Amply${event.name}`, {
    amply_campaign_id: event.properties.campaignId ?? '',
    amply_campaign_name: event.properties.campaignName ?? '',
    amply_result: event.properties.result ?? 'shown',
  });
});
```

{% endtab %}
{% endtabs %}

## How it runs

1. A user on the free plan triggers your `spring-offer` campaign. The SDK shows it and your listener forwards `AmplyCampaignShown` with `amply_campaign_name = "Spring offer"`.
2. **Path A:** the user taps through. The deep link opens your paywall with the campaign attached; they buy. `PurchaseCompleted` goes out with `amply_touch = "link"`.
3. **Path B:** the user closes the offer, browses, and buys from the settings screen twenty minutes later. At purchase time the app asks for the last campaign touch within 24 hours, gets `spring-offer`, and sends `PurchaseCompleted` with `amply_touch = "shown"`.
4. **Path C:** the user buys three days later. The touch is outside the 24-hour window, so the purchase goes out without a campaign. Choose a wider window if you want to credit it.
5. In your analytics, group `PurchaseCompleted` by `amply_campaign_name`, or build the funnel `AmplyCampaignShown` → `PurchaseCompleted` filtered on the same `amply_campaign_id`.

## Why the numbers can differ

Don't expect Amply and your analytics to match to the unit:

* **Your window.** The window you pass to `getLastCampaignTouch` decides which purchases get a campaign at all. A purchase outside it carries no campaign anywhere.
* **Your analytics' funnel window.** Your analytics has its own conversion window and its own rule for who counts as the same user. A one-hour funnel counts fewer conversions than the 24-hour window that tagged the purchases.
* **User switch, offline and consent.** Touches are forgotten when the app switches to a different user, so a purchase right after signing in to another account carries no campaign. Events sent offline arrive later, and either tool may drop or sample events the other keeps.

Compare campaigns with each other inside one tool, and pick one tool as the number you report.

## Metrics to watch

* Purchases and revenue per `amply_campaign_name`, against purchases with no campaign.
* The share of `link` versus `shown` / `engaged` purchases per campaign. An offer that mostly converts later may need a clearer call to action, not a different audience.
* Funnel conversion from `AmplyCampaignShown` to `PurchaseCompleted`, per campaign.

## Related

* [Handling deeplinks](https://docs.amply.tools/developer-guide/handling-deeplinks.md) — the `info` your handler receives, and values filled into links
* [Handling callbacks](https://docs.amply.tools/developer-guide/handling-callbacks.md) — subscribing to system events
* [Events](https://docs.amply.tools/reference/events.md) — `CampaignShown` and `CampaignResolved` properties
* [Tracking events](https://docs.amply.tools/developer-guide/tracking-events.md) — sending your own events to Amply
* [Second-chance paywall](https://docs.amply.tools/recipes/second-chance-paywall.md) — a campaign whose purchases you'll want to credit
* [Targeting and audiences](https://docs.amply.tools/concepts/targeting-and-audiences.md) — targeting on past events and their properties
