Skip to content

Cards

Accept card payments with 3D Secure authentication, automatic validation, and saved cards for returning customers.

Overview

Card payments are automatically included in the drop-in when enabled in your session. The drop-in handles all card field rendering, validation, 3D Secure authentication, and payment processing automatically.

Key benefits

  • Card fields appear automatically in the drop-in when cards are enabled in your session configuration.
  • The drop-in handles all card setup, so you don't need card-specific code.
  • Card payments use the same onSuccess and onError callbacks as other payment methods for a unified integration.
  • Automatic field validation for card number, expiry date, and CVC.
  • 3D Secure authentication is handled automatically with native iOS UI.
  • Returning customers can use saved cards when card-on-file is enabled.
  • PCI DSS Level 1 compliant, with no card data stored on your server.

How it works

When a customer pays with a card:

  1. The customer taps "Card" in the payment options list. The card form appears.
  2. The customer enters their card number, expiry date, and CVC.
  3. The drop-in validates the card details in real time.
  4. The customer taps "Pay" and 3D Secure authentication begins (if required).
  5. The customer completes authentication in the native iOS UI.
  6. The payment is processed through Unity.
  7. Your onSuccess callback fires.

Configuration

Card-specific settings are configured through methodConfig.global in the Drop-in configuration. The DropInCardConfig class is currently an empty marker and doesn't have its own properties.

Configuration properties

The following properties in DropInGlobalConfig apply to card payments:

Property Description
acceptedCardNetworks
[DropInCardNetworks]?
Which card brands to accept through card payments. Falls back to session configuration if not specified.

Possible values:
  • .visa
  • .mastercard
  • .amex
  • .unionPay
  • .diners
  • .jcb
  • .discover
allowedCardFundingSource
[DropInCardFundingSource]?
Which funding types to accept (Credit, Debit). Falls back to session restrictions if not specified.

Possible values:
  • .credit
  • .debit

Note: To filter by .prepaid, use CheckoutDropInConfig.restrictions instead: restrictions: Restrictions(card: Restrictions.Card(fundingSources: [.credit, .debit, .prepaid]))
allowedIssuerCountryCodes
[String]?
Allowed card issuer countries as ISO country codes (e.g., ["GB", "US", "FR"]).
onGetConsent
(DropInPaymentMethod) -> Bool
For cards, onGetConsent(.card) provides the consent value used during tokenisation. The SDK renders the card consent checkbox only when a shopper ID is available and the Unity site configuration requires asking for stored-card consent.

Complete example

This example shows a full card configuration using global settings:

methodConfig: DropInMethodConfig(
    // Global settings that apply to card payments
    global: DropInGlobalConfig(
        // Restrict to specific card networks
        acceptedCardNetworks: [
            .visa,
            .mastercard,
            .amex
        ],
        
        // Allow only credit and debit cards
        allowedCardFundingSource: [
            .credit,
            .debit
        ],
        
        // Restrict to cards issued in specific countries
        allowedIssuerCountryCodes: ["GB", "US", "FR"],
        
        // Provide consent value for card tokenisation
        onGetConsent: { paymentMethod in
            // Return consent value for card vaulting
            return paymentMethod == .card
        }
    ),
    
    // Card config is currently an empty marker
    card: DropInCardConfig()
)

Card requirements

Card payments require the following to function correctly:

  • iOS compatibility: iOS 14.0 or higher.
  • HTTPS: Your backend endpoints must be served over HTTPS.
  • Unity Portal configuration: Cards must be enabled and configured in the Unity Portal.
  • Entry type: Cards support .ecom and .moto entry types.
  • 3D Secure: Your merchant account must be configured for 3D Secure authentication.

Card-on-file payments require the shopper to have previously authorised your merchant account. Authorisations must be captured within the time window specified by your payment scheme (typically 7-30 days).

Implementation

Card payments work through the standard implementation, with no card-specific code needed:

import SwiftUI
import PXPCheckoutSDK

struct CheckoutView: View {
    @StateObject private var viewModel = CheckoutViewModel()
    
