Skip to content

Events

Implement callbacks to customise your Payout Drop-in withdrawal flow.

Overview

Payout Drop-in provides a unified event system across payout methods. Use these callbacks to inject business logic and UX customisations at critical points in the withdrawal flow. The SDK loads instruments and submits payouts; you control confirmation, loading states, error messaging, and backend reconciliation.

Callbacks enable you to:

  • Supply the authenticated shopper ID used to load stored instruments and PayPal.
  • Validate business rules before a card-on-file payout proceeds.
  • Display custom loading states and progress indicators.
  • Show shopper-safe error messages.
  • Verify successful submissions on your backend before updating withdrawal status.
  • Track analytics and monitor withdrawal performance.
  • Offer retry or alternative methods when errors occur.

onSuccess and onError are required. onGetShopper is strongly recommended whenever Drop-in must resolve stored instruments. onBeforeSubmit, onSubmit, and analyticsEvent are optional.

PayPal uses onSuccess and onError for the submit path. Drive PayPal loading UI from those callbacks. There is no Drop-in onCancel for the PayPal stored panel. onBeforeSubmit and onSubmit run for Card, Apple Pay, and Google Pay only. onPayoutMethodChange isn't available on PayoutDropIn.initialize().

Some failures occur outside onError, such as synchronous validation from initialize(), or a rejected onGetShopper promise that causes create() to reject. Wrap initialize() and create() in try or catch. When onError runs during create() (e.g., SDK1700 or SDK1701), create() usually settles without throwing. See Error handling.

Supported events

onGetShopper

This callback provides shopper information so Drop-in can load stored payout instruments and the PayPal wallet association.

Typical uses include:

  • Provide the shopper ID for logged-in users.
  • Enable Card, Apple Pay, and Google Pay token lists for returning shoppers.
  • Resolve the linked PayPal account for the PayPal panel.
  • Reject guest or unauthenticated sessions before Drop-in mounts.

Event data

This callback receives no parameters and must return a Promise that resolves to a shopper object.

Return value

The callback must resolve to a shopper object with this property:

PropertyDescription
id
string
required
The stable shopper identifier from your authenticated session. Don't take this from untrusted client input alone.

Example implementation

The following example returns the authenticated shopper ID from your session API:

const payoutDropIn = PayoutDropIn.initialize({
  // ... other config
  onGetShopper: async () => {
    const session = await fetch('/api/me').then((response) => response.json());

    if (!session.shopperId) {
      throw new Error('Shopper not authenticated');
    }

    return { id: session.shopperId };
  },
});

Require login before withdrawals:

onGetShopper: async () => {
  const user = getAuthenticatedUser();

  if (!user?.shopperId) {
    throw new Error('Log in to withdraw funds');
  }

  return { id: user.shopperId };
},

Without a shopper ID, token retrieval is skipped and PayPal can't resolve a linked account. Methods may disappear rather than throwing. If this promise rejects, create() rejects. Show a login prompt and don't assume onError will fire.

onBeforeSubmit

Drop-in calls this callback for Card, Apple Pay, and Google Pay when the shopper is about to submit a withdrawal. This is your last chance to validate data or cancel before card-on-file submit starts.

Use this callback to:

  • Perform final validation before payout submission.
  • Verify withdrawal eligibility or account status.
  • Display confirmation dialogs.
  • Track analytics events.
  • Block duplicate withdrawals while one is already in flight.

Event data

The callback receives the selected payout method:

ParameterDescription
payoutMethod
PayoutMethod
required
The selected payout method for the panel that is submitting. One of Card, ApplePay, or GooglePay.

Return value

The return value controls whether submission continues:

  • true or undefined: Continue with payout submission. If the callback returns undefined, Drop-in treats that as continue.
  • false: Cancel payout submission. Loading state is cleared; onSubmit isn't called.
  • Promise<boolean>: Async validation (the resolved value determines whether to proceed).

Example implementation

The following example confirms the withdrawal and checks eligibility before allowing submit:

