Skip to content

Events

Implement callbacks to customise your PayPal payout flow for iOS.

Overview

The PayPal payout submission component emits events throughout the payout lifecycle. You can use these to implement callback functions, which allow you to inject your own business logic and user experience customisations into the payout flow at critical moments. They ensure that while the SDK handles the complex technical aspects of payout processing, you retain full control over the user experience and can seamlessly integrate payouts into your broader business workflows and systems.

The PayoutAmountComponent and PayPalPayoutReceiverComponent are display-only components and don't emit events.

Callbacks enable you to:

  • Validate business rules before payouts execute.
  • Implement custom approval flows for payout authorisation.
  • Display custom error, failure, or success messages.
  • Tailor user interfaces to match your brand's look and feel.
  • Integrate with your own systems for compliance or audit logging.
  • Control exactly how your recipients experience both successful and failed payouts.
  • Track user interactions and payout status for analytics.

All events are optional and can be mixed and matched based on your business needs.

Supported events

The PayPal payout submission component supports the following events:

  • onClick
  • onPrePayoutSubmit
  • onPostPayout
  • onError

PayoutSubmissionComponentConfig also has an onCancel property, but the SDK doesn't currently invoke it. To cancel a payout, return nil or PrePayoutSubmitResult(isApproved: false) from onPrePayoutSubmit.

Callbacks

The following sections describe each callback in detail.

onClick

This callback is triggered when the user taps the payout button, before the payout executes.

When proceedPayoutWithSdk is false (backend-managed), onClick is the only callback that runs. Use it to notify your backend that the user requested a payout, so that your backend can execute it.

You can use it to:

  • Notify your backend to execute the payout (backend-managed mode).
  • Trigger analytics tracking for user engagement.
  • Show loading indicators or status messages.
  • Log user interactions for monitoring.

Event data

This callback receives no parameters.

Example implementation

The following example tracks the click, shows a loading state, and runs a pre-flight check.

let config = PayoutSubmissionComponentConfig(
    submitText: "Withdraw to PayPal",
    onClick: {
        print("PayPal payout button clicked")
        
        // Track button click
        Analytics.track("paypal_payout_clicked", properties: [
            "timestamp": Date().timeIntervalSince1970,
            "payoutAmount": getCurrentPayoutAmount()
        ])
        
        // Show loading state
        showLoadingIndicator()
        
        // Perform pre-flight checks
        validateUserEligibleForPayout()
    }
)

onPrePayoutSubmit

This callback is triggered to allow merchant approval before the payout executes. This is where you implement your business logic to decide whether to proceed with the payout.

This callback is only triggered when proceedPayoutWithSdk: true in your PayPal configuration. If set to false, payouts are managed entirely by your backend. When it's true, the SDK executes the payout only if you provide this callback and it returns PrePayoutSubmitResult(isApproved: true).

You can use it to:

  • Show confirmation dialogs to verify payout details.
  • Implement compliance checks or fraud prevention.
  • Allow users to review payout amount and recipient.
  • Apply business rules before authorising payout.
  • Provide an opportunity to cancel the payout.

Event data

This callback receives no parameters.

Return value

Returns an optional PrePayoutSubmitResult object:

PropertyDescription
isApproved
Bool
required
Whether the merchant or user approves the payout. Return false, or return nil from the callback, to cancel.

PrePayoutSubmitResult only has the isApproved property. The PayoutSubmissionComponent uses the payer ID already configured in PayPalConfig.payout.paypalWallet.payerId.

Example implementation

The following example shows an approval dialog and approves the payout only when the user confirms.

let config = PayoutSubmissionComponentConfig(
    submitText: "Withdraw to PayPal",
    onPrePayoutSubmit: {
        print("Pre-payout approval requested")
        
        // Show approval dialog and wait for user response
        let approved = await showPayoutApprovalDialog(
            amount: getCurrentPayoutAmount(),
            currency: "USD",
            recipientEmail: getCurrentPayPalEmail()
        )
        
        // If user cancelled
        guard approved else {
            Analytics.track("payout_approval_rejected")
            return nil  // or return result with isApproved: false
        }
        
        // User approved - proceed with payout
        Analytics.track("payout_approval_granted", properties: [
            "amount": getCurrentPayoutAmount(),
            "currency": "USD",
            "timestamp": Date().timeIntervalSince1970
        ])
        
        // Return approval
        return PrePayoutSubmitResult(isApproved: true)
    }
)

Example with async confirmation dialog

The following example uses a Swift continuation to wait for the user's response to a SwiftUI alert.

