# Events

Implement callbacks to customise your Aeropay payment flow for Web.

## Overview

Aeropay callbacks let your application respond to shopper interaction, user verification, popup close-button cancellation, transaction submission, and errors.

Use callbacks to:

* Save the verified Aeropay user ID for returning-shopper flows.
* Validate business rules before submitting a transaction.
* Verify successful transactions on your backend.
* Restore your checkout interface when the shopper selects the popup close button.
* Log errors and show appropriate recovery options.


Configure `onGetShopper` on `PxpCheckout.initialize()`. Configure the other callbacks on the `aeropay-button` component.

## Basic event handling

The following example implements the main Aeropay callbacks:

```typescript
const pxpSdk = PxpCheckout.initialize({
  // ...session and transaction configuration
  onGetShopper: async () => ({
    id: 'shopper-123',
    firstName: 'John',
    lastName: 'Doe',
    email: 'john.doe@example.com',
    phoneNumber: '+14155550123'
  })
});

const aeropayButton = pxpSdk.create('aeropay-button', {
  onCustomValidation: async () => {
    return await validateCheckoutBusinessRules();
  },
  onClick: () => {
    clearPaymentErrors();
  },
  onUserVerificationSuccess: (user) => {
    saveAeropayUserId(user.id);
  },
  onCancel: () => {
    resetCheckoutState();
  },
  onPreAuthorisation: async () => {
    return await validateOrderOnBackend();
  },
  onPostAuthorisation: (result) => {
    const submitResult = result as {
      merchantTransactionId: string;
      systemTransactionId: string;
    };
    verifyPaymentOnBackend({
      merchantTransactionId: submitResult.merchantTransactionId,
      systemTransactionId: submitResult.systemTransactionId
    });
  },
  onSubmitError: (error) => {
    console.error('Aeropay transaction submission failed', error);
    showAlternativePaymentMethods();
  },
  onError: (error) => {
    console.error('Aeropay flow failed', error);
    showPaymentError('Unable to complete the Aeropay flow.');
  }
});
```

Frontend callbacks aren't proof of payment. Verify every transaction on your backend before fulfilling an order or confirming a payout.

## Callback order

### New-shopper flow

For a successful new-shopper transaction, callbacks run in this order:

1. Optional `onCustomValidation` runs when the shopper clicks the button. Return `false` to prevent the popup from opening.
2. The SDK starts the flow and requests available consumer details from `onGetShopper`. It also calls `onClick` when the button is clicked.
3. The component displays the consumer data and OTP screens.
4. `onUserVerificationSuccess` runs after successful OTP verification.
5. `onPreAuthorisation` runs after the shopper selects a bank account and confirms the transaction.
6. `onGetShopper` runs again when the SDK builds the transaction request.
7. `onPostAuthorisation` runs after successful transaction submission.


If the shopper selects the popup close button, `onCancel` runs. Pressing Escape or programmatically unmounting the component hides the popup without calling `onCancel`. Flow errors call `onError`, while transaction submission failures call `onSubmitError`.

### Returning-shopper flow

When you provide `userId`, the SDK skips consumer data collection and OTP verification. A successful returning-shopper transaction follows this order:

1. Optional `onCustomValidation` runs when the shopper clicks the button. Return `false` to prevent the popup from opening.
2. `onClick` runs after the shopper clicks the button and user validation starts.
3. The SDK validates `userId` and opens bank selection.
4. `onPreAuthorisation` runs after the shopper selects a bank account and confirms the transaction.
5. `onGetShopper` supplies shopper data for the transaction request, if configured.
6. `onPostAuthorisation` runs after successful transaction submission.


The returning-shopper flow doesn't call `onUserVerificationSuccess`.

## SDK data callbacks

### `onGetShopper`

Configure `onGetShopper` on `PxpCheckout.initialize()`. For a new shopper, the SDK first calls it when the Aeropay button is clicked and uses `firstName`, `lastName`, `email`, and `phoneNumber` to prefill consumer data. The SDK calls it again before transaction submission to get the shopper object for the transaction request.

