Skip to content

PayPal

Accept PayPal and Pay Later payments with automatic popup handling and one-click vaulting for returning customers.

Overview

PayPal is automatically included in the drop-in when enabled in your session. The drop-in handles all PayPal setup, button rendering, web view interaction, and payment processing automatically.

Key benefits

  • PayPal appears automatically in the drop-in when it's enabled in your session configuration.
  • The drop-in handles all PayPal setup, so you don't need PayPal-specific code.
  • PayPal uses the same onSuccess and onError callbacks as other payment methods for a unified integration.
  • Customers can pay using PayPal or Pay Later financing options.
  • Returning customers can use one-click payments when their PayPal account is saved.
  • Standard PayPal branding is included automatically, ensuring a familiar checkout experience.

How it works

When a customer selects PayPal:

  1. The customer taps "PayPal" in the payment options list. The PayPal web view opens.
  2. The customer logs in to their PayPal account.
  3. The customer approves the payment in the PayPal interface.
  4. The web view closes automatically.
  5. The payment is processed through Unity.
  6. Your onSuccess callback fires.

Configuration

Configure PayPal-specific settings for the PayPal button, checkout flow, and shipping integration.

Configuration properties

The following properties are available for PayPal configuration:

Property Description
fundingSources
List<PaypalFundingSources>?
Which PayPal funding sources to display. Falls back to session configuration if not specified.

Possible values:
  • PaypalFundingSources.PAYPAL
  • PaypalFundingSources.PAYLATER
shippingOption
String?
The selected shipping option value passed to PayPal.
enableOneClickPayment
Boolean?
Enables one-click payment for returning customers who have saved their PayPal account (requires vaulting via onGetShopper).
locale
String?
Locale code for the PayPal button and checkout experience (e.g., "en_US", "fr_FR", "de_DE"). Format is language_COUNTRY.
payeeEmailAddress
String?
The payee email address for the PayPal transaction.
paymentDescription
String?
A description of the payment shown to the customer in PayPal.
useBuiltInChangePreferredPaymentMethod
Boolean?
Uses the built-in preferred payment method change behaviour when supported.
consentComponent
Boolean?
Controls whether to show the consent checkbox for saving the payment method.
shippingPreference
ShippingPreference?
How shipping address is handled in PayPal.

Possible values:
  • ShippingPreference.NO_SHIPPING - No shipping address required (digital goods)
  • ShippingPreference.GET_FROM_FILE - Get address from buyer's PayPal account
  • ShippingPreference.SET_PROVIDED_ADDRESS - Use merchant-provided address
buyerCountry
String?
The buyer's country code as an ISO code (e.g., "GB", "US", "FR").
onShippingAddressChange
(String) -> String?
Called when the PayPal shipping address changes. Return null to accept or a reject response string to reject the change.
onShippingOptionsChange
(String) -> String?
Called when the PayPal shipping option changes. Return null to accept or a reject response string to reject the change.

To display Pay Later as a payment option, ensure PaypalFundingSources.PAYLATER is included in your fundingSources configuration and that Pay Later is enabled for your merchant account in the Unity Portal.

Settings used from global configuration

PayPal inherits the following settings from methodConfig.global:

Property Description
onGetConsent
(paymentMethod: PaymentMethod) -> Boolean
Controls whether to show consent checkbox for PayPal (used for vaulting)
onCancel
(paymentMethod: PaymentMethod, data: Any?) -> Unit
Called when user cancels PayPal payment (closes web view)

Complete example

This example shows a full PayPal configuration with global callbacks, shipping integration, and all PayPal-specific options:

