# Implementation

Complete guide to integrating the Aeropay component into your application.

## Overview

The Aeropay component lets shoppers make payments or receive payouts through a linked US bank account. The integration follows a three-stage lifecycle:

1. **Initialise:** Configure the SDK with an Aeropay-enabled session and transaction data.
2. **Create and mount:** Create the Aeropay button and render it on your checkout page.
3. **Handle the flow:** Respond to user verification, transaction results, close-button cancellation, and errors.


The SDK handles consumer data collection, OTP verification, bank selection, Aerosync bank linking, and pay-by-bank transaction submission.

Backend verification is mandatory. Always verify transactions on your backend before fulfilling orders or confirming payouts. Frontend callbacks can be manipulated by malicious users.

## Before you start

Complete [Aeropay onboarding](/guides/checkout/components/web/aeropay/onboarding) in the Unity Portal before integrating the component. You'll need:

* Aeropay enabled at merchant group and site level.
* Your Aeropay merchant ID, API key, API secret, and configuration ID added to the Aeropay service.
* PXP API credentials for creating sessions on your backend.
* Node.js 22.x or higher.


Aeropay transactions must also meet these requirements:

| Setting | Required value |
|  --- | --- |
| Currency | `USD` |
| Entry type | `Ecom` |
| Intent | `Authorisation`, `Purchase`, `EstimatedAuthorisation`, or `Payout` |


## Step 1: Install the Web SDK library

Install the latest version of the Web SDK from the npm public registry:

```shell
npm i @pxpio/web-components-sdk
```

Import `PxpCheckout`, `IntentType`, and the Aeropay component types from the SDK:

```typescript
import { PxpCheckout, IntentType, AeropayButtonComponent, AeropayButtonComponentConfig } from '@pxpio/web-components-sdk';
```

## Step 2: Create a session on your backend

Create sessions on your backend using PXP-UST1 HMAC authentication. Never expose your PXP token value or other API credentials in frontend code.

Send a `POST` request to `/api/v1/sessions` with the Aeropay intent under `transactionMethod.intent.aeropay`:

```json
{
  "merchant": "MERCHANT-1",
  "site": "SITE-1",
  "sessionTimeout": 1200,
  "merchantTransactionId": "0f3501f0-2577-4dee-8be2-bbb6908588e3",
  "amounts": {
    "currencyCode": "USD",
    "transactionValue": 25.00
  },
  "transactionMethod": {
    "intent": {
      "aeropay": "Authorisation"
    }
  },
  "allowTransaction": true
}
```

Configure the request with these Aeropay-specific values:

| Property | Description |
|  --- | --- |
| `merchantTransactionId`string | Your unique identifier for the session transaction. We recommend reusing the value when initialising the SDK to simplify reconciliation. |
| `amounts.currencyCode`string | Transaction currency. Set this to `USD`. |
| `amounts.transactionValue`number | The payment or payout amount. |
| `transactionMethod.intent.aeropay`string | The Aeropay transaction intent. Use `Authorisation`, `Purchase`, `EstimatedAuthorisation`, or `Payout`. |
| `allowTransaction`boolean | Whether the session can be used to submit a transaction. |


For the complete authentication process and request headers, see the [Components for Web quickstart](/guides/checkout/components/web/quickstart).

### Session response

If Aeropay is configured for the site, the session response includes its funding configuration:

```json
{
  "sessionId": "c5f0799b-0839-43ce-abc5-5b462a98f250",
  "hmacKey": "904bc42395d4af634e2fd48ee8c2c7f52955a1da97a3aa3d82957ff12980a7bb",
  "encryptionKey": "20d175a669ad3f8c195c9c283fc86155",
  "sessionExpiry": "2026-07-21T12:00:00.000Z",
  "allowedFundingTypes": {
    "payByBanks": {
      "aeropay": {
        "externalMerchantId": "aeropay-merchant-id",
        "configurationId": "aerosync-configuration-id"
      }
    }
  }
}
```

The SDK requires both `allowedFundingTypes.payByBanks.aeropay.externalMerchantId` and `allowedFundingTypes.payByBanks.aeropay.configurationId`.

PXP adds the Aeropay funding configuration to the session automatically from your Unity Portal setup. Don't add Aeropay credentials to the response yourself.

Return the session and `merchantTransactionId` to your frontend:

```json
{
  "session": {
    "sessionId": "c5f0799b-0839-43ce-abc5-5b462a98f250",
    "hmacKey": "904bc42395d4af634e2fd48ee8c2c7f52955a1da97a3aa3d82957ff12980a7bb",
    "encryptionKey": "20d175a669ad3f8c195c9c283fc86155",
    "allowedFundingTypes": {
      "payByBanks": {
        "aeropay": {
          "externalMerchantId": "aeropay-merchant-id",
          "configurationId": "aerosync-configuration-id"
        }
      }
    }
  },
  "merchantTransactionId": "0f3501f0-2577-4dee-8be2-bbb6908588e3"
}
```

## Step 3: Initialise the SDK on your frontend

Request the session from your backend, then initialise `PxpCheckout`:

```typescript
const sessionResult = await fetch('/api/checkout/session', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    amount: 25,
    intent: 'Authorisation'
  })
}).then((response) => response.json());

const pxpSdk = PxpCheckout.initialize({
  environment: 'test',
  session: sessionResult.session,
  ownerId: 'MERCHANT_GROUP_1',
  ownerType: 'MerchantGroup',
  transactionData: {
    currency: 'USD',
    amount: 25,
    entryType: 'Ecom',
    intent: {
      aeropay: IntentType.Authorisation
    },
    merchantTransactionId: sessionResult.merchantTransactionId,
    merchantTransactionDate: () => new Date().toISOString()
  },
  onGetShopper: async () => ({
    id: 'shopper-123',
    firstName: 'John',
    lastName: 'Doe',
    email: 'john.doe@example.com',
    phoneNumber: '+14155550123'
  })
});
```

Set `environment` to `test` for UAT or `live` for production.

Keep the session request and SDK transaction data consistent so that you can trace and reconcile transactions. The browser SDK doesn't compare the `merchantTransactionId`, amount, currency, or intent with the values used to create the session. Verify the completed transaction against records stored on your backend.

### Shopper data

For new shoppers, the SDK uses `onGetShopper` to prefill the consumer data screen. It supports these fields:

* `firstName`
* `lastName`
* `email`
* `phoneNumber`


If you provide a field, it must be valid. First and last names accept a maximum of 100 Unicode letters and spaces. Email addresses accept a maximum of 128 characters and must match the SDK's email format. Phone numbers must contain `+1` followed by ten digits, such as `+14155550123`.

If a supplied name, email address, or phone number is non-empty but invalid, the SDK invokes `onError` with `SDK1300` before opening the popup.

The SDK calls `onGetShopper` again when it builds the transaction request, so return the current shopper data each time.

Return only the data required for the flow. Don't include personal data in `merchantTransactionId`, `shopper.id`, URLs, or free-text order descriptions.

## Step 4: Create the Aeropay button

Create the component with `pxpSdk.create()`:

```typescript
const config: AeropayButtonComponentConfig = {
  onCustomValidation: async () => {
    return await validateCheckoutBusinessRules();
  },
  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 failed', error);
    showPaymentError('Unable to complete the transaction.');
  },
  onError: (error) => {
    console.error('Aeropay flow failed', error);
    showPaymentError('Unable to continue with Aeropay.');
  }
};

const aeropayButton = pxpSdk.create(
  'aeropay-button',
  config
) as AeropayButtonComponent;
```

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

`onCancel` runs only when the shopper selects the popup's close button. Closing the popup with `Escape` or unmounting the component doesn't invoke it.

For all component properties, see [Configuration](/guides/checkout/components/web/aeropay/configuration). For callback payloads and examples, see [Events](/guides/checkout/components/web/aeropay/events).

## Step 5: Mount the button

Add a container element where the SDK can render the Aeropay button:

```html
<div id="aeropay-button-container"></div>
```

Pass the container's element ID to `mount()`:

```typescript
aeropayButton.mount('aeropay-button-container');
```

## Step 6: Unmount the component

Call `unmount()` when your checkout view is destroyed:

```typescript
return () => {
  aeropayButton.unmount();
};
```

Unmounting removes the button, popup resources, and event listeners.

## Step 7: Verify the transaction on your backend