For a returning shopper with `userId`, the SDK doesn't need `onGetShopper` to open the popup. It still calls the callback when building the transaction request.

Use the callback to return the latest shopper data from your application:

```typescript
const pxpSdk = PxpCheckout.initialize({
  // ...session and transaction configuration
  onGetShopper: async () => {
    const shopper = await getCurrentShopper();

    return {
      id: shopper.id,
      firstName: shopper.firstName,
      lastName: shopper.lastName,
      email: shopper.email,
      phoneNumber: shopper.phoneNumber
    };
  }
});
```

The Aeropay flow uses these shopper properties:

| Property  | Description |
|  --- | --- |
| `id`string | Your shopper identifier. Include a stable value so you can associate the transaction with your customer record. |
| `firstName`string | The shopper's given name. Used to prefill consumer data and included in the transaction request. |
| `lastName`string | The shopper's family name. Used to prefill consumer data and included in the transaction request. |
| `email`string | The shopper's email address. Used to prefill consumer data and included in the transaction request. |
| `phoneNumber`string | The shopper's US phone number, including the `+1` country prefix. Used to prefill consumer data and included in the transaction request. |


The new-shopper flow validates any values returned for `firstName`, `lastName`, `email`, and `phoneNumber`. Invalid data calls `onError` and prevents the popup from opening.

## Aeropay component callbacks

Configure the following callbacks on `pxpSdk.create('aeropay-button', { ... })`.

### `onCustomValidation`

The `onCustomValidation` callback enables you to implement custom business rule validation when the shopper clicks the Aeropay button, before the popup opens. Return `true` to continue or `false` to stop the flow.

Use `onCustomValidation` to:

* Validate transaction amount limits or thresholds.
* Check customer eligibility for specific payment methods.
* Verify inventory availability before the shopper continues.
* Implement fraud prevention rules based on order data.
* Enforce payment policies based on customer account status.
* Validate promotional code or discount eligibility.


```typescript
onCustomValidation: async () => {
  if (!cartHasItems()) {
    showValidationError('Your cart is empty.');
    return false;
  }

  if (!termsAccepted()) {
    showValidationError('Please accept the terms and conditions.');
    return false;
  }

  return true;
}
```

Use `onCustomValidation` for checks that must pass before the Aeropay popup opens. Use `onPreAuthorisation` for a final check immediately before transaction submission. The SDK doesn't show an error UI when `onCustomValidation` returns `false`; display any shopper message in your application.

### `onClick`

The SDK calls `onClick` when the shopper clicks the Aeropay button. This callback can't prevent the popup from opening. Use `onCustomValidation` when you need to block the flow.

Use this callback to clear previous errors, update your checkout interface, or track the interaction:

```typescript
onClick: (event) => {
  clearPaymentErrors();
  setCheckoutActive(true);
  trackEvent('aeropay-button-clicked');
}
```

The callback receives the native button event:

| Parameter  | Description |
|  --- | --- |
| `event`MouseEvent | The native browser click event. |


### `onUserVerificationSuccess`

The SDK calls `onUserVerificationSuccess` after a new shopper enters the correct OTP. The callback isn't called for returning shoppers who enter the flow with `userId`.

Store the returned Aeropay user ID securely so you can use the returning-shopper flow:

```typescript
onUserVerificationSuccess: async (user) => {
  await saveAeropayUserId({
    shopperId: getCurrentShopperId(),
    aeropayUserId: user.id
  });
}
```

The callback receives an `AeropayUser` object:

| Property  | Description |
|  --- | --- |
| `id`string | The verified Aeropay user ID. |
| `firstName`string | The user's given name. |
| `lastName`string | The user's family name. |
| `type`string | The Aeropay user type. |
| `email`string | The user's email address. |
| `phoneNumber`string | The user's phone number. |
| `createdDate`string | The date and time when the Aeropay user was created. |


### `onCancel`

The SDK calls `onCancel` when the shopper selects the close button in the Aeropay popup.

Pressing Escape or programmatically unmounting the component hides the popup without calling `onCancel` in the current implementation.