import { PayoutDropIn } from '@pxpio/web-components-sdk';

const payoutDropIn = PayoutDropIn.initialize({
  // ... other config
  onBeforeSubmit: async (payoutMethod) => {
    console.log('Payout method selected:', payoutMethod);

    const confirmed = await showConfirmationDialog({
      title: 'Confirm withdrawal',
      message: `Withdraw ${formatMoney(amount)} using ${payoutMethod}?`,
      confirmText: 'Confirm',
      cancelText: 'Cancel',
    });

    if (!confirmed) {
      return false;
    }

    const check = await fetch('/api/withdrawal/eligibility', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        withdrawalId,
        payoutMethod,
      }),
    }).then((response) => response.json());

    if (!check.eligible) {
      showMessage(check.reason);
      return false;
    }

    return true;
  },
});

This shorter example cancels submit with a synchronous eligibility check:

onBeforeSubmit: (payoutMethod) => {
  if (!isWithdrawalAllowed(payoutMethod)) {
    showMessage("This withdrawal can't proceed. Please review your details.");
    return false;
  }

  return true;
},

Returning true only allows the SDK to continue. It isn't server authorisation of the payout. Perform final reconciliation on your backend after onSuccess or a webhook.

onSubmit

Drop-in calls this callback for Card, Apple Pay, and Google Pay when payout processing begins, after onBeforeSubmit validation passes. Use this to show loading indicators and disable UI elements.

Common patterns include:

  • Show loading spinners or progress indicators.
  • Disable submit controls to prevent double-submission.
  • Display "Processing withdrawal…" messages.
  • Update UI to show the payout is in progress.
  • Track analytics for payout submission.

Event data

The callback receives the payout method that started submission:

ParameterDescription
payoutMethod
PayoutMethod
required
The payout method whose submission has started (Card, ApplePay, or GooglePay).

Example implementation

The following example shows a loading overlay and disables the withdrawal form:

const payoutDropIn = PayoutDropIn.initialize({
  // ... other config
  onSubmit: (payoutMethod) => {
    console.log('Processing payout with:', payoutMethod);

    const overlay = document.getElementById('payout-overlay');
    if (overlay) {
      overlay.hidden = false;
    }

    disableWithdrawalForm(true);
  },
});

The following example shows loading UI and warns if submit takes longer than expected:

let loadingTimeout: ReturnType<typeof setTimeout> | undefined;

onSubmit: (payoutMethod) => {
  setLoadingState(true);

  loadingTimeout = setTimeout(() => {
    showMessage(
      'This withdrawal is taking longer than expected. Please wait…'
    );
  }, 10000);

  window.payoutStartTime = Date.now();
},

Pair with onSuccess and onError to clear loading state. Drop-in also clears its own submission-in-progress flag when those outcomes are delivered through the SDK handler.

onSuccess

Drop-in calls this callback after a payout submission succeeds. It receives the result from the payout processing path, including PayPal.

After a successful submit, you typically:

  • Verify the payout on your backend (required).
  • Redirect to a status page after verification.
  • Display success messages.
  • Track successful payout analytics.
  • Clear loading UI.

Event data

The callback receives a result object with these properties:

Event dataDescription
result
PayoutDropInSubmitResult
required
The payout processing result from the SDK.
result.systemTransactionId
string | undefined
The Unity system transaction ID for a single-method payout. Prefer this for backend verification when present.
result.merchantTransactionId
string | undefined
Your merchant transaction ID when returned by the flow.
result.payoutMethod
PayoutMethod | undefined
The method used for a single-method payout (e.g., Card, Paypal, ApplePay, or GooglePay).
result.payouts
ClosedLoopPayoutResult[] | undefined
Closed-loop results when that flow creates one or more payout transactions. Each entry has systemTransactionId and merchantTransactionId. When a line isn't Authorised or Pending, it can also include amount, currency, errorCode, and errorReason. For closed-loop, top-level systemTransactionId may be omitted.

PayoutDropInSubmitResult type:

interface PayoutDropInSubmitResult {
  systemTransactionId?: string;
  merchantTransactionId?: string;
  payoutMethod?: PayoutMethod;
  payouts?: Array<{
    systemTransactionId: string;
    merchantTransactionId: string;
    amount?: number;
    currency?: string;
    errorCode?: string;
    errorReason?: string;
  }>;
}

The onSuccess callback is a frontend event and can be manipulated in the browser. For closed-loop, onSuccess can fire with a mix of successful and failed lines in payouts. Never mark a withdrawal paid, credit a balance, or settle funds based on this callback alone. Always verify with your webhook handler or a server-side transaction lookup before updating withdrawal status.

Example implementation

The following example verifies the payout on your backend, then redirects to a status page:

import {
  PayoutDropIn,
  type PayoutDropInSubmitResult,
} from '@pxpio/web-components-sdk';

const payoutDropIn = PayoutDropIn.initialize({
  // ... other config
  onSuccess: async (result: PayoutDropInSubmitResult) => {
    if (loadingTimeout) {
      clearTimeout(loadingTimeout);
    }

    setLoadingState(false);
    showMessage('Withdrawal received. Verifying…');

    try {
      const verification = await fetch('/api/verify-payout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          systemTransactionId: result.systemTransactionId,
          merchantTransactionId: result.merchantTransactionId,
          payoutMethod: result.payoutMethod,
          payouts: result.payouts,
        }),
      }).then((response) => {
        if (!response.ok) {
          throw new Error('Verification request failed');
        }
        return response.json();
      });

      if (verification.success) {
        window.location.href = `/withdrawals/${verification.id}/status`;
        return;
      }

      showMessage(
        "We couldn't verify this withdrawal yet. Please check your email or contact support with your reference: " +
          `${result.merchantTransactionId ?? result.systemTransactionId}`
      );
    } catch (error) {
      console.error('Failed to verify payout:', error);
      showMessage(
        "Unable to verify this withdrawal. It may still be processing. Contact support with your reference: " +
          `${result.merchantTransactionId ?? result.systemTransactionId}`
      );
    }
  },
});

onError

Drop-in calls this callback when an error occurs during configuration, method resolution, or payout submission.

Handle errors so you can:

  • Display shopper-safe error messages.
  • Log errors for debugging and monitoring.
  • Track failed payout analytics.
  • Offer retry or alternative methods.
  • Hide loading indicators.
  • Re-enable form controls.

Event data

The callback receives a BaseSdkException with these properties:

ParameterDescription
error
BaseSdkException
required
The error object containing details about what went wrong.
error.message
string
required
A human-readable error message. Derive shopper copy carefully; prefer your own mapped messages.
error.ErrorCode
string
required
The SDK error code in the form SDK#### (e.g., 'SDK1700', 'SDK1701', 'SDK1703'). Use this for programmatic handling.
error.name
string
The exception class name.
error.details
unknown
A structured payload on some payout initiation failures.

Import from:

import type { BaseSdkException } from '@pxpio/web-components-sdk';

Use error.ErrorCode for branching. There's no separate code property on BaseSdkException.

Common error scenarios

The following table shows common error scenarios and how to detect and respond to them:

ScenarioDetection approachUser action
Payout Drop-in configuration missingerror.ErrorCode === 'SDK1700'Refresh or try again later. Confirm the site service is active.
No eligible payout methodserror.ErrorCode === 'SDK1701'Link an eligible instrument or use another account path.
Payout initiation or card-on-file submit failederror.ErrorCode === 'SDK1703'Retry or choose another method. Confirm backend transaction state first.
Network errorerror.ErrorCode === 'SDK0500'Check the connection and retry.
Session or credential problemerror.message mentions session or credentialsRefresh the page and create a new payout session.

See Error handling for the full code table, SDK1703 collision notes, and recovery patterns.

Example implementation

The following example clears loading state and maps common payout error codes to shopper-safe messages:

import {
  PayoutDropIn,
  type BaseSdkException,
} from '@pxpio/web-components-sdk';