    var body: some View {
        Group {
            if let dropIn = viewModel.dropIn {
                dropIn.buildContent()
            } else if let errorMessage = viewModel.errorMessage {
                Text(errorMessage)
            } else {
                ProgressView("Loading checkout...")
            }
        }
        .task {
            await viewModel.loadDropIn()
        }
    }
}

@MainActor
final class CheckoutViewModel: ObservableObject {
    @Published var dropIn: CheckoutDropIn?
    @Published var errorMessage: String?
    
    func loadDropIn() async {
        // Fetch session from backend
        guard let sessionData = await fetchSessionFromBackend() else {
            errorMessage = "Failed to create session"
            return
        }
        
        // Initialise Drop-in
        let config = CheckoutDropInConfig(
            environment: .test,
            session: sessionData,
            transactionData: DropInTransactionData(
                amount: Decimal(string: "99.99") ?? 0,
                currency: "GBP",
                entryType: .ecom,
                intent: DropInTransactionIntentData(
                    card: .authorisation
                ),
                merchantTransactionId: UUID().uuidString,
                merchantTransactionDate: { Date() }
            ),
            merchantShopperId: "shopper-123",
            ownerId: "MERCHANT-1",
            onGetShopper: {
                // Provide shopper ID for vaulting
                TransactionShopper(id: "shopper-123")
            },
            onSuccess: { result in
                print("Card payment successful!")
                print("System transaction ID: \(result.systemTransactionId)")
                print("Payment method: \(result.paymentMethod.rawValue)")
                
                // CRITICAL: Verify on backend
                Task {
                    await verifyPaymentOnBackend(result)
                }
            },
            onError: { paymentMethod, error in
                print("Card payment failed: \(error.errorMessage)")
                Task { @MainActor in
                    self.errorMessage = "Payment failed: \(error.errorMessage)"
                }
            }
        )
        
        do {
            let instance = try CheckoutDropIn(config: config)
            await instance.create()
            dropIn = instance
        } catch {
            errorMessage = error.localizedDescription
        }
    }
    
    private func fetchSessionFromBackend() async -> SessionData? {
        // Implementation to fetch session from your backend
        // ...
    }
    
    private func verifyPaymentOnBackend(_ result: DropInSubmitResult) async {
        // Implementation to verify payment
        // ...
    }
}

Session configuration (backend)

Enable cards in your session request. The backend response should include allowedFundingTypes with card configuration that the SDK can decode directly into SessionData:

// BACKEND: Create a session with cards enabled
const sessionRequest = {
  merchant: "MERCHANT-1",
  site: "SITE-1",
  sessionTimeout: 120,
  merchantTransactionId: crypto.randomUUID(),
  transactionMethod: {
    intent: {
      card: "Authorisation"  // or "Purchase"
    }
  },
  amounts: {
    currencyCode: "GBP",
    transactionValue: 99.99
  },
  allowedFundingTypes: {
    // Card configuration from the Unity Portal will be used
    // The SDK expects this response shape:
    cards: ["Visa", "Mastercard", "American Express"],  // Array of card network strings
    cardSchemes: ["Visa", "Mastercard", "American Express"]  // SDK resolves to DropInCardNetworks
  },
  allowTransaction: true,
  serviceType: "CheckoutDropIn"
};

The backend response is decoded into SessionData, which includes card network configuration that Drop-in uses to filter payment methods.

Payment flows

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

Two-step payment: authorise now, capture later (within scheme-specific time windows).

transactionData: DropInTransactionData(
    amount: Decimal(string: "149.99") ?? 0,
    currency: "GBP",
    entryType: .ecom,
    intent: DropInTransactionIntentData(
        card: .authorisation  // Confirm Payment flow
    ),
    merchantTransactionId: UUID().uuidString,
    merchantTransactionDate: { Date() }
)

Use this flow for:

  • Physical products (capture on shipment)
  • Inventory validation needed
  • Final amount may change (shipping, taxes)
  • Complex order workflows

Handling responses

Card callback data

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