Use this callback to restore your checkout interface without treating cancellation as an error:

```typescript
onCancel: () => {
  setCheckoutActive(false);
  setLoading(false);
  showAlternativePaymentMethods();
}
```

This callback receives no parameters and has no return value.

### `onPreAuthorisation`

The SDK calls `onPreAuthorisation` after the shopper selects a bank account and confirms the payment or payout. Use it to validate your order or payout before the SDK submits the transaction.

Return `true` to continue or `false` to stop submission:

```typescript
onPreAuthorisation: async () => {
  const validation = await validateOrderOnBackend();

  if (!validation.approved) {
    showPaymentError(validation.message);
    return false;
  }

  return true;
}
```

The callback controls transaction submission as follows:

| Return value | Behaviour |
|  --- | --- |
| `true` | The SDK builds and submits the transaction. |
| `false` | The SDK stops transaction submission and leaves the Aeropay flow open. |


Implement `onPreAuthorisation` and return `true` when the transaction can proceed. If the callback is omitted or doesn't return a truthy value, the SDK doesn't submit the transaction.

### `onPostAuthorisation`

The SDK calls `onPostAuthorisation` after PXP accepts the transaction submission. The successful runtime payload is a `MerchantSubmitResult` containing the transaction identifiers.

Send the identifiers to your backend and verify the final transaction state:

```typescript
onPostAuthorisation: (submitResult) => {
  const result = submitResult as {
    merchantTransactionId: string;
    systemTransactionId: string;
  };

  verifyPaymentOnBackend({
    merchantTransactionId: result.merchantTransactionId,
    systemTransactionId: result.systemTransactionId
  });
}
```

The successful payload contains these properties:

| Property  | Description |
|  --- | --- |
| `merchantTransactionId`string | Your unique transaction identifier. |
| `systemTransactionId`string | PXP's unique transaction identifier. |


The callback is declared with the shared `BaseSubmitResult` type. For a successful Aeropay submission, the SDK passes a `MerchantSubmitResult` with only `merchantTransactionId` and `systemTransactionId`. Don't rely on optional card or external-token fields for Aeropay.

### `onSubmitError`

The SDK calls `onSubmitError` when transaction submission fails. It isn't used for consumer data, user verification, bank account, or Aerosync failures. Those errors call `onError`.

Handle submission failures without exposing technical details to the shopper:

```typescript
onSubmitError: (submitError) => {
  console.error('Aeropay submission failed', submitError);

  const error = submitError as unknown;
  if (
    typeof error === 'object' &&
    error !== null &&
    'errorCode' in error
  ) {
    logPaymentFailure({
      errorCode: String(error.errorCode),
      correlationId: 'correlationId' in error
        ? String(error.correlationId)
        : undefined
    });
  }

  setLoading(false);
  showPaymentError('We could not complete the transaction. Try again or use another payment method.');
}
```

The callback's public parameter type is `BaseSubmitResult`. At runtime, a failed PXP response passes a `FailedSubmitResult`:

| Property  | Description |
|  --- | --- |
| `errorCode`string | The transaction error code. |
| `errorReason`string | A description of the failure. |
| `correlationId`string | The correlation identifier to include in logs and support requests. |
| `httpStatusCode`number | The HTTP status code returned by PXP. |
| `details`any[] | Additional error details. |


If submission processing throws a network error with `code: 'ERR_NETWORK'`, the SDK passes a `NetworkSdkException`. Other thrown values can pass through unchanged, including values that aren't `Error` objects. Treat the callback value defensively and check its shape before reading `FailedSubmitResult` or exception properties. The SDK doesn't export a runtime union covering these possibilities.

### `onError`

The SDK calls `onError` for errors outside transaction submission, including:

* Invalid shopper data.
* Aeropay user creation or verification failure.
* Invalid or inactive returning users.
* Bank account retrieval or linking failure.
* Aerosync failure.


