Skip to content

Events

Implement callbacks to customise your Drop-in payment flow.

Overview

Drop-in provides a unified event system that works consistently across all payment methods. You can use these callbacks to inject your own business logic and user experience customisations into the payment flow at critical moments. They ensure that while the SDK handles the complex technical aspects of payment processing, you retain full control over the customer experience and can seamlessly integrate payments into your broader business workflows and systems.

Callbacks enable you to:

  • Validate business rules before payments proceed.
  • Display custom loading states and progress indicators.
  • Show user-friendly error messages.
  • Track analytics and monitor payment performance.
  • Integrate with your own systems for fraud detection or customer management.
  • Implement card-on-file functionality for returning customers.

Your callbacks receive normalised data regardless of whether the customer paid with cards, PayPal, Google Pay, or Aeropay.

All callbacks are optional. onSuccess and onError are strongly recommended for production. Without onError, setup and payment failures are silently ignored.

Supported events

onGetShopper

This callback provides shopper information for card-on-file functionality, allowing returning customers to use saved payment methods.

Card-on-file also requires methodConfig.card.showCOF to resolve to true (the default when omitted). On Android, the saved-cards section header and COF panel can appear while tokens are loading or when cardTokens is non-empty. The token list appears only when cardTokens is non-empty. See Cards.

onGetShopper returns your merchant shopper ID for vault and card-on-file behaviour. Linking the Unity session to a Customer Profile is separate: set optional customerProfileId on the Sessions API request on your backend. See Implementation — Customer Profile.

You can use it to:

  • Provide shopper ID for logged-in users.
  • Generate anonymous shopper ID for guest checkout.
  • Enable card-on-file for returning customers.
  • Associate payment methods with customer accounts.

Event data

This callback receives no parameters and must return a Shopper object (or null).

Return value

The callback returns:

PropertyDescription
id
String
required
A unique shopper identifier. Use customer ID for logged-in users or generate a unique ID for guests. Card-on-file requires a non-empty id.
firstName
String?
Shopper first name. Used by Aeropay for consumer data when methodConfig.aeropay.userId isn't set.
lastName
String?
Shopper last name. Used by Aeropay for consumer data when userId isn't set.
email
String?
Shopper email. Used by Aeropay for consumer data when userId isn't set.
phoneNumber
String?
Shopper phone number. Used by Aeropay for consumer data when userId isn't set.

For Aeropay, prefill consumer fields via onGetShopper, or set methodConfig.aeropay.userId for returning shoppers. Missing fields are handled by the consumer-data collection screen instead. See Aeropay.

Example implementation

Configure the callback as follows:

import com.pxp.checkout.services.models.transaction.Shopper

onGetShopper = {
    // For logged-in users, return their customer ID
    val customerId = getCurrentCustomerId()
    if (customerId != null) {
        return@onGetShopper Shopper(id = customerId)
    }

    // For guest users, generate or retrieve a session-based ID
    val guestId = getOrCreateGuestId()
    Shopper(id = guestId)
}

The shopper ID is used to store and retrieve saved payment methods. For guests, generate a unique ID such as a UUID that persists across the session. For registered users, use their customer or account ID from your system.

onGetShippingAddress

This callback supplies a shipping address for billing prefill and for PayPal when shippingPreference is SET_PROVIDED_ADDRESS. Card, Google Pay, and PayPal transaction builders can consume it.

import com.pxp.checkout.models.ShippingAddress

onGetShippingAddress = {
    ShippingAddress(
        addressLine1 = "221B Baker Street",
        city = "London",
        postalCode = "NW1 6XE",
        countryCode = "GB"
    )
}

For configuration details, see Configuration: shipping address callback.

onBeforeSubmit

This callback is triggered when a payment method is selected and the user is about to submit payment. This is your last chance to validate data or block submission before it's processed.

Drop-in wires this callback for Card, PayPal, Google Pay, and Aeropay. For Aeropay, return false to stop the flow before the popup opens.

You can use it to:

  • Perform final validation before payment submission.
  • Check inventory availability.
  • Verify customer account status.
  • Display confirmation dialogs.
  • Track analytics events.
  • Perform fraud checks.

Event data

This callback receives the following data:

ParameterDescription
paymentMethod
PaymentMethod
required
The selected payment method.

Possible values:
  • PaymentMethod.CARD
  • PaymentMethod.PAYPAL
  • PaymentMethod.GOOGLE_PAY
  • PaymentMethod.AEROPAY