onSuccess: { result in
    print("Payment details:")
    print("- System transaction ID: \(result.systemTransactionId)")
    print("- Merchant transaction ID: \(result.merchantTransactionId ?? "N/A")")
    print("- Payment method: \(result.paymentMethod.rawValue)") // "Card"
    
    // Note: Amount, currency, card details must be retrieved from backend
    // 3D Secure authentication data is handled internally
}

Error handling

Handle card-specific errors:

onError: { paymentMethod, error in
    print("Error code: \(error.errorCode)")
    print("Error message: \(error.errorMessage)")
    
    // Handle specific error codes
    let userMessage: String
    switch error.errorCode {
    case "SDK1114":
        userMessage = "Authentication failed. Please try again."
    case "SDK1115", "SDK1116":
        userMessage = "Card payment failed. Please try another card."
    default:
        // Fall back to message-based detection
        if error.errorMessage.localizedCaseInsensitiveContains("declined") {
            userMessage = "Card declined. Please try a different card."
        } else if error.errorMessage.localizedCaseInsensitiveContains("insufficient") {
            userMessage = "Insufficient funds. Please use a different card."
        } else if error.errorMessage.localizedCaseInsensitiveContains("expired") {
            userMessage = "Card expired. Please use a different card."
        } else if error.errorMessage.localizedCaseInsensitiveContains("invalid") {
            userMessage = "Invalid card details. Please check and try again."
        } else if error.errorMessage.localizedCaseInsensitiveContains("3DS") ||
                  error.errorMessage.localizedCaseInsensitiveContains("authentication") {
            userMessage = "Authentication failed. Please try again."
        } else {
            userMessage = "Payment failed: \(error.errorMessage)"
        }
    }
    
    Task { @MainActor in
        showError(userMessage)
    }
}

Common error scenarios

The following table describes common card error scenarios:

ScenarioHow to detectRecommended action
Update allow transaction failederror.errorCode == "SDK1113"Retry the payment or contact support.
Authentication failederror.errorCode == "SDK1114" or message contains "authentication"Suggest trying again or contacting the bank.
Authorisation failederror.errorCode == "SDK1115"Suggest trying a different card.
Card payment failederror.errorCode == "SDK1116"Suggest trying a different card.
Card declinederror.errorMessage contains "declined"Suggest trying a different card.
Insufficient fundserror.errorMessage contains "insufficient"Suggest using a different card or payment method.
Card expirederror.errorMessage contains "expired"Request valid card details.
Invalid carderror.errorMessage contains "invalid"Ask customer to check card details.
Network errorerror.errorMessage contains "network" or "timeout"Retry the payment after a brief delay.

Card errors include both error codes (SDK1114, SDK1115, SDK1116) and descriptive messages. Use error.errorCode for programmatic handling and error.errorMessage for additional context. For production apps, implement robust error handling with retry logic and user-friendly messaging.

Backend verification

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

onSuccess: { result in
    // Send to backend for verification
    Task {
        do {
            let response = try await apiClient.post("/api/verify-payment", body: [
                "systemTransactionId": result.systemTransactionId,
                "merchantTransactionId": result.merchantTransactionId ?? ""
            ])
            
            if response.success {
                // Navigate to success screen
                await MainActor.run {
                    navigateToSuccess(orderId: response.orderId)
                }
            } else {
                await MainActor.run {
                    showError("Payment verification failed")
                }
            }
        } catch {
            print("Verification error: \(error.localizedDescription)")
            await MainActor.run {
                showError("Failed to verify payment")
            }
        }
    }
}

Backend verification code

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

