Implement callbacks to customise your Drop-in payment flow.
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.
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.
This callback receives no parameters and must return a Shopper object (or null).
The callback returns:
| Property | Description |
|---|---|
idString 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. |
firstNameString? | Shopper first name. Used by Aeropay for consumer data when methodConfig.aeropay.userId isn't set. |
lastNameString? | Shopper last name. Used by Aeropay for consumer data when userId isn't set. |
emailString? | Shopper email. Used by Aeropay for consumer data when userId isn't set. |
phoneNumberString? | 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.
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.
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.
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.
This callback receives the following data:
| Parameter | Description |
|---|---|
paymentMethodPaymentMethod required | The selected payment method. Possible values:
|
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.
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
}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.
This callback receives the following data:
| Parameter | Description |
|---|---|
paymentMethodPaymentMethod required | The payment method being processed. Possible values:
|
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()
}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.
This callback receives the following data:
| Event data | Description |
|---|---|
resultDropInSubmitResult required | The payment processing result from PXP's backend. |
result.systemTransactionIdString required | Unity's system transaction identifier. Use for backend verification. |
result.merchantTransactionIdString? | Your unique transaction identifier (optional). |
result.authenticationIdString? | 3DS authentication identifier when authentication was performed. |
result.paymentMethodPaymentMethod required | The payment method used. Possible values:
|
result.paymentDataDropInPaymentData? | 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()
}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:
| Field | Populated when |
|---|---|
email | Not populated by Drop-in today. DropInGooglePayConfig does not expose emailRequired, so AuthorisationPaymentData.email is typically null. |
shippingAddress | googlePay.shippingAddressRequired is true. |
shippingOption | global.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.
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}"
)
}
}
}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.
This callback receives the following data:
| Parameter | Description |
|---|---|
paymentMethodPaymentMethod? | The payment method associated with the failure, or null for initialisation or cross-method errors. |
errorBaseSdkException required | The error object containing details about what went wrong. |
error.messageString required | A human-readable error message. |
error.errorCodeString 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.detailsAny? | 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)The following table shows common error scenarios and how to detect and respond to them:
| Scenario | Detection approach | User action |
|---|---|---|
| Card declined | error.message contains "declined" or specific provider messages | Try a different card. |
| Insufficient funds | error.message contains "insufficient funds" | Use a different payment method. |
| Expired card | error.message contains "expired" | Use a different card. |
| Invalid CVV | error.message contains "CVV" or "security code" | Check security code. |
| 3DS authentication failed | error.errorCode == "SDK1113" or error.message contains "Authentication failed" | Try again or use different card. |
| 3DS timeout | error.message contains "timeout" | Check connection and retry. |
| User cancelled 3DS | error.message contains "cancel" | Retry payment. |
| PayPal error | error.errorCode == "SDK1116" or payment method is PayPal | Try again or use different method. |
| Aeropay failed to load | error.errorCode == "SDK1125" (setup failures may also show as SDK0113 or SDK0115); paymentMethod is often PaymentMethod.AEROPAY | Check session payByBanks.aeropay, USD and Ecom, and aeropayDropInIntent. See Aeropay. |
| Aeropay payment failed | error.errorCode == "SDK1126" or other payment-flow codes such as SDK1302 with PaymentMethod.AEROPAY | Try again or use a different method. See Aeropay. |
| Invalid Aeropay consumer data at create | error.errorCode == "SDK1300" | Fix non-empty invalid fields on onGetShopper, or set methodConfig.aeropay.userId. |
| Session expired | error.message contains "Session has expired" (prefer this over matching any message containing "session") | Refresh page and retry. |
| Network error | error.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 error | error.errorCode starts with "SDK01" or "SDK02" | Contact support. |
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 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 (
Askwithout a checkbox). - Return different consent values for guest vs registered shoppers.
This callback receives the following data:
| Parameter | Description |
|---|---|
paymentMethodPaymentMethod required | The payment method being evaluated. Possible values:
PaymentMethod.AEROPAY. |
The callback returns:
true: Send consent as granted for this payment method.false: Send consent as not granted for this payment method.
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
}
)
)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.
This callback receives the following data:
| Parameter | Description |
|---|---|
paymentMethodPaymentMethod required | The payment method that was cancelled. Includes PaymentMethod.AEROPAY when the Aeropay popup is closed. |
dataAny? | 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.
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()
}
)
)Understanding the callback flow helps you implement proper payment handling:
onGetShopper: optional initial setup- Called during
create()(for example insideLaunchedEffectafterinitialize) when Drop-in loads shopper data for card-on-file and Aeropay validation—not duringCheckoutDropIn.initialize()itself - When provided with a non-empty
idandshowCOFis enabled, enables card-on-file token lookup. The section header and COF panel can appear while tokens are loading or whencardTokensis non-empty. The token list appears only whencardTokensis non-empty.
- Called during
onGetShippingAddress: optional address resolution- Used for billing prefill and PayPal
SET_PROVIDED_ADDRESSflows when provided
- Used for billing prefill and PayPal
onBeforeSubmit: validation phase- User selects payment method and taps submit (card, PayPal, Google Pay, or Aeropay)
- Return
trueto proceed,falseto block submission without callingonCanceloronError - For Aeropay, returning
falseprevents the popup from opening - Perform business validation and fraud checks (suspend or async work is supported)
onSubmit: processing starts (ifonBeforeSubmitreturnstrue, when wired)- Show loading indicators
- Disable form fields
- Track analytics
- For Aeropay, Drop-in always proceeds after
onSubmit(no merchantonPreAuthorisationgate)
onSuccessoronError: payment completesonSuccess: payment succeeded (verify on backend before fulfilling)onError: payment failed (show error message and offer alternatives). Card or 3DS cancellation also usesonError
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.
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())
}