# Analytics

Track Aeropay interactions, bank linking, errors, and transaction lifecycle events.

## Overview

The iOS SDK emits structured analytics events throughout the Aeropay flow. Use these events to measure conversion, identify drop-off points, and connect client activity with your monitoring and analytics systems.

Aeropay analytics can help you:

* Measure progression from the payment button to transaction submission.
* Track Aerosync bank-linking attempts and outcomes.
* Monitor consumer data, OTP, bank selection, and transaction errors.
* Correlate client activity with sessions and merchant transactions.
* Find points where shoppers abandon or repeatedly retry the flow.


## Consume analytics events

Set `analyticsEvent` when building `CheckoutConfig`:

```swift
let transactionData = TransactionData(
    amount: Decimal(25.00),
    currency: "USD",
    entryType: .ecom,
    intent: TransactionIntentData(aeropay: .authorisation),
    merchantTransactionId: sessionResult.merchantTransactionId,
    merchantTransactionDate: { Date() }
)

let checkoutConfig = CheckoutConfig(
    environment: .test,
    session: sessionResult.session,
    transactionData: transactionData,
    merchantShopperId: "shopper-123",
    ownerId: "MERCHANT_GROUP_1",
    onGetShopper: {
        await getCurrentShopper()
    },
    analyticsEvent: { event in
        sendAnalyticsEvent(
            eventName: event.eventName,
            payload: event
        )
    }
)
```

The SDK calls this handler when an event is created. Keep the handler non-blocking and catch errors in your analytics client so tracking doesn't interrupt checkout.

`onGetShopper` is `(() async -> TransactionShopper?)?`. Use a parameterless closure. You can `await` inside it when needed; don't write `{ async in ... }`.

Don't use analytics events to confirm payments or payouts. Verify the transaction on your backend using the authoritative PXP transaction result.

## Supported events

Aeropay emits payment-method-specific events and shared component events. All events inherit `timestamp` (`Date` on iOS) from `BaseAnalyticsEvent`. In the `analyticsEvent` callback, `event.timestamp` is a `Date`. If you `JSONEncoder().encode(event)` yourself, the default `dateEncodingStrategy` is `.deferredToDate` (seconds since the Swift reference date, 2001). Use `.secondsSince1970` only if you intentionally want Unix seconds. This isn't epoch milliseconds (`Long` on Android).

### Aeropay-specific events

The following events describe the embedded Aerosync bank-linking flow.

For these events, `componentId` is `aerosync-widget-host` (the embedded Aerosync widget host from `AeropayConstants.aerosyncWidgetComponentId`). It isn't the screen `componentType` value `aeropayAerosync`.

| Event name | Trigger | Fields returned  |
|  --- | --- | --- |
| `AerosyncLaunched` | The Aerosync bank-linking widget opens. | - `eventName`
- `sessionId`
- `timestamp`
- `componentId` (`aerosync-widget-host`)

 |
| `AerosyncCompleted` | Aerosync bank linking completes successfully. | - `eventName`
- `sessionId`
- `timestamp`
- `componentId` (`aerosync-widget-host`)

 |
| `AerosyncFailed` | Aerosync bank linking fails. | - `eventName`
- `sessionId`
- `timestamp`
- `componentId` (`aerosync-widget-host`)

 |


### Authorisation events

`PreAuthorisation` and `PostAuthorisation` describe the submission path and successful submission. Both extend `RetryablePaymentLifecycleAnalyticsEvent`, so they include `isRetry` (Bool, default `false`) in addition to the base `timestamp`.

| Event name | Trigger | Fields returned  |
|  --- | --- | --- |
| `PreAuthorisation` | Emitted when `onPreAuthorisation` is configured and the shopper confirms payment or payout (the submission path starts). The event fires before the callback runs and even if the callback returns `false`. No Unity submission runs when the callback returns `false`. Don't use this event as a "transaction submitted" funnel step. | - `eventName`
- `sessionId`
- `timestamp`
- `componentType` (`aeropay`)
- `transactionId`
- `isRetry`

 |
| `PostAuthorisation` | `onPostAuthorisation` is configured and invoked after successful submission. | - `eventName`
- `sessionId`
- `timestamp`
- `componentType` (`aeropay`)
- `transactionId`
- `isRetry`

 |


The `transactionId` is the `merchantTransactionId` supplied during SDK initialisation. These events fire only when the corresponding callbacks are configured. Use `PostAuthorisation` (and backend verification) to mark successful submission.

### Retry events

When Unity transaction submission retries, the SDK can emit `ApplePayRetryAttempt`. Treat the event name as a shared retry signal for this Aeropay path, not as an Apple Pay-only event.

The event includes:

| Field | Description |
|  --- | --- |
| `eventName` | Always `ApplePayRetryAttempt`. |
| `sessionId` | The current checkout session identifier. |
| `timestamp` | Event time as a `Date`. |
| `componentId` | The Aeropay button component identifier. |
| `merchantTransactionId` | The merchant transaction identifier from SDK initialisation. |
| `walletType` | Always `ApplePay` on this shared event type. |
| `additionalData` | Includes `retryCount` for the current retry. |