const payoutDropIn = PayoutDropIn.initialize({
  // ... other config
  onError: (error: BaseSdkException) => {
    if (loadingTimeout) {
      clearTimeout(loadingTimeout);
    }

    setLoadingState(false);
    disableWithdrawalForm(false);

    console.error('Payout Drop-in', {
      errorCode: error.ErrorCode,
      message: error.message,
      name: error.name,
      details: error.details,
    });

    let userMessage =
      "We couldn't complete your withdrawal. Please try again or contact support.";

    if (error.ErrorCode === 'SDK0500') {
      userMessage =
        'Network connection issue. Please check your internet connection and try again.';
    } else if (error.ErrorCode === 'SDK1700') {
      userMessage =
        "We couldn't load withdrawal settings. Please refresh or try again later.";
    } else if (error.ErrorCode === 'SDK1701') {
      userMessage = 'No withdrawal methods are available for your account.';
    } else if (error.ErrorCode === 'SDK1703') {
      userMessage =
        "This withdrawal couldn't be completed. Please try again or choose another method.";
    }

    showMessage(userMessage);
  },
});

analyticsEvent

Optional hook for structured SDK analytics payloads. Treat it as observational alongside onSuccess, onError, and backend webhooks.

Example implementation

The following example forwards SDK analytics events to Google Analytics when gtag is available:

analyticsEvent: (event) => {
  if (typeof gtag !== 'undefined') {
    gtag('event', event.eventName, {
      session_id: event.sessionId,
      timestamp:
        event.timestamp instanceof Date
          ? event.timestamp.toISOString()
          : event.timestamp,
    });
  }
},

Don't block the withdrawal UI waiting on analytics network calls. Fire and forget, or queue events. See Analytics.

Event data structures

PayoutMethod

For Payout Drop-in on Web, PayoutMethod identifies the method in use. Values for Card, PayPal, Apple Pay, and Google Pay are:

enum PayoutMethod {
  Card = 'Card',
  Paypal = 'Paypal',
  ApplePay = 'ApplePay',
  GooglePay = 'GooglePay',
}

Import from:

import { PayoutMethod } from '@pxpio/web-components-sdk';

PayoutDropInSubmitResult interface

The success callback receives a PayoutDropInSubmitResult object:

interface PayoutDropInSubmitResult {
  systemTransactionId?: string;
  merchantTransactionId?: string;
  payoutMethod?: PayoutMethod;
  payouts?: Array<{
    systemTransactionId: string;
    merchantTransactionId: string;
  }>;
}

Import from:

import type { PayoutDropInSubmitResult } from '@pxpio/web-components-sdk';

BaseSdkException interface

The error callback receives a BaseSdkException object:

interface BaseSdkException {
  message: string;
  ErrorCode: string;
  name?: string;
  details?: unknown;
}

Import from:

import type { BaseSdkException } from '@pxpio/web-components-sdk';

Shopper interface

The onGetShopper callback must return a shopper object:

interface Shopper {
  id: string;
}

Error handling in events

Handle event-callback errors gracefully and give shoppers clear next steps. Prefer branching on ErrorCode, then fall back to message or details when you need more context.

onError: (error: BaseSdkException) => {
  hideLoadingIndicator();

  if (error.ErrorCode === 'SDK1701') {
    showMessage('No withdrawal methods are available for your account.');
    return;
  }

  if (error.ErrorCode === 'SDK1700') {
    showMessage(
      "We couldn't load withdrawal settings. Please refresh or try again later."
    );
    return;
  }

  if (error.ErrorCode === 'SDK1703') {
    showMessage(
      "This withdrawal couldn't be completed. Please try again or choose another method."
    );
    return;
  }

  showMessage(
    "We couldn't complete your withdrawal. Please try again or contact support."
  );
},

For recovery patterns, retry guidance, and the full code reference, see Error handling.

Callback execution order

Understanding the callback flow helps you implement withdrawal handling correctly.

Card, Apple Pay, and Google Pay