// BACKEND: Verify card 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' });
    }
    
    // Verify funding type is card
    const fundingType = transaction.fundingData?.fundingType || 
                       transaction.fundingType || 
                       'Unknown';
    if (fundingType !== 'Card') {
      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 card flows

Card vaulting (card-on-file)

Card vaulting allows returning customers to pay with a saved card. When enabled, customers who have previously saved a card can use it for faster checkout.

How it works

  1. The customer pays with a card and agrees to save it.
  2. Unity vaults the card and returns a vault ID.
  3. On return visit, onGetShopper provides the shopper ID.
  4. Drop-in displays the saved card for payment.
  5. The customer completes the payment with the saved card (CVC or expiry date may be required depending on your site configuration).

Enable card vaulting

Implement onGetShopper to enable vaulting:

import SwiftUI
import PXPCheckoutSDK

@MainActor
final class CheckoutViewModel: ObservableObject {
    @Published var dropIn: CheckoutDropIn?
    @Published var errorMessage: String?
    
    func loadDropIn() async {
        // Fetch session from backend
        guard let sessionData = await fetchSessionFromBackend() else {
            errorMessage = "Failed to create session"
            return
        }
        
        // Initialise Drop-in
        let config = CheckoutDropInConfig(
            environment: .test,
            session: sessionData,
            transactionData: DropInTransactionData(
                amount: Decimal(string: "99.99") ?? 0,
                currency: "GBP",
                entryType: .ecom,
                intent: DropInTransactionIntentData(
                    card: .purchase
                ),
                merchantTransactionId: UUID().uuidString,
                merchantTransactionDate: { Date() }
            ),
            merchantShopperId: "shopper-123",
            ownerId: "MERCHANT-1",
            // REQUIRED: Provide shopper ID to enable card vaulting
            onGetShopper: {
                let user = getCurrentUser()
                return TransactionShopper(id: user.shopperId) // e.g., TransactionShopper(id: "shopper-123")
            },
            onSuccess: { result in
                Task {
                    await verifyPaymentOnBackend(result)
                    await MainActor.run {
                        navigateToSuccess()
                    }
                }
            },
            onError: { paymentMethod, error in
                print("Card payment failed: \(error.errorMessage)")
                Task { @MainActor in
                    self.errorMessage = "Payment failed: \(error.errorMessage)"
                }
            }
        )
        
        do {
            let instance = try CheckoutDropIn(config: config)
            await instance.create()
            dropIn = instance
        } catch {
            errorMessage = error.localizedDescription
        }
    }
}

When onGetShopper returns a shopper ID, the SDK automatically:

  • Fetches saved cards from the PXP API.
  • Displays saved cards for faster checkout.
  • Handles vault setup during the first payment.

Card vaulting configuration

Card vaulting is enabled by implementing onGetShopper and optionally controlling consent with methodConfig.global.onGetConsent:

CheckoutDropInConfig(
    // ... other config
    merchantShopperId: "shopper-123",
    ownerId: "MERCHANT-1",
    onGetShopper: {
        let user = getCurrentUser()
        return TransactionShopper(id: user.shopperId)  // Required for vaulting
    },
    methodConfig: DropInMethodConfig(
        global: DropInGlobalConfig(
            onGetConsent: { paymentMethod in
                // Provide consent value for card tokenisation
                return paymentMethod == .card
            }
        ),
        card: DropInCardConfig()  // Empty marker
    )
)

3D Secure authentication

3D Secure authentication is handled automatically by the drop-in. When a card requires 3D Secure, the drop-in:

  1. Detects that 3D Secure is required from the payment response.
  2. Launches the native iOS 3D Secure UI.
  3. Guides the customer through authentication (OTP, biometric, etc.).
  4. Processes the authenticated payment.
  5. Fires your onSuccess callback on completion.

No additional code is required for 3D Secure authentication. The drop-in manages the entire flow automatically.

3D Secure UI is rendered using native iOS components and adapts to the authentication method required by the card issuer (OTP, biometric, challenge questions, etc.). The UI is fully PCI DSS Level 1 compliant.

Recurring card payments

For subscriptions and recurring charges, use the .authorisation flow with card vaulting enabled and the recurring transaction field:

transactionData: DropInTransactionData(
    amount: Decimal(string: "9.99") ?? 0,
    currency: "GBP",
    entryType: .ecom,
    intent: DropInTransactionIntentData(
        card: .authorisation  // Use Authorisation for recurring
    ),
    merchantTransactionId: UUID().uuidString,
    merchantTransactionDate: { Date() },
    recurring: RecurringType(
        frequencyInDays: 30,
        frequencyExpiration: "2026-12-31"
    )
)

After the first payment, use the vaulted card token to process subsequent recurring payments via the PXP API without customer interaction.