After transaction submission, `onPostAuthorisation` receives the merchant and PXP transaction identifiers. Send the result to your backend and retrieve the transaction from PXP before updating the order or payout:

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

    await fetch('/api/checkout/verify', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        merchantTransactionId: result.merchantTransactionId,
        systemTransactionId: result.systemTransactionId
      })
    });
  }
};
```

Your backend verification must:

1. Authenticate directly with PXP.
2. Retrieve the transaction using its transaction identifier.
3. Confirm that the merchant, amount, currency, intent, and final state match your records.
4. Update the order or payout only after every check passes.


Don't trust the request body sent by the browser. Use it only to identify the transaction, then compare the authoritative PXP response with values stored on your backend.

## Manage post-transaction operations

After a successful Aeropay transaction, you can perform follow-up actions manually in the Unity Portal under **Report & search > Report**:

* **Capture:** Capture funds for an authorised transaction.
* **Increment:** Increase the authorised amount.
* **Void:** Cancel an authorisation before it's captured.
* **Refund:** Return funds for a captured or purchased transaction.


To take an action:

1. In the Unity Portal, go to **Report & search > Report**.
2. Find the transaction using the `merchantTransactionId` or `systemTransactionId` from `onPostAuthorisation`.
3. Open the transaction details and choose the required action.


Available actions depend on the transaction intent and current state. A `Purchase` captures funds at submission, so it doesn't need a separate capture.

For the full lifecycle context, see [Post-transaction operations](/guides/checkout/components/web/aeropay/how-it-works#post-transaction-operations) in *How it works*.

## New-shopper flow

Use the new-shopper flow when you don't have a verified Aeropay user ID. Don't set `userId` on the component.

The shopper completes these stages:

1. Reviews or enters their first name, last name, email address, and phone number.
2. Enters the OTP sent to their phone by SMS.
3. Selects a linked bank account or links a new account through Aerosync.
4. Confirms the transaction.


Save the verified Aeropay user ID in `onUserVerificationSuccess`:

```typescript
const config: AeropayButtonComponentConfig = {
  onUserVerificationSuccess: async (user) => {
    await fetch('/api/customers/aeropay-user', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        shopperId: 'shopper-123',
        aeropayUserId: user.id
      })
    });
  },
  onPreAuthorisation: () => true,
  onPostAuthorisation: (result) => {
    const submitResult = result as {
      merchantTransactionId: string;
      systemTransactionId: string;
    };
    verifyPaymentOnBackend({
      merchantTransactionId: submitResult.merchantTransactionId,
      systemTransactionId: submitResult.systemTransactionId
    });
  }
};

const aeropayButton = pxpSdk.create(
  'aeropay-button',
  config
) as AeropayButtonComponent;
```

### Skip consumer data collection

If your application already has all four consumer fields, set `skipConsumerDataCollection` to `true` to begin with OTP verification:

```typescript
const config: AeropayButtonComponentConfig = {
  skipConsumerDataCollection: true,
  onUserVerificationSuccess: (user) => {
    saveAeropayUserId(user.id);
  },
  onPreAuthorisation: () => true
};

const aeropayButton = pxpSdk.create(
  'aeropay-button',
  config
) as AeropayButtonComponent;
```

The SDK skips the screen only when `onGetShopper` returns valid, non-empty `firstName`, `lastName`, `email`, and `phoneNumber` values, and `consumerDataCollectionConfig.editableFields` is omitted or empty.

## Returning-shopper flow

For a returning shopper, get their stored Aeropay user ID from your backend and pass it to the component:

```typescript
const aeropayProfile = await fetch(
  '/api/customers/shopper-123/aeropay'
).then((response) => response.json());

const config: AeropayButtonComponentConfig = {
  userId: aeropayProfile.userId,
  onPreAuthorisation: () => true,
  onPostAuthorisation: (result) => {
    const submitResult = result as {
      merchantTransactionId: string;
      systemTransactionId: string;
    };
    verifyPaymentOnBackend({
      merchantTransactionId: submitResult.merchantTransactionId,
      systemTransactionId: submitResult.systemTransactionId
    });
  },
  onError: (error) => {
    if (error.ErrorCode === 'SDK1307' || error.ErrorCode === 'SDK1309') {
      offerNewShopperFlow();
      return;
    }

    showPaymentError('Unable to continue with Aeropay.');
  }
};