Log recognised SDK errors and show a message that helps the shopper recover. The public callback type is `BaseSdkException`, but unexpected thrown values can pass through unchanged after the SDK only normalises errors with `code: 'ERR_NETWORK'`. Narrow the runtime value before reading exception properties:

```typescript
onError: (error) => {
  const runtimeError = error as unknown;

  if (
    typeof runtimeError === 'object' &&
    runtimeError !== null &&
    'ErrorCode' in runtimeError
  ) {
    logErrorToMonitoring({
      errorCode: String(runtimeError.ErrorCode),
      message: 'message' in runtimeError
        ? String(runtimeError.message)
        : 'Aeropay flow failed',
      details: 'details' in runtimeError
        ? runtimeError.details
        : undefined
    });
  } else {
    logErrorToMonitoring({
      message: runtimeError instanceof Error
        ? runtimeError.message
        : 'Unexpected Aeropay error'
    });
  }

  setLoading(false);
  showPaymentError('Unable to continue with Aeropay. Try again or use another payment method.');
}
```

Recognised SDK failures use `BaseSdkException`:

| Property  | Description |
|  --- | --- |
| `ErrorCode`string | The PXP Web SDK error code. |
| `message`string | A description of the error. |
| `details`any | Optional additional error information. |
| `cause`unknown | Optional original error that caused the SDK exception. |


## Event data structures

### `AeropayUser`

`onUserVerificationSuccess` receives the following object:

```typescript
interface AeropayUser {
  id: string;
  firstName?: string;
  lastName?: string;
  type?: string;
  email?: string;
  phoneNumber?: string;
  createdDate?: string;
}
```

### `MerchantSubmitResult`

Successful Aeropay transaction submission produces the following object:

```typescript
class MerchantSubmitResult extends BaseSubmitResult {
  merchantTransactionId: string;
  systemTransactionId: string;
}
```

Use only these identifiers for frontend handling and backend verification.

### `FailedSubmitResult`

A failed PXP transaction response produces the following object:

```typescript
class FailedSubmitResult extends BaseSubmitResult {
  errorCode: string;
  errorReason: string;
  correlationId: string;
  httpStatusCode: number;
  details: any[];
}
```

### `BaseSdkException`

Recognised `onError` failures use the following error type. `NetworkSdkException` extends this class, but other unexpected thrown values aren't guaranteed to use it:

```typescript
class BaseSdkException extends Error {
  ErrorCode: string;
  message: string;
  details?: any;
  cause?: unknown;
}
```

## Error-handling pattern

Keep error logging separate from the message shown to the shopper. The following pattern records diagnostic information while displaying a neutral recovery message:

```typescript
const aeropayButton = pxpSdk.create('aeropay-button', {
  onPreAuthorisation: () => true,

  onPostAuthorisation: async (result) => {
    try {
      const submitResult = result as {
        merchantTransactionId: string;
        systemTransactionId: string;
      };
      await verifyPaymentOnBackend({
        merchantTransactionId: submitResult.merchantTransactionId,
        systemTransactionId: submitResult.systemTransactionId
      });
      showPaymentSuccess();
    } catch (error) {
      console.error('Backend verification failed', error);
      showPaymentError('We could not confirm the transaction status. Contact support before trying again.');
    }
  },

  onSubmitError: (error) => {
    console.error('Aeropay transaction submission failed', error);
    reportErrorToMonitoring(error);
    showPaymentError('We could not complete the transaction. Try another payment method.');
  },

  onError: (error) => {
    console.error('Aeropay flow failed', error);
    const runtimeError = error as unknown;
    if (
      typeof runtimeError === 'object' &&
      runtimeError !== null &&
      'ErrorCode' in runtimeError
    ) {
      reportErrorToMonitoring({
        errorCode: String(runtimeError.ErrorCode),
        message: 'message' in runtimeError
          ? String(runtimeError.message)
          : 'Aeropay flow failed',
        details: 'details' in runtimeError
          ? runtimeError.details
          : undefined
      });
    } else {
      reportErrorToMonitoring(runtimeError);
    }
    showPaymentError('Unable to continue with Aeropay. Try again or use another payment method.');
  }
});
```