Return value

Return true to continue, false to block submission for this attempt. Blocking doesn't call onCancel or onError. The callback is suspend, so async validation is supported. The lambda must return a Boolean.

Example implementation

Configure the callback as follows:

onBeforeSubmit = { paymentMethod ->
    Log.d("CheckoutDropIn", "Payment method selected: $paymentMethod")

    // Track analytics
    analytics.track("payment_initiated", mapOf(
        "payment_method" to paymentMethod.toString(),
        "amount" to 25.00
    ))

    // Show confirmation for large amounts
    if (amount > 100) {
        val confirmed = showConfirmationDialog(
            "Confirm payment of $amount USD?"
        )
        if (!confirmed) return@onBeforeSubmit false
    }

    // Check inventory availability (suspend OK)
    val hasStock = checkInventory()
    if (!hasStock) {
        showToast("Some items are no longer available")
        return@onBeforeSubmit false
    }

    true // Proceed with payment
}

Simple validation example:

onBeforeSubmit = { paymentMethod ->
    // Simple synchronous validation
    if (!isValidOrder()) {
        showToast("Please complete all required fields")
        return@onBeforeSubmit false // Payment won't proceed
    }

    true // Payment will proceed
}

onSubmit

This callback is triggered when payment processing begins, after onBeforeSubmit validation passes (when that callback is wired for the method). Use this to show loading indicators and disable UI elements.

For Aeropay, Drop-in always proceeds with the Unity transaction after onSubmit. There's no merchant onPreAuthorisation gate in Drop-in.

You can use it to:

  • Show loading spinners or progress indicators.
  • Disable submit buttons to prevent double-submission.
  • Display "Processing payment..." messages.
  • Update UI to show payment is in progress.
  • Track analytics for payment submission.

Event data

This callback receives the following data:

ParameterDescription
paymentMethod
PaymentMethod
required
The payment method being processed.

Possible values:
  • PaymentMethod.CARD
  • PaymentMethod.PAYPAL
  • PaymentMethod.GOOGLE_PAY
  • PaymentMethod.AEROPAY

Example implementation

Configure the callback as follows:

onSubmit = { paymentMethod ->
    Log.d("CheckoutDropIn", "Processing payment with: $paymentMethod")

    // Show loading overlay
    showLoadingOverlay(true)

    // Disable submit button to prevent double-submission
    disableSubmitButton()

    // Track analytics
    analytics.track("payment_processing", mapOf(
        "payment_method" to paymentMethod.toString()
    ))
}

Complete loading state management. This snippet assumes an Activity or Fragment lifecycleScope. In a Compose screen, use rememberCoroutineScope() as in the complete integration example:

var loadingTimeout: Job? = null

onSubmit = { paymentMethod ->
    // Show loading state
    setLoadingState(true)

    // Set timeout in case payment takes too long
    loadingTimeout = lifecycleScope.launch {
        delay(10000) // 10 seconds
        showWarning("Payment is taking longer than expected. Please wait...")
    }

    // Track start time for performance monitoring
    paymentStartTime = System.currentTimeMillis()
}

onSuccess

This callback is triggered after payment succeeds. It receives the final transaction result from the payment processing system.

You can use it to:

  • Verify payment on your backend.
  • Redirect to success page after verification.
  • Display success messages.
  • Track successful payment analytics.
  • Update stock levels for purchased items.
  • Send order confirmation emails to customers.
  • Clear shopping cart.

Event data

This callback receives the following data:

Event dataDescription
result
DropInSubmitResult
required
The payment processing result from PXP's backend.
result.systemTransactionId
String
required
Unity's system transaction identifier. Use for backend verification.
result.merchantTransactionId
String?
Your unique transaction identifier (optional).
result.authenticationId
String?
3DS authentication identifier when authentication was performed.
result.paymentMethod
PaymentMethod
required
The payment method used.

Possible values:
  • PaymentMethod.CARD
  • PaymentMethod.PAYPAL
  • PaymentMethod.GOOGLE_PAY
  • PaymentMethod.AEROPAY
result.paymentData
DropInPaymentData?
Optional wallet payment data. Google Pay returns DropInPaymentData.Authorisation. Typically null for card, PayPal, and Aeropay.

DropInSubmitResult type:

data class DropInSubmitResult(
    val systemTransactionId: String,
    val merchantTransactionId: String? = null,
    val authenticationId: String? = null,
    val paymentMethod: PaymentMethod,
    val paymentData: DropInPaymentData? = null,
)