Callbacks run in this order for card-on-file methods:

  1. onGetShopper: Runs at the start of create(). Returns the shopper ID used for token lookup.
  2. onBeforeSubmit: Shopper selects a stored token and confirms. Return true or undefined to proceed, or false to cancel.
  3. onSubmit: Runs if onBeforeSubmit allows submission. Show loading UI.
  4. onSuccess or onError: Submission completed or failed. Verify on your backend after onSuccess.

PayPal

Callbacks run in this order for the PayPal panel:

  1. onGetShopper: Runs at the start of create(). Returns the shopper ID used for wallet association lookup.
  2. onSuccess or onError: Shopper submits from the PayPal panel. onBeforeSubmit and onSubmit aren't called for this panel.

Mount failures

During mount, failures can surface like this:

  1. onGetShopper: Runs at the start of create().
  2. Configuration or empty-method failures during mount call onError (SDK1700, SDK1701, and related codes). create() usually settles without throwing in those cases.
  3. A rejected onGetShopper causes create() to reject instead of calling onError.

Complete integration example

The following example wires the main callbacks together for a Payout Drop-in mount:

import {
  PayoutDropIn,
  type PayoutDropInSubmitResult,
  type BaseSdkException,
} from '@pxpio/web-components-sdk';

let loadingTimeout: ReturnType<typeof setTimeout> | undefined;

async function initializePayoutDropIn(sessionData: unknown) {
  const payoutDropIn = PayoutDropIn.initialize({
    environment: 'test',
    session: sessionData,
    ownerId: 'YOUR-MERCHANT-GROUP-ID',
    transactionData: {
      currency: 'USD',
      amount: 25,
      entryType: 'Ecom',
      merchantTransactionId: crypto.randomUUID(),
      merchantTransactionDate: () => new Date().toISOString(),
    },

    onGetShopper: async () => {
      const user = getAuthenticatedUser();
      if (!user?.shopperId) {
        throw new Error('Log in to withdraw funds');
      }
      return { id: user.shopperId };
    },

    onBeforeSubmit: async (payoutMethod) => {
      const confirmed = await showConfirmationDialog({
        title: 'Confirm withdrawal',
        message: `Withdraw using ${payoutMethod}?`,
        confirmText: 'Confirm',
        cancelText: 'Cancel',
      });
      return confirmed;
    },

    onSubmit: (payoutMethod) => {
      console.log('Processing payout:', payoutMethod);
      setLoadingState(true);
      loadingTimeout = setTimeout(() => {
        showMessage(
          'This withdrawal is taking longer than expected. Please wait…'
        );
      }, 10000);
    },

    onSuccess: async (result: PayoutDropInSubmitResult) => {
      if (loadingTimeout) {
        clearTimeout(loadingTimeout);
      }
      setLoadingState(false);

      const verification = await fetch('/api/verify-payout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          systemTransactionId: result.systemTransactionId,
          merchantTransactionId: result.merchantTransactionId,
          payoutMethod: result.payoutMethod,
          payouts: result.payouts,
        }),
      }).then((response) => response.json());

      if (verification.success) {
        window.location.href = `/withdrawals/${verification.id}/status`;
        return;
      }

      showMessage(
        "We couldn't verify this withdrawal yet. Please contact support with your reference."
      );
    },

    onError: (error: BaseSdkException) => {
      if (loadingTimeout) {
        clearTimeout(loadingTimeout);
      }
      setLoadingState(false);

      console.error('Payout failed:', error.ErrorCode, error.message);

      if (error.ErrorCode === 'SDK1701') {
        showMessage('No withdrawal methods are available for your account.');
        return;
      }

      if (error.ErrorCode === 'SDK1700') {
        showMessage(
          "We couldn't load withdrawal settings. Please refresh or try again later."
        );
        return;
      }

      showMessage(
        "We couldn't complete your withdrawal. Please try again or contact support."
      );
    },

    analyticsEvent: (event) => {
      console.log(event.eventName, event.sessionId);
    },
  });

  await payoutDropIn.create('payout-drop-in-container');
}