// State for managing approval flow
@State private var showApprovalAlert = false
@State private var pendingApprovalContinuation: CheckedContinuation<PrePayoutSubmitResult?, Never>?

let config = PayoutSubmissionComponentConfig(
    submitText: "Withdraw to PayPal",
    onPrePayoutSubmit: { [self] in
        // Show approval dialog and wait for user response
        return await withCheckedContinuation { continuation in
            Task { @MainActor in
                self.pendingApprovalContinuation = continuation
                self.showApprovalAlert = true
            }
        }
    }
)

// In your SwiftUI view
.alert("Confirm Payout", isPresented: $showApprovalAlert) {
    Button("Cancel", role: .cancel) {
        // User rejected
        pendingApprovalContinuation?.resume(returning: nil)
        pendingApprovalContinuation = nil
    }
    Button("Confirm") {
        // User approved
        pendingApprovalContinuation?.resume(returning: 
            PrePayoutSubmitResult(isApproved: true)
        )
        pendingApprovalContinuation = nil
    }
} message: {
    Text("Send $\(payoutAmount) to your PayPal account?")
}

onPostPayout

This callback is triggered after the payout transaction completes successfully. This is where you update your system and notify the user of the successful payout.

You can use it to:

  • Update transaction records in your database.
  • Display success messages to users.
  • Send notifications about completed payouts.
  • Update user balance or pending payout status.
  • Navigate to a success screen.
  • Track successful payout metrics.

Event data

The callback receives a MerchantSubmitResult object with the following properties.

Event dataDescription
result
MerchantSubmitResult
The payout transaction result object.
result.merchantTransactionId
String
Your unique transaction identifier.
result.systemTransactionId
String
The PXP system transaction ID for tracking.

Example implementation

The following example updates your records, notifies the user, and navigates to a success screen.

let config = PayoutSubmissionComponentConfig(
    submitText: "Withdraw to PayPal",
    onPostPayout: { result in
        print("Payout successful!")
        print("Merchant Transaction ID: \(result.merchantTransactionId)")
        print("System Transaction ID: \(result.systemTransactionId)")
        
        // Update payout record in your system
        updatePayoutStatus(
            merchantTxId: result.merchantTransactionId,
            systemTxId: result.systemTransactionId,
            status: "completed",
            completedAt: Date()
        )
        
        // Update user balance
        updateUserBalance(
            userId: currentUser.id,
            amount: getCurrentPayoutAmount(),
            type: "payout_completed"
        )
        
        // Send push notification
        sendPushNotification(
            title: "Payout Complete",
            body: "Your payout of $\(getCurrentPayoutAmount()) has been sent to your PayPal account"
        )
        
        // Track successful payout
        Analytics.track("payout_completed", properties: [
            "merchantTransactionId": result.merchantTransactionId,
            "systemTransactionId": result.systemTransactionId,
            "amount": getCurrentPayoutAmount(),
            "currency": "USD",
            "timestamp": Date().timeIntervalSince1970
        ])
        
        // Navigate to success screen
        navigateToPayoutSuccessScreen(result.merchantTransactionId)
    }
)

onError

This callback is triggered when a payout fails during execution, for example because of a network issue or an error returned by the API.

Validation errors for the payout configuration (e.g., a missing email or payer ID) are thrown by pxpCheckout.create, so catch them with try-catch. They aren't delivered to onError.

You can use it to:

  • Log errors for debugging and monitoring.
  • Display user-friendly error messages.
  • Handle specific error types differently.
  • Implement retry logic for transient errors.
  • Offer alternative payout methods on failure.

Event data

The callback receives an error object with the following properties.

Event dataDescription
error
BaseSdkException
The error object containing details about what went wrong. The initialiser parameter is typed as Error, so cast it to BaseSdkException.
error.errorCode
String
The error code for identifying specific error types.
error.errorMessage
String
A human-readable error message.
error.localizedDescription
String
The localised error description (same as errorMessage).

Payout failures

A failed payout is reported as a PayoutFailedException. Its errorCode and errorMessage contain the code and reason returned by the API, so don't match them against a fixed SDK code. Check for the PayoutFailedException type instead.

For the validation error codes that pxpCheckout.create throws (SDK0803 to SDK0818), see Data validation.

Example implementation

The following example logs the error, hides the loading indicator, and shows a message based on the error type.