### Component interaction

`ComponentInteraction` records shopper activity such as button taps and popup close actions. For the payment button, `Click` is emitted only after `onCustomValidation` returns `true`. If custom validation returns `false`, `onClick` still runs, but the analytics Click event doesn't.

`interactionType` values are PascalCase strings (for example `Click`, `Close`, `Submit`, `Change`, `Focus`, `Blur`, and `Paste`). Aeropay also emits `ComponentInteraction` for screens such as `aeropayDataCollection`, `aeropayOtpVerification`, and `aeropayAerosync`, so don't map every interaction to a button-click funnel step.

| Field | Description |
|  --- | --- |
| `eventName` | Always `ComponentInteraction`. |
| `sessionId` | The current checkout session identifier. |
| `timestamp` | Event time as a `Date`. |
| `componentType` | The Aeropay area that produced the interaction. |
| `interactionType` | The interaction, such as `Click`, `Close`, or `Submit`. |
| `componentId` | The component identifier for the active control or screen. |


Aeropay uses these component types to identify parts of the flow:

| Component type | Area |
|  --- | --- |
| `aeropay-button` | Main Aeropay payment button. |
| `aeropayDataCollection` | Consumer data collection screen. |
| `aeropayOtpVerification` | OTP verification screen. |
| `aeropayAerosync` | Bank selection and Aerosync screen. |


### Component lifecycle

`ComponentLifecycleEvent` records popup screen mount and unmount activity. Use `eventType` and `componentId` to distinguish which control or screen changed (for example continue or verify OTP buttons).

| Field | Description |
|  --- | --- |
| `eventName` | Always `ComponentLifecycleEvent`. |
| `sessionId` | The current checkout session identifier. |
| `timestamp` | Event time as a `Date`. |
| `eventType` | Lifecycle stage. Encoded values include `Mount`, `Unmount`, `Loaded`, `Unloaded`, `onMounted`, and `Callback`. |
| `componentId` | Identifier of the component that mounted, unmounted, loaded, or unloaded. |


### Component errors

`ComponentError` records SDK and provider failures:

| Field | Description |
|  --- | --- |
| `eventName` | Always `ComponentError`. |
| `sessionId` | The current checkout session identifier. |
| `timestamp` | Event time as a `Date`. |
| `componentId` | Optional component identifier for the failing area. |
| `errorCode` | The SDK error code when available. |
| `errorMessage` | A description of the error. |


Use `errorCode`, `sessionId`, and `componentId` when investigating errors. Don't display `errorMessage` directly to shoppers without mapping it to an approved user-facing message.

Mapped failed Unity transaction responses call `onSubmitError` and also emit `ComponentError` with `SDK1326`. Network or transport failures still call `onSubmitError`, but can emit a different `ComponentError` code.

### Error messages shown

`ErrorMessageShown` records messages rendered inside the Aeropay flow. The event can represent field validation, user creation, OTP, bank account, account-linking, or transaction feedback shown in the popup. It isn't emitted merely because an error occurred.

The event includes `messageContent` (the user-visible text), plus `componentType`, `componentId`, `sessionId`, and `timestamp`. Treat `messageContent` as sensitive, the same way you treat `errorMessage` on `ComponentError`.

## Track a conversion funnel

Use `eventName`, `componentType`, and `interactionType` to derive a basic Aeropay funnel. Cast `ComponentInteraction` and filter by `componentType` and `interactionType` so you don't count Close, Submit, field Change, and other interactions as button clicks:

```swift
analyticsEvent: { event in
    switch event.eventName {
    case "ComponentInteraction":
        if let interaction = event as? ComponentInteractionAnalyticsEvent,
           interaction.componentType == "aeropay-button",
           interaction.interactionType == .click {
            // Track aeropay_button_clicked
        }
    case "AerosyncLaunched":
        // Track aeropay_bank_linking_started
        break
    case "AerosyncCompleted":
        // Track aeropay_bank_linking_completed
        break
    case "PostAuthorisation":
        // Track aeropay_transaction_submitted using transactionId
        break
    default:
        break
    }
}
```

Don't treat `PreAuthorisation` as a successful-submission funnel step. It can fire when merchant validation still cancels the submit path.

Analytics events don't include a dedicated user-verification-success event. If you need that funnel stage, record a custom event from `onUserVerificationSuccess`.

## Privacy guidance

When forwarding Aeropay analytics:

* Prefer `sessionId`, `merchantTransactionId`, `eventName`, `componentType`, and `errorCode`.
* Don't forward OTPs, full shopper records, bank account numbers, or provider payloads.
* Don't forward `messageContent` from `ErrorMessageShown` to third-party analytics. Treat it like `errorMessage` on `ComponentError`.
* Treat other message-content fields as potentially sensitive.
* Keep analytics out of the payment-confirmation path.
* On iOS, `event.timestamp` is a `Date`. When you encode the event with `JSONEncoder`, default encoding is `.deferredToDate`; use `.secondsSince1970` for Unix seconds if needed. This isn't epoch milliseconds.