sealed class DropInPaymentData {
    data class Authorisation(val data: AuthorisationPaymentData) : DropInPaymentData()
}

Google Pay payment data

When a payment is completed using Google Pay, result.paymentData is typically DropInPaymentData.Authorisation, wrapping AuthorisationPaymentData:

data class AuthorisationPaymentData(
    val email: String? = null,
    val shippingAddress: Map<String, String?>? = null,
    val shippingOption: Map<String, String?>? = null
)

These fields depend on what Drop-in collects:

FieldPopulated when
emailNot populated by Drop-in today. DropInGooglePayConfig does not expose emailRequired, so AuthorisationPaymentData.email is typically null.
shippingAddressgooglePay.shippingAddressRequired is true.
shippingOptionglobal.shippingOptions are configured and the user selects one.

Example handling payment data:

onSuccess = { result ->
    Log.d("Checkout", "Payment successful: ${result.systemTransactionId}")
    Log.d("Checkout", "Payment method: ${result.paymentMethod}")

    when (val paymentData = result.paymentData) {
        is DropInPaymentData.Authorisation -> {
            // email is typically null in Drop-in today
            paymentData.data.email?.let { email ->
                Log.d("Checkout", "Customer email: $email")
            }

            paymentData.data.shippingAddress?.let { address ->
                Log.d("Checkout", "Shipping address: $address")
            }

            paymentData.data.shippingOption?.let { option ->
                Log.d("Checkout", "Shipping option: $option")
            }
        }
        else -> {
            // Card, PayPal, and Aeropay typically return null paymentData
        }
    }

    // CRITICAL: Verify on backend before fulfilling
    verifyPaymentOnBackend(result)
}

The onSuccess callback is a frontend event and can be manipulated by malicious users. Never fulfil orders based solely on this callback. Always verify payments on your backend using Unity webhooks or the Get transaction details API before fulfilling orders.

Example implementation

Configure the callback as follows. The snippet assumes an Activity or Fragment lifecycleScope. In a Compose screen, use rememberCoroutineScope() as in the complete integration example:

onSuccess = { result ->
    Log.d("CheckoutDropIn", "Payment successful (frontend notification only)")
    Log.d("CheckoutDropIn", "System transaction ID: ${result.systemTransactionId}")
    Log.d("CheckoutDropIn", "Merchant transaction ID: ${result.merchantTransactionId}")
    Log.d("CheckoutDropIn", "Payment method: ${result.paymentMethod}")

    // Clear loading timeout if set
    loadingTimeout?.cancel()

    // Hide loading overlay
    setLoadingState(false)

    // Track analytics
    val processingTime = System.currentTimeMillis() - paymentStartTime
    analytics.track("payment_success_frontend", mapOf(
        "system_transaction_id" to result.systemTransactionId,
        "merchant_transaction_id" to result.merchantTransactionId,
        "payment_method" to result.paymentMethod.toString(),
        "processing_time" to processingTime
    ))

    // Show temporary success message
    showMessage("Payment received! Verifying...", MessageType.SUCCESS)

    // CRITICAL: Verify payment on backend before fulfilling order
    lifecycleScope.launch {
        try {
            val verification = verifyPaymentOnBackend(
                systemTransactionId = result.systemTransactionId,
                merchantTransactionId = result.merchantTransactionId
            )

            if (verification.success) {
                // Payment verified on backend - safe to proceed
                Log.d("CheckoutDropIn", "Payment verified on backend: ${verification.orderId}")

                // Track backend verification success
                analytics.track("payment_verified", mapOf(
                    "order_id" to verification.orderId,
                    "system_transaction_id" to result.systemTransactionId
                ))

                // Clear cart
                clearShoppingCart()

                // Navigate to success page
                navigateToOrderConfirmation(verification.orderId)
            } else {
                // Verification failed
                Log.e("CheckoutDropIn", "Backend verification failed: ${verification.error}")

                analytics.track("payment_verification_failed", mapOf(
                    "system_transaction_id" to result.systemTransactionId,
                    "error" to verification.error
                ))

                showError(
                    "Payment verification failed. Please contact support with " +
                    "transaction ID: ${result.merchantTransactionId}"
                )
            }
        } catch (e: Exception) {
            // Network or server error during verification
            Log.e("CheckoutDropIn", "Failed to verify payment", e)

            analytics.track("payment_verification_error", mapOf(
                "system_transaction_id" to result.systemTransactionId,
                "error" to e.message
            ))

            // Show error but don't clear cart (webhook may still process it)
            showError(
                "Unable to verify payment. Your payment may still be processing. " +
                "Please check your email for confirmation or contact support with " +
                "transaction ID: ${result.merchantTransactionId}"
            )
        }
    }
}

onError

This callback is triggered when an error occurs during the payment process. paymentMethod is null for initialisation or cross-method errors.

You can use it to:

  • Display user-friendly error messages.
  • Log errors for debugging and monitoring.
  • Track failed payment analytics.
  • Offer alternative payment methods.
  • Provide retry options.
  • Hide loading indicators.
  • Re-enable form controls.

Event data

This callback receives the following data:

ParameterDescription
paymentMethod
PaymentMethod?
The payment method associated with the failure, or null for initialisation or cross-method errors.
error
BaseSdkException
required
The error object containing details about what went wrong.
error.message
String
required
A human-readable error message.
error.errorCode
String
required
SDK error code in format SDK#### (for example 'SDK1113' for authentication failed, 'SDK0550' for network error via SdkErrorCodes.NETWORK_ERROR). Use this for programmatic error handling.
error.details
Any?
Optional additional error details.

BaseSdkException type:

open class BaseSdkException(
    message: String,
    cause: Throwable? = null,
    val errorCode: String,
    open val details: Any? = null,
) : Exception(message, cause)

Common error scenarios

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

ScenarioDetection approachUser action
Card declinederror.message contains "declined" or specific provider messagesTry a different card.
Insufficient fundserror.message contains "insufficient funds"Use a different payment method.
Expired carderror.message contains "expired"Use a different card.
Invalid CVVerror.message contains "CVV" or "security code"Check security code.
3DS authentication failederror.errorCode == "SDK1113" or error.message contains "Authentication failed"Try again or use different card.
3DS timeouterror.message contains "timeout"Check connection and retry.
User cancelled 3DSerror.message contains "cancel"Retry payment.
PayPal errorerror.errorCode == "SDK1116" or payment method is PayPalTry again or use different method.
Aeropay failed to loaderror.errorCode == "SDK1125" (setup failures may also show as SDK0113 or SDK0115); paymentMethod is often PaymentMethod.AEROPAYCheck session payByBanks.aeropay, USD and Ecom, and aeropayDropInIntent. See Aeropay.
Aeropay payment failederror.errorCode == "SDK1126" or other payment-flow codes such as SDK1302 with PaymentMethod.AEROPAYTry again or use a different method. See Aeropay.
Invalid Aeropay consumer data at createerror.errorCode == "SDK1300"Fix non-empty invalid fields on onGetShopper, or set methodConfig.aeropay.userId.
Session expirederror.message contains "Session has expired" (prefer this over matching any message containing "session")Refresh page and retry.
Network errorerror.errorCode == "SDK0550" (SdkErrorCodes.NETWORK_ERROR), or error.errorCode == "SDK0500" only when the message is network-related (SDK0500 is also used for invalid transaction amount)Check connection and retry.
Configuration errorerror.errorCode starts with "SDK01" or "SDK02"Contact support.

Example implementation

Configure the callback as follows:

import com.pxp.checkout.checkoutdropin.types.PaymentMethod
import com.pxp.checkout.exceptions.BaseSdkException
import com.pxp.checkout.exceptions.SdkErrorCodes
import android.util.Log

onError = { paymentMethod: PaymentMethod?, error: BaseSdkException ->
    Log.e(
        "CheckoutDropIn",
        "Payment failed [${paymentMethod?.value}]: ${error.errorCode}: ${error.message}"
    )

    // Clear loading timeout if set
    loadingTimeout?.cancel()

    // Hide loading overlay
    setLoadingState(false)

    // Re-enable submit button
    enableSubmitButton()

    // Track error analytics
    analytics.track("payment_failed", mapOf(
        "payment_method" to paymentMethod?.value,
        "error_code" to error.errorCode,
        "error_message" to error.message
    ))

    // Log error for monitoring
    logErrorToMonitoring(
        category = "payment_error",
        code = error.errorCode,
        message = error.message,
        userAgent = Build.MODEL
    )

    // Show user-friendly error message based on error code and message
    val userMessage = when {
        // Check by SDK error code
        error.errorCode == SdkErrorCodes.NETWORK_ERROR ||
            (error.errorCode == "SDK0500" && error.message?.contains("network", ignoreCase = true) == true) ->
            "Network connection issue. Please check your internet connection and try again."
        error.errorCode == "SDK1113" ->
            "Authentication failed. Please try again or use a different payment method."
        error.errorCode == "SDK1115" -> {
            // Card payment failed - check message for specifics
            when {
                error.message?.contains("declined", ignoreCase = true) == true ->
                    "Your card was declined. Please try a different card or contact your bank for more information."
                error.message?.contains("insufficient funds", ignoreCase = true) == true ->
                    "Insufficient funds. Please use a different payment method."
                error.message?.contains("expired", ignoreCase = true) == true ->
                    "This card has expired. Please use a different card."
                error.message?.contains("cvv", ignoreCase = true) == true ||
                error.message?.contains("security code", ignoreCase = true) == true ->
                    "Invalid security code. Please check the CVV on the back of your card and try again."
                else ->
                    "Card payment failed. Please check your details and try again."
            }
        }
        error.errorCode == "SDK1116" ->
            "PayPal payment failed. Please try again or use a different payment method."
        error.errorCode == "SDK1117" ->
            "Google Pay payment failed. Please try again or use a different payment method."
        error.errorCode == "SDK1125" ->
            "Aeropay could not be loaded. Check session Aeropay credentials and intent."
        error.errorCode == "SDK1300" ->
            "Aeropay could not start. Check shopper email/phone or set methodConfig.aeropay.userId."
        error.errorCode == "SDK1126" ->
            "Aeropay payment could not be completed. Please try again or use a different method."
        error.message?.contains("timeout", ignoreCase = true) == true ->
            "Request timed out. Please check your internet connection and try again."
        error.message?.contains("Session has expired", ignoreCase = true) == true ->
            "Your payment session has expired. Please refresh the page and try again."
        else -> error.message
    }

    showErrorMessage(userMessage)
}

Error handling with retry logic:

var retryCount = 0
val MAX_RETRIES = 3

onError = { paymentMethod, error ->
    // Check if error is retryable (network issues, timeouts)
    val isNetworkError = error.errorCode == SdkErrorCodes.NETWORK_ERROR || // "SDK0550"
        (error.errorCode == "SDK0500" && error.message?.contains("network", ignoreCase = true) == true)
    val isTimeout = error.message?.contains("timeout", ignoreCase = true) == true
    val isRetryable = isNetworkError || isTimeout

    if (isRetryable && retryCount < MAX_RETRIES) {
        retryCount++

        Log.d("CheckoutDropIn", "Retryable error, attempt $retryCount/$MAX_RETRIES")

        showMessage(
            "Connection issue. Attempt $retryCount/$MAX_RETRIES. Please try your payment again.",
            MessageType.WARNING
        )
    } else {
        retryCount = 0 // Reset retry count

        if (isRetryable) {
            showMessage(
                "Unable to process payment after multiple attempts. " +
                "Please check your connection and try again later.",
                MessageType.ERROR
            )
        } else {
            showMessage(
                "Payment failed: ${error.message}",
                MessageType.ERROR
            )
        }

        // Show alternative options for persistent failures
        showAlternativePaymentMethods()
    }
}

onGetConsent

onGetConsent returns whether the shopper has consented for that payment method when Drop-in has no visible consent component for it. Return true to send consent as granted, false otherwise. It doesn't show or hide a checkbox.

onGetConsent applies to card, PayPal, and Google Pay only. It doesn't apply to Aeropay.

For cards, Drop-in only uses this callback for new-card tokenisation when site storeCardConsent is Ask and the consent checkbox isn't shown. When the site is ConsentAlreadyObtained, Drop-in stores the card without calling onGetConsent. When the site is DontAsk, Drop-in doesn't store the card through this consent flow. See Cards — Store-card consent.

You can use it to:

  • Grant or withhold consent for specific payment methods when no consent UI is shown.
  • Comply with regulations requiring explicit consent for storing payment data.
  • Supply consent for card tokenisation when the card consent checkbox isn't rendered (Ask without a checkbox).
  • Return different consent values for guest vs registered shoppers.

Event data

This callback receives the following data:

ParameterDescription
paymentMethod
PaymentMethod
required
The payment method being evaluated.

Possible values:
  • PaymentMethod.CARD
  • PaymentMethod.PAYPAL
  • PaymentMethod.GOOGLE_PAY
Not used for PaymentMethod.AEROPAY.

Return value

The callback returns:

  • true: Send consent as granted for this payment method.
  • false: Send consent as not granted for this payment method.

Example implementation

Configure the callback as follows:

methodConfig = DropInMethodConfig(
    global = DropInGlobalConfig(
        // Grant consent for cards and PayPal when no consent UI is shown
        onGetConsent = { paymentMethod ->
            paymentMethod == PaymentMethod.CARD || paymentMethod == PaymentMethod.PAYPAL
        }
    )
)

Dynamic consent based on user type:

methodConfig = DropInMethodConfig(
    global = DropInGlobalConfig(
        onGetConsent = { paymentMethod ->
            // Only grant consent for logged-in users
            val isLoggedIn = checkUserLoginStatus()

            if (!isLoggedIn) {
                return@onGetConsent false // Guests: consent not granted
            }

            // Logged-in: grant consent for cards only
            paymentMethod == PaymentMethod.CARD
        }
    )
)

onCancel

This callback fires when the user cancels a payment. This allows you to track cancellations, update UI, or perform cleanup operations.

DropInGlobalConfig.onCancel is wired to PayPal, Google Pay, and Aeropay cancel handlers. Card and 3D Secure cancellation or failure routes through onError, not onCancel.

You can use it to:

  • Track payment abandonment analytics.
  • Show user-friendly cancellation message.
  • Re-enable form fields or buttons.
  • Clear loading indicators.
  • Offer alternative payment methods.
  • Send abandonment emails for cart recovery.

Event data

This callback receives the following data:

ParameterDescription
paymentMethod
PaymentMethod
required
The payment method that was cancelled. Includes PaymentMethod.AEROPAY when the Aeropay popup is closed.
data
Any?
Additional cancellation data (varies by payment method). For Aeropay, the payload is null.

This callback is triggered when:

  • User closes PayPal popup without completing payment.
  • User cancels Google Pay payment sheet.
  • User closes the Aeropay popup without completing payment.

Card or 3DS failures and user abandonment use onError.

Example implementation

Configure the callback as follows:

methodConfig = DropInMethodConfig(
    global = DropInGlobalConfig(
        onCancel = { paymentMethod, data ->
            Log.d("CheckoutDropIn", "Payment cancelled: $paymentMethod")

            // Track analytics
            analytics.track("payment_cancelled", mapOf(
                "method" to paymentMethod.toString(),
                "timestamp" to System.currentTimeMillis()
            ))

            // Hide loading spinner
            setIsProcessing(false)

            // Re-enable checkout button
            setCheckoutButtonDisabled(false)

            // Show cancellation message
            showNotification(
                type = NotificationType.INFO,
                message = "$paymentMethod payment was cancelled. " +
                         "Please try again or choose a different payment method."
            )

            // Reset payment form
            resetPaymentForm()
        }
    )
)

Callback execution order

Understanding the callback flow helps you implement proper payment handling:

  1. onGetShopper: optional initial setup

    • Called during create() (for example inside LaunchedEffect after initialize) when Drop-in loads shopper data for card-on-file and Aeropay validation—not during CheckoutDropIn.initialize() itself
    • When provided with a non-empty id and showCOF is enabled, enables card-on-file token lookup. The section header and COF panel can appear while tokens are loading or when cardTokens is non-empty. The token list appears only when cardTokens is non-empty.
  2. onGetShippingAddress: optional address resolution

    • Used for billing prefill and PayPal SET_PROVIDED_ADDRESS flows when provided
  3. onBeforeSubmit: validation phase

    • User selects payment method and taps submit (card, PayPal, Google Pay, or Aeropay)
    • Return true to proceed, false to block submission without calling onCancel or onError
    • For Aeropay, returning false prevents the popup from opening
    • Perform business validation and fraud checks (suspend or async work is supported)
  4. onSubmit: processing starts (if onBeforeSubmit returns true, when wired)

    • Show loading indicators
    • Disable form fields
    • Track analytics
    • For Aeropay, Drop-in always proceeds after onSubmit (no merchant onPreAuthorisation gate)
  5. onSuccess or onError: payment completes

    • onSuccess: payment succeeded (verify on backend before fulfilling)
    • onError: payment failed (show error message and offer alternatives). Card or 3DS cancellation also uses onError
  6. onCancel: user cancels (optional)

    • Triggered for PayPal, Google Pay, and Aeropay cancel flows
    • Update UI and track analytics

For Aeropay-specific callback behaviour, shopper data, and methodConfig.aeropay, see Aeropay.

Complete integration example

Here's a complete example showing all callbacks working together. Initialise Drop-in outside rendering, call create() from a coroutine, and render with CheckoutDropIn.Content():

import android.util.Log
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.*
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import com.pxp.checkout.checkoutdropin.CheckoutDropIn
import com.pxp.checkout.checkoutdropin.types.*
import com.pxp.checkout.checkoutdropin.types.methodconfigs.*
import com.pxp.checkout.exceptions.BaseSdkException
import com.pxp.checkout.exceptions.SdkErrorCodes
import com.pxp.checkout.models.CardIntentType
import com.pxp.checkout.models.SessionConfig
import com.pxp.checkout.models.ShippingAddress
import com.pxp.checkout.models.*
import com.pxp.checkout.services.models.transaction.Shopper
import java.time.Instant
import java.util.UUID
import kotlinx.coroutines.*

var loadingTimeout: Job? = null
var retryCount = 0
val MAX_RETRIES = 3

@Composable
fun CheckoutWithEventsScreen() {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    var sessionConfig by remember { mutableStateOf<SessionConfig?>(null) }

    LaunchedEffect(Unit) {
        sessionConfig = fetchSessionFromBackend()
    }

    val checkoutDropIn = remember(sessionConfig) {
        sessionConfig?.let { session ->
            CheckoutDropIn.initialize(
                context = context,
                config = CheckoutDropInConfig(
                    environment = Environment.LIVE,
                    session = session,
                ownerType = "MerchantGroup",
                ownerId = "MERCHANT-1",
                transactionData = DropInTransactionData(
                    amount = 25.0,
                    currency = "USD",
                    entryType = EntryType.Ecom,
                    intent = DropInTransactionIntentData(
                        card = CardIntentType.Authorisation,
                        paypalDropInIntent = DropInPayPalIntentType.Purchase,
                        aeropayDropInIntent = DropInAeropayIntentType.Authorisation
                    ),
                    merchant = "MERCHANT-1",
                    merchantTransactionId = UUID.randomUUID().toString(),
                    merchantTransactionDate = { Instant.now().toString() }
                ),
                kountDisabled = false, // OPTIONAL: Set to true to disable Kount fraud detection

                onGetShopper = {
                    val customerId = getCurrentCustomerId()
                    Shopper(
                        id = customerId ?: "guest-${UUID.randomUUID()}"
                    )
                },

                onGetShippingAddress = {
                    ShippingAddress(
                        addressLine1 = shippingLine1,
                        city = shippingCity,
                        postalCode = shippingPostalCode,
                        countryCode = shippingCountryCode
                    )
                },

                // Before payment submission (suspend)
                onBeforeSubmit = { paymentMethod ->
                    Log.d("CheckoutDropIn", "Payment method selected: $paymentMethod")

                    analytics.track("payment_initiated", mapOf(
                        "payment_method" to paymentMethod.toString(),
                        "amount" to 25.00
                    ))

                    if (25.00 > 100) {
                        val confirmed = showConfirmation(
                            "Confirm payment of 25.00 USD?"
                        )
                        if (!confirmed) return@onBeforeSubmit false
                    }

                    val hasStock = checkInventory()
                    if (!hasStock) {
                        showToast("Some items are no longer available")
                        return@onBeforeSubmit false
                    }

                    true
                },

                onSubmit = { paymentMethod ->
                    Log.d("CheckoutDropIn", "Processing payment...")

                    showLoadingOverlay(true)
                    disableSubmitButton()

                    loadingTimeout = scope.launch {
                        delay(10000)
                        showMessage("Payment is taking longer than expected...", MessageType.WARNING)
                    }

                    paymentStartTime = System.currentTimeMillis()

                    analytics.track("payment_processing", mapOf(
                        "payment_method" to paymentMethod.toString()
                    ))
                },

                onSuccess = { result ->
                    Log.d("CheckoutDropIn", "Payment successful (verifying on backend...)")

                    loadingTimeout?.cancel()

                    val processingTime = System.currentTimeMillis() - paymentStartTime
                    Log.d("CheckoutDropIn", "Payment processed in ${processingTime}ms")

                    analytics.track("payment_success_frontend", mapOf(
                        "system_transaction_id" to result.systemTransactionId,
                        "payment_method" to result.paymentMethod.toString(),
                        "processing_time" to processingTime
                    ))

                    showMessage("Payment received! Verifying...", MessageType.SUCCESS)

                    scope.launch {
                        try {
                            val verified = verifyPaymentOnBackend(
                                systemTransactionId = result.systemTransactionId,
                                merchantTransactionId = result.merchantTransactionId
                            )

                            if (verified.success) {
                                analytics.track("payment_verified", mapOf(
                                    "order_id" to verified.orderId
                                ))

                                clearCart()
                                navigateToSuccess(verified.orderId)
                            } else {
                                throw Exception(verified.error ?: "Verification failed")
                            }
                        } catch (e: Exception) {
                            Log.e("CheckoutDropIn", "Verification error", e)
                            showLoadingOverlay(false)
                            showError(
                                "Payment verification failed. Please contact support with " +
                                "transaction ID: ${result.merchantTransactionId}"
                            )
                        }
                    }
                },

                onError = { paymentMethod: PaymentMethod?, error: BaseSdkException ->
                    Log.e(
                        "CheckoutDropIn",
                        "Payment failed [${paymentMethod?.value}]: ${error.errorCode}: ${error.message}"
                    )

                    loadingTimeout?.cancel()
                    showLoadingOverlay(false)
                    enableSubmitButton()

                    analytics.track("payment_failed", mapOf(
                        "payment_method" to paymentMethod?.value,
                        "error_code" to error.errorCode,
                        "error_message" to error.message
                    ))

                    logError(error)

                    val isNetworkError =
                        error.errorCode == SdkErrorCodes.NETWORK_ERROR ||
                        (error.errorCode == "SDK0500" &&
                            error.message?.contains("network", ignoreCase = true) == true)
                    val isTimeout = error.message?.contains("timeout", ignoreCase = true) == true
                    if ((isNetworkError || isTimeout) && retryCount < MAX_RETRIES) {
                        retryCount++
                        showMessage(
                            "Connection issue (attempt $retryCount/$MAX_RETRIES). Please try again.",
                            MessageType.WARNING
                        )
                        return@onError
                    }

                    retryCount = 0

                    val userMessage = when {
                        error.errorCode == "SDK1113" ->
                            "3D Secure authentication failed."
                        error.errorCode == "SDK1115" ->
                            "Card payment failed."
                        error.errorCode == "SDK1116" ->
                            "PayPal payment failed."
                        error.errorCode == "SDK1125" ->
                            "Aeropay could not be loaded."
                        error.errorCode == "SDK1300" ->
                            "Aeropay could not start. Check shopper data or set methodConfig.aeropay.userId."
                        error.errorCode == "SDK1126" ->
                            "Aeropay payment could not be completed."
                        error.message?.contains("Session has expired", ignoreCase = true) == true ->
                            "Your payment session has expired. Please refresh and try again."
                        error.message?.contains("declined", ignoreCase = true) == true ->
                            "Card declined. Please try a different card."
                        error.message?.contains("insufficient funds", ignoreCase = true) == true ->
                            "Insufficient funds. Please use a different payment method."
                        error.message?.contains("expired", ignoreCase = true) == true ->
                            "This card has expired."
                        error.message?.contains("cvv", ignoreCase = true) == true ->
                            "Invalid security code."
                        else -> "Payment failed. Please try again."
                    }

                    showErrorMessage(userMessage)

                    if (error.errorCode == "SDK1115" ||
                        error.message?.contains("card", ignoreCase = true) == true) {
                        showAlternativePaymentMethods()
                    }
                },

                methodConfig = DropInMethodConfig(
                    global = DropInGlobalConfig(
                        onGetConsent = { paymentMethod ->
                            // Grant consent for cards and PayPal when no consent UI is shown
                            paymentMethod == PaymentMethod.CARD ||
                            paymentMethod == PaymentMethod.PAYPAL
                        },

                        onCancel = { paymentMethod, data ->
                            Log.d("CheckoutDropIn", "Payment cancelled: $paymentMethod")

                            loadingTimeout?.cancel()
                            showLoadingOverlay(false)
                            enableSubmitButton()

                            analytics.track("payment_cancelled", mapOf(
                                "payment_method" to paymentMethod.toString()
                            ))

                            showMessage("Payment was cancelled. Please try again.", MessageType.INFO)
                        }
                    )
                )
            )
        )
        }
    }

    LaunchedEffect(checkoutDropIn) {
        checkoutDropIn?.create()
    }

    checkoutDropIn?.Content(modifier = Modifier.fillMaxWidth())
}