methodConfig = DropInMethodConfig(
    // Global callbacks that apply to PayPal
    global = DropInGlobalConfig(
        // Control consent checkbox for PayPal
        onGetConsent = { paymentMethod ->
            // Show consent checkbox for PayPal to save payment method
            paymentMethod == PaymentMethod.PAYPAL
        },
        
        // Handle PayPal cancellation
        onCancel = { paymentMethod, data ->
            if (paymentMethod == PaymentMethod.PAYPAL) {
                Log.d("Checkout", "PayPal payment cancelled: $data")
                
                // Track analytics
                analytics.trackEvent("paypal_cancelled", mapOf(
                    "timestamp" to System.currentTimeMillis()
                ))
                
                // Update UI
                Toast.makeText(
                    context,
                    "PayPal payment was cancelled. Please try again.",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    ),
    
    paypal = DropInPaypalConfig(
        // Funding sources to display
        fundingSources = listOf(
            PaypalFundingSources.PAYPAL,
            PaypalFundingSources.PAYLATER
        ),
        
        // Enable one-click payment for returning users
        enableOneClickPayment = true,
        
        // Locale for PayPal button and checkout experience
        locale = "en_GB",
        
        // Payee email address
        payeeEmailAddress = "merchant@example.com",
        
        // Payment description shown to buyer
        paymentDescription = "Purchase from Demo Store",
        
        // Buyer's country code
        buyerCountry = "GB",
        
        // Show/hide consent checkbox for saving the payment method
        consentComponent = true,
        
        // Shipping preference
        shippingPreference = ShippingPreference.GET_FROM_FILE // or NO_SHIPPING or SET_PROVIDED_ADDRESS
    )
)

PayPal requirements

PayPal requires the following to function correctly:

  • Android compatibility: Android 8.0 (API level 26) or higher.
  • Internet connection: Active internet connection required for PayPal web view.
  • Customer setup: The customer must have a PayPal account (created during checkout if needed).
  • HTTPS: Your backend endpoints must be served over HTTPS.
  • Unity Portal configuration: PayPal must be enabled and configured in the Unity Portal.
  • Entry type: PayPal only supports entryType: Ecom.

One-click payments require the buyer to have previously authorised your merchant account. Authorisations must be captured within 29 days for PayPal.

Implementation

PayPal works through the standard implementation, with no PayPal-specific code needed:

import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import com.pxp.checkout.checkoutdropin.CheckoutDropIn
import com.pxp.checkout.checkoutdropin.types.CheckoutDropInConfig
import com.pxp.checkout.components.checkoutdropincomponent.CheckoutDropInComponent
import com.pxp.checkout.models.DropInTransactionData
import com.pxp.checkout.models.DropInTransactionIntentData
import com.pxp.checkout.models.DropInPayPalIntentType
import com.pxp.checkout.models.Environment
import com.pxp.checkout.models.EntryType
import com.pxp.checkout.models.IntentType
import com.pxp.checkout.checkoutdropin.types.DropInSubmitResult
import com.pxp.checkout.exceptions.BaseSdkException

@Composable
fun CheckoutScreen() {
    val context = LocalContext.current
    var sessionData by remember { mutableStateOf<SessionData?>(null) }
    var checkoutDropInComponent by remember { mutableStateOf<CheckoutDropInComponent?>(null) }
    var isLoading by remember { mutableStateOf(true) }
    
    // Fetch session from backend (with PayPal enabled)
    LaunchedEffect(Unit) {
        try {
            val response = apiClient.post("/api/create-session") {
                contentType(ContentType.Application.Json)
            }
            
            if (response.status.value == 200) {
                val result = response.body<SessionResponse>()
                if (result.success && result.data != null) {
                    sessionData = result.data
                } else {
                    Log.e("Checkout", "Failed to create session: ${result.error}")
                }
            }
        } catch (e: Exception) {
            Log.e("Checkout", "Error creating session", e)
        } finally {
            isLoading = false
        }
    }
    
    // Initialize Drop-in once session is loaded
    LaunchedEffect(sessionData) {
        sessionData?.let { session ->
            val checkoutDropIn = CheckoutDropIn.initialize(
                context = context,
                config = CheckoutDropInConfig(
                    environment = Environment.TEST,
                    session = session,
                    ownerType = "MerchantGroup",
                    ownerId = "MERCHANT-1",
                    transactionData = DropInTransactionData(
                        currency = "GBP",
                        amount = 99.99,
                        entryType = EntryType.Ecom,
                        intent = DropInTransactionIntentData(
                            card = IntentType.Authorisation,
                            paypalDropInIntent = DropInPayPalIntentType.Purchase  // Choose Purchase or Authorisation
                        ),
                        merchant = "Demo Store",
                        merchantTransactionId = { UUID.randomUUID().toString() },
                        merchantTransactionDate = { Instant.now().toString() }
                    ),
                    onGetShopper = {
                        Shopper(id = "shopper-123")
                    },
                    onSuccess = { result: DropInSubmitResult ->
                        Log.d("Checkout", "PayPal payment successful!")
                        Log.d("Checkout", "System transaction ID: ${result.systemTransactionId}")
                        Log.d("Checkout", "Payment method: ${result.paymentMethod}") // Will be "Paypal"
                        
                        // CRITICAL: Verify on backend
                        coroutineScope.launch {
                            verifyPaymentOnBackend(result)
                        }
                    },
                    onError = { error: BaseSdkException ->
                        Log.e("Checkout", "PayPal payment failed", error)
                        Toast.makeText(
                            context,
                            "Payment failed: ${error.message}",
                            Toast.LENGTH_LONG
                        ).show()
                    }
                )
            )
            checkoutDropInComponent = checkoutDropIn.create()
        }
    }
    
    // Render Drop-in
    if (isLoading) {
        CircularProgressIndicator()
    } else {
        checkoutDropInComponent?.Content(modifier = Modifier.fillMaxWidth())
    }
}

Session configuration (backend)

Enable PayPal in your session request:

// BACKEND: Create a session with PayPal enabled
const sessionRequest = {
  merchant: "MERCHANT-1",
  site: "SITE-1",
  sessionTimeout: 120,
  merchantTransactionId: crypto.randomUUID(),
  transactionMethod: {
    intent: {
      paypal: "Purchase"  // or "Authorisation"
    }
  },
  amounts: {
    currencyCode: "GBP",
    transactionValue: 99.99
  },
  allowedFundingTypes: {
    wallets: {
      paypal: {
        // PayPal configuration from the Unity Portal will be used
        // You can optionally specify allowedFundingOptions here
        allowedFundingOptions: ["paypal", "paylater"]
      }
    }
  },
  allowTransaction: true,
  serviceType: "CheckoutDropIn"
};

Payment flows

Drop-in supports two PayPal payment flows, configured via the intent parameter:

Immediate, single-step payment where funds are captured right away.

import com.pxp.checkout.models.DropInTransactionData
import com.pxp.checkout.models.DropInTransactionIntentData
import com.pxp.checkout.models.DropInPayPalIntentType
import com.pxp.checkout.models.EntryType
import com.pxp.checkout.models.IntentType

transactionData = DropInTransactionData(
    currency = "GBP",
    amount = 99.99,
    entryType = EntryType.Ecom,
    intent = DropInTransactionIntentData(
        card = IntentType.Authorisation,
        paypalDropInIntent = DropInPayPalIntentType.Purchase  // Pay Now flow
    ),
    merchant = "Demo Store",
    merchantTransactionId = { UUID.randomUUID().toString() },
    merchantTransactionDate = { Instant.now().toString() }
)

Use this flow for:

  • Digital products
  • Simple orders with immediate fulfillment
  • Subscriptions
  • Donations

Handling responses

PayPal callback data

When a PayPal payment succeeds, your onSuccess callback receives the same standard result as other payment methods:

onSuccess = { result: DropInSubmitResult ->
    Log.d("Checkout", "Payment details:")
    Log.d("Checkout", "- System transaction ID: ${result.systemTransactionId}")
    Log.d("Checkout", "- Merchant transaction ID: ${result.merchantTransactionId}")
    Log.d("Checkout", "- Payment method: ${result.paymentMethod}") // "Paypal"
    
    // Note: Amount, currency, and other transaction details must be retrieved from backend
    // PayPal authentication is handled internally by PayPal
}

Error handling

Handle PayPal-specific errors:

import com.pxp.checkout.exceptions.BaseSdkException

onError = { error: BaseSdkException ->
    Log.e("Checkout", "Error code: ${error.code}")
    Log.e("Checkout", "Error message: ${error.message}")
    
    // Handle user cancellation
    if (error.message?.contains("cancelled", ignoreCase = true) == true ||
        error.message?.contains("closed", ignoreCase = true) == true) {
        Log.d("Checkout", "User cancelled PayPal payment")
        // Don't show error - user intentionally cancelled
        return@CheckoutDropInConfig
    }
    
    // Handle PayPal-specific errors based on message content
    when {
        error.message?.contains("insufficient funds", ignoreCase = true) == true -> {
            Toast.makeText(
                context,
                "Insufficient funds in PayPal account. Please add funds or use a different payment method.",
                Toast.LENGTH_LONG
            ).show()
        }
        error.message?.contains("restricted", ignoreCase = true) == true -> {
            Toast.makeText(
                context,
                "Your PayPal account is restricted. Please contact PayPal support.",
                Toast.LENGTH_LONG
            ).show()
        }
        error.message?.contains("declined", ignoreCase = true) == true -> {
            Toast.makeText(
                context,
                "Payment declined by PayPal. Please try a different payment method.",
                Toast.LENGTH_LONG
            ).show()
        }
        else -> {
            Toast.makeText(
                context,
                "PayPal payment failed: ${error.message}",
                Toast.LENGTH_LONG
            ).show()
        }
    }
}

Common error scenarios

The following table describes common PayPal error scenarios:

ScenarioHow to detectRecommended action
User cancellederror.message contains "cancelled" or "closed"No alert needed - user action was intentional
Insufficient fundserror.message contains "insufficient"Suggest adding funds or using different payment method
Account restrictederror.message contains "restricted"Direct user to contact PayPal support
Payment declinederror.message contains "declined"Suggest trying different payment method

PayPal errors return descriptive messages rather than specific error code constants. Check the error.message property for error details. You can also use the onCancel callback in methodConfig.global to specifically handle user cancellations.

Backend verification

Always verify PayPal payments on your backend to ensure payment success before fulfilling orders:

import com.pxp.checkout.checkoutdropin.types.DropInSubmitResult

onSuccess = { result: DropInSubmitResult ->
    // Send to backend for verification
    coroutineScope.launch {
        try {
            val response = apiClient.post("/api/verify-payment") {
                contentType(ContentType.Application.Json)
                setBody(mapOf(
                    "systemTransactionId" to result.systemTransactionId,
                    "merchantTransactionId" to result.merchantTransactionId
                ))
            }
            
            if (response.status.value == 200) {
                val verified = response.body<VerificationResponse>()
                if (verified.success) {
                    // Navigate to success screen
                    navController.navigate("success?orderId=${verified.orderId}")
                } else {
                    Toast.makeText(
                        context,
                        "Payment verification failed",
                        Toast.LENGTH_LONG
                    ).show()
                }
            }
        } catch (e: Exception) {
            Log.e("Checkout", "Verification error", e)
            Toast.makeText(
                context,
                "Failed to verify payment",
                Toast.LENGTH_LONG
            ).show()
        }
    }
}

Backend verification code

Use the following backend code to verify PayPal transactions via the PXP API:

// BACKEND: Verify PayPal payment
app.post('/api/verify-payment', async (req, res) => {
  const { systemTransactionId, merchantTransactionId } = req.body;
  
  try {
    // Query the PXP API to get transaction details
    const txnPath = `api/v1/transactions/${systemTransactionId}`;
    const { authHeader, requestId } = createAuthHeader(
      txnPath,
      '',
      process.env.PXP_TOKEN_ID,
      process.env.PXP_TOKEN_VALUE
    );
    
    const transaction = await fetch(
      `https://api-services.pxp.io/${txnPath}`,
      {
        headers: {
          'X-Client-Id': process.env.PXP_CLIENT_ID,
          'X-Request-Id': requestId,
          'Authorization': authHeader
        }
      }
    ).then(r => r.json());
    
    // Verify transaction state
    if (transaction.state !== 'Authorised' && transaction.state !== 'Captured') {
      return res.json({ success: false, error: 'Transaction not successful' });
    }
    
    // Verify merchant transaction ID matches
    if (transaction.merchantTransactionId !== merchantTransactionId) {
      return res.json({ success: false, error: 'Transaction ID mismatch' });
    }
    
    // Verify amount matches expected amount from your order records
    const order = await getOrderByMerchantTransactionId(merchantTransactionId);
    const txnAmount = transaction.amounts?.transactionValue || transaction.amount || 0;
    if (Math.abs(txnAmount - order.amount) > 0.01) {
      return res.json({ success: false, error: 'Amount mismatch' });
    }
    
    // PayPal payments show as PayPal funding type
    const fundingType = transaction.fundingData?.fundingType || 
                       transaction.fundingType || 
                       'Unknown';
    if (fundingType !== 'PayPal') {
      return res.json({ success: false, error: 'Invalid funding type' });
    }
    
    // Fulfill order
    const orderId = await fulfillOrder(transaction);
    
    return res.json({ success: true, orderId });
    
  } catch (error) {
    console.error('Verification error:', error);
    return res.json({ success: false, error: 'Verification failed' });
  }
});

Advanced PayPal flows

PayPal vaulting (one-click payment)

PayPal vaulting allows returning customers to pay with one click by saving their PayPal account. When enabled, customers who have previously connected their PayPal account can skip the PayPal login flow entirely.

How it works

  1. The customer pays with PayPal and agrees to save their account.
  2. PayPal vaults the account and returns a vault ID.
  3. On return visit, onGetShopper provides the shopper ID.
  4. Drop-in enables one-click PayPal payment (no web view).
  5. The customer taps "Pay with PayPal" and payment completes instantly.

Enable PayPal vaulting

Implement onGetShopper to enable vaulting:

import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import com.pxp.checkout.checkoutdropin.CheckoutDropIn
import com.pxp.checkout.checkoutdropin.types.CheckoutDropInConfig
import com.pxp.checkout.components.checkoutdropincomponent.CheckoutDropInComponent
import com.pxp.checkout.models.DropInTransactionData
import com.pxp.checkout.models.DropInTransactionIntentData
import com.pxp.checkout.models.DropInPayPalIntentType
import com.pxp.checkout.models.Environment
import com.pxp.checkout.models.EntryType
import com.pxp.checkout.models.IntentType
import com.pxp.checkout.checkoutdropin.types.DropInSubmitResult
import com.pxp.checkout.exceptions.BaseSdkException
import com.pxp.checkout.services.models.transaction.Shopper

@Composable
fun CheckoutScreen() {
    val context = LocalContext.current
    var sessionData by remember { mutableStateOf<SessionData?>(null) }
    var checkoutDropInComponent by remember { mutableStateOf<CheckoutDropInComponent?>(null) }
    
    // Fetch session from backend (with PayPal enabled)
    LaunchedEffect(Unit) {
        sessionData = fetchSessionFromBackend()
    }
    
    // Initialize Drop-in once session is loaded
    LaunchedEffect(sessionData) {
        sessionData?.let { session ->
            val checkoutDropIn = CheckoutDropIn.initialize(
                context = context,
                config = CheckoutDropInConfig(
                    environment = Environment.TEST,
                    session = session,
                    ownerType = "MerchantGroup",
                    ownerId = "MERCHANT-1",
                    transactionData = DropInTransactionData(
                        currency = "GBP",
                        amount = 99.99,
                        entryType = EntryType.Ecom,
                        intent = DropInTransactionIntentData(
                            card = IntentType.Purchase,
                            paypalDropInIntent = DropInPayPalIntentType.Purchase
                        ),
                        merchant = "Demo Store",
                        merchantTransactionId = { UUID.randomUUID().toString() },
                        merchantTransactionDate = { Instant.now().toString() }
                    ),
                    // REQUIRED: Provide shopper ID to enable PayPal vaulting
                    onGetShopper = {
                        val user = getCurrentUser()
                        Shopper(id = user.shopperId) // e.g., Shopper(id = "shopper-123")
                    },
                    onSuccess = { result: DropInSubmitResult ->
                        coroutineScope.launch {
                            verifyPaymentOnBackend(result)
                            navController.navigate("success")
                        }
                    },
                    onError = { error: BaseSdkException ->
                        Log.e("Checkout", "PayPal payment failed", error)
                        Toast.makeText(
                            context,
                            "Payment failed: ${error.message}",
                            Toast.LENGTH_LONG
                        ).show()
                    }
                )
            )
            checkoutDropInComponent = checkoutDropIn.create()
        }
    }
    
    // Render Drop-in
    checkoutDropInComponent?.Content(modifier = Modifier.fillMaxWidth())
}

When onGetShopper returns a shopper ID, the SDK automatically:

  • Fetches the PayPal user ID token from the PXP API.
  • Enables one-click payment for vaulted PayPal accounts.
  • Handles vault setup during the first payment.

PayPal vaulting configuration

You can configure PayPal vaulting behaviour using methodConfig.paypal.enableOneClickPayment:

CheckoutDropInConfig(
    // ... other config
    methodConfig = DropInMethodConfig(
        paypal = DropInPaypalConfig(
            enableOneClickPayment = true  // Enable PayPal vaulting
        )
    )
)