let config = PayoutSubmissionComponentConfig(
    submitText: "Withdraw to PayPal",
    onPrePayoutSubmit: {
        let approved = await showPayoutApprovalDialog()
        return approved ? PrePayoutSubmitResult(isApproved: true) : nil
    },
    onError: { error in
        guard let error = error as? BaseSdkException else { return }
        
        print("Payout error: \(error.errorMessage)")
        print("Error code: \(error.errorCode)")
        
        // Log error for debugging
        Crashlytics.crashlytics().log("PayPal payout error: \(error.errorMessage)")
        Crashlytics.crashlytics().record(error: error)
        
        // Hide loading indicator
        hideLoadingIndicator()
        
        // Handle different error types
        let errorMessage: String
        
        switch error {
        case is PayoutFailedException:
            errorMessage = "Payout transaction failed. Please try again or contact support."
            
        default:
            errorMessage = "Payout failed. Please try again or contact support."
        }
        
        // Show error dialog
        showErrorDialog(
            title: "Payout Error",
            message: errorMessage
        )
        
        // Track error metrics
        Analytics.track("payout_error", properties: [
            "errorCode": error.errorCode,
            "errorMessage": error.errorMessage,
            "payoutAmount": getCurrentPayoutAmount(),
            "timestamp": Date().timeIntervalSince1970
        ])
    }
)

Complete example

Here's a complete example with all event callbacks configured:

import SwiftUI
import PXPCheckoutSDK

struct PayoutView: View {
    @State private var pxpCheckout: PxpCheckout?
    @State private var submissionComponent: BaseComponent?
    @State private var showApprovalAlert = false
    @State private var pendingApprovalContinuation: CheckedContinuation<PrePayoutSubmitResult?, Never>?
    
    var body: some View {
        VStack(spacing: 20) {
            Text("Receive Your Payout")
                .font(.headline)
            
            if let component = submissionComponent {
                component.buildContent()
                    .frame(height: 50)
            }
        }
        .padding()
        .alert("Confirm Payout", isPresented: $showApprovalAlert) {
            Button("Cancel", role: .cancel) {
                pendingApprovalContinuation?.resume(returning: nil)
                pendingApprovalContinuation = nil
            }
            Button("Confirm") {
                pendingApprovalContinuation?.resume(returning: 
                    PrePayoutSubmitResult(isApproved: true)
                )
                pendingApprovalContinuation = nil
            }
        } message: {
            Text("Send $100.00 to your PayPal account?")
        }
        .onAppear {
            createPayoutComponent()
        }
    }
    
    private func createPayoutComponent() {
        Task {
            do {
                // Initialise SDK (see Setup for full configuration)
                let checkout = try await initializePxpCheckout()
                
                // Configure payout component with all callbacks
                let config = PayoutSubmissionComponentConfig(
                    submitText: "Withdraw to PayPal",
                    submitAccessibilityLabel: "Withdraw funds to PayPal account",
                    
                    // 1. Button clicked
                    onClick: {
                        print("📱 PayPal payout button clicked")
                        Analytics.track("paypal_payout_clicked")
                    },
                    
                    // 2. Pre-payout approval
                    onPrePayoutSubmit: { [self] in
                        print("💰 Pre-payout approval requested")
                        
                        // Show approval dialog and wait for user response
                        return await withCheckedContinuation { continuation in
                            Task { @MainActor in
                                self.pendingApprovalContinuation = continuation
                                self.showApprovalAlert = true
                            }
                        }
                    },
                    
                    // 3. Payout completed
                    onPostPayout: { result in
                        print("🎉 Payout successful!")
                        print("   Merchant TX ID: \(result.merchantTransactionId)")
                        print("   System TX ID: \(result.systemTransactionId)")
                        
                        // Update payout status
                        updatePayoutStatus(
                            merchantTxId: result.merchantTransactionId,
                            status: "completed"
                        )
                        
                        // Show success message
                        showSuccessMessage("Payout completed!")
                        
                        // Track success
                        Analytics.track("payout_completed", properties: [
                            "merchantTransactionId": result.merchantTransactionId,
                            "systemTransactionId": result.systemTransactionId
                        ])
                    },
                    
                    // 4. Error occurred
                    onError: { error in
                        guard let error = error as? BaseSdkException else { return }
                        print("⚠️ Error occurred:")
                        print("   Code: \(error.errorCode)")
                        print("   Message: \(error.errorMessage)")
                        
                        // Log error
                        logError(error)
                        
                        // Show error dialog
                        showErrorDialog(
                            title: "Payout Error",
                            message: error.errorMessage
                        )
                        
                        // Track error
                        Analytics.track("payout_error", properties: [
                            "errorCode": error.errorCode,
                            "errorMessage": error.errorMessage
                        ])
                    }
                )
                
                // Create component
                let component = try checkout.create(
                    .payoutSubmission,
                    componentConfig: config
                )
                
                await MainActor.run {
                    self.submissionComponent = component
                }
            } catch {
                print("Failed to create payout component: \(error)")
            }
        }
    }
}