const aeropayButton = pxpSdk.create(
  'aeropay-button',
  config
) as AeropayButtonComponent;
```

The SDK validates that the Aeropay user exists and is active. It then skips consumer data collection and OTP verification, and opens bank selection.

If the user isn't found or isn't active, `onError` receives `SDK1309` or `SDK1307`. Remove the invalid stored ID and let the shopper restart the new-shopper flow.

Associate each Aeropay user ID with the authenticated customer on your backend. Retrieve it from your backend rather than browser storage, and don't accept a `userId` supplied or changed by the browser.

The SDK and provider handle bank linking. Don't collect routing numbers or full account numbers in your checkout. If you store bank metadata for a business need, restrict access and retain only the required values.

## Payout flow

Use `IntentType.Payout` in the SDK and `Payout` in the session request:

```typescript
const pxpSdk = PxpCheckout.initialize({
  // ...session configuration
  transactionData: {
    currency: 'USD',
    amount: 25,
    entryType: 'Ecom',
    intent: {
      aeropay: IntentType.Payout
    },
    merchantTransactionId: sessionResult.merchantTransactionId,
    merchantTransactionDate: () => new Date().toISOString()
  },
  onGetShopper: getCurrentShopper
});
```

By default, shoppers can only select an existing linked bank account during a payout. To allow bank linking, set `allowLinkBankOnPayout` to `true`:

```typescript
const config: AeropayButtonComponentConfig = {
  userId: aeropayProfile.userId,
  bankSelectionConfig: {
    allowLinkBankOnPayout: true
  },
  onPreAuthorisation: () => true,
  onPostAuthorisation: (result) => {
    const submitResult = result as {
      merchantTransactionId: string;
      systemTransactionId: string;
    };
    verifyPayoutOnBackend({
      merchantTransactionId: submitResult.merchantTransactionId,
      systemTransactionId: submitResult.systemTransactionId
    });
  }
};

const aeropayButton = pxpSdk.create(
  'aeropay-button',
  config
) as AeropayButtonComponent;
```

Before enabling payouts, confirm that your PXP and Aeropay accounts support them. Validate customer eligibility, amount limits, account status, and duplicate requests on your backend.

## Control the component

After mounting the `AeropayButtonComponent` created in Step 4, you can update the button's availability and visibility:

```typescript
aeropayButton.setDisabled(true);
aeropayButton.setDisabled(false);

aeropayButton.hide();
aeropayButton.show();
```

Use `setDisabled()` while your checkout is unavailable or being updated. Use `hide()` and `show()` when Aeropay availability depends on your application state.

## Complete React example

The following example creates a new-shopper `Authorisation` flow and cleans up the component safely:

```tsx
import { useEffect } from 'react';
import { PxpCheckout, IntentType, AeropayButtonComponent, AeropayButtonComponentConfig } from '@pxpio/web-components-sdk';

export default function AeropayCheckout() {
  useEffect(() => {
    let cancelled = false;
    let component: AeropayButtonComponent | undefined;

    async function initialiseAeropay() {
      const sessionResult = await fetch('/api/checkout/session', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          amount: 25,
          intent: 'Authorisation'
        })
      }).then((response) => response.json());

      if (cancelled) {
        return;
      }

      const pxpSdk = PxpCheckout.initialize({
        environment: 'test',
        session: sessionResult.session,
        ownerId: 'MERCHANT_GROUP_1',
        ownerType: 'MerchantGroup',
        transactionData: {
          currency: 'USD',
          amount: 25,
          entryType: 'Ecom',
          intent: {
            aeropay: IntentType.Authorisation
          },
          merchantTransactionId: sessionResult.merchantTransactionId,
          merchantTransactionDate: () => new Date().toISOString()
        },
        onGetShopper: async () => ({
          id: 'shopper-123',
          firstName: 'John',
          lastName: 'Doe',
          email: 'john.doe@example.com',
          phoneNumber: '+14155550123'
        })
      });

      const config: AeropayButtonComponentConfig = {
        onUserVerificationSuccess: async (user) => {
          await fetch('/api/customers/aeropay-user', {
            method: 'PUT',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              shopperId: 'shopper-123',
              aeropayUserId: user.id
            })
          });
        },
        onCancel: () => {
          console.log('Aeropay popup close button selected');
        },
        onPreAuthorisation: async () => {
          const validation = await fetch('/api/orders/validate', {
            method: 'POST'
          }).then((response) => response.json());

          return validation.approved;
        },
        onPostAuthorisation: async (result) => {
          const submitResult = result as {
            merchantTransactionId: string;
            systemTransactionId: string;
          };

          await fetch('/api/checkout/verify', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              merchantTransactionId: submitResult.merchantTransactionId,
              systemTransactionId: submitResult.systemTransactionId
            })
          });
        },
        onSubmitError: (error) => {
          console.error('Aeropay transaction failed', error);
        },
        onError: (error) => {
          console.error('Aeropay flow failed', error);
        }
      };

      const aeropayButton = pxpSdk.create(
        'aeropay-button',
        config
      ) as AeropayButtonComponent;

      if (cancelled) {
        aeropayButton.unmount();
        return;
      }

      aeropayButton.mount('aeropay-button-container');
      component = aeropayButton;
    }

    void initialiseAeropay();

    return () => {
      cancelled = true;
      component?.unmount();
    };
  }, []);

  return <div id="aeropay-button-container"></div>;
}
```