Best practices

Error handling

Always implement the onError callback to handle failures gracefully:

config.onError = { error in
    // Log for debugging
    logError(error)
    
    // Show user-friendly message
    showErrorDialog(getUserFriendlyMessage(for: error.errorCode))
    
    // Track for analytics
    trackError(error)
    
    // Offer alternatives
    showAlternativeOptions()
}

Approval flow

For onPrePayoutSubmit, always show clear information to users:

config.onPrePayoutSubmit = {
    // showApprovalDialog returns a Bool
    let approved = await showApprovalDialog(
        title: "Confirm Payout",
        message: "Send $\(amount) to your PayPal account?",
        details: [
            "Amount: $\(amount)",
            "Fee: $\(fee)",
            "Total: $\(total)",
            "PayPal Account: \(email)"
        ]
    )
    
    guard approved else { return nil }
    return PrePayoutSubmitResult(isApproved: true)
}

Analytics tracking

Track key events for monitoring and optimisation:

// Track funnel
onClick: {
    Analytics.track("payout_started")
}

onPostPayout: { _ in
    Analytics.track("payout_completed")
}

// Track failures
onError: { error in
    guard let error = error as? BaseSdkException else { return }
    Analytics.track("payout_error", properties: [
        "errorCode": error.errorCode,
        "stage": determineErrorStage(error)
    ])
}

State management

Maintain clean state throughout the payout flow:

enum PayoutState {
    case idle
    case awaitingApproval
    case processing
    case completed
    case failed
    case cancelled
}

@State private var payoutState: PayoutState = .idle

// Update state in callbacks
onClick: {
    payoutState = .awaitingApproval
}

onPrePayoutSubmit: {
    let approved = await showApprovalDialog()
    guard approved else {
        payoutState = .cancelled
        return nil
    }
    payoutState = .processing
    return PrePayoutSubmitResult(isApproved: true)
}

onPostPayout: { _ in
    payoutState = .completed
}

SDK analytics events

In addition to component-level callbacks, you can receive analytics events from the SDK by configuring the analyticsEvent callback on CheckoutConfig. This provides visibility into SDK-level events for monitoring, debugging, and analytics integration.

Configuration

Configure the analytics callback when initialising the SDK:

let checkoutConfig = CheckoutConfig(
    environment: .test,
    session: sessionData,
    transactionData: transactionData,
    merchantShopperId: "user-123",
    ownerId: "merchant-456",
    paypalConfig: paypalConfig,
    analyticsEvent: { event in
        // Handle analytics events
        print("Analytics event: \(event.eventName)")
        
        // Forward to your analytics service
        Analytics.track(event.eventName, properties: [
            "timestamp": Date().timeIntervalSince1970
        ])
    }
)

BaseAnalyticsEvent

All analytics events inherit from BaseAnalyticsEvent and include the following properties:

PropertyDescription
eventName
String
required
The name of the analytics event.
sessionId
String
required
The session ID associated with the event.
timestamp
Date
required
The timestamp when the event occurred.

Use cases

Use the analytics callback to:

  • Monitor SDK performance: Track initialisation times, component lifecycle events, and error rates.
  • Debug integration issues: Log events during development to understand the SDK flow.
  • Integration with analytics platforms: Forward events to services like Firebase Analytics, Amplitude, or Mixpanel.
  • Audit logging: Record SDK events for compliance and audit purposes.

Example: Comprehensive analytics tracking

The following example logs events during development and forwards them to your analytics and crash reporting services.

let checkoutConfig = CheckoutConfig(
    environment: .test,
    session: sessionData,
    transactionData: transactionData,
    merchantShopperId: "user-123",
    ownerId: "merchant-456",
    paypalConfig: paypalConfig,
    analyticsEvent: { event in
        // Log to console during development
        #if DEBUG
        print("📊 SDK Analytics: \(event.eventName)")
        #endif
        
        // Send to analytics service
        AnalyticsService.shared.track(
            event: event.eventName,
            properties: [
                "sdk_version": "1.0.0",
                "platform": "iOS",
                "environment": "test"
            ]
        )
        
        // Log to crash reporting for debugging
        Crashlytics.crashlytics().log("SDK event: \(event.eventName